Code Highlighter

Sunday 18 May 2014

Basic ASP.NET Questions


What is the ViewBag object ?
ViewBag object is a member of Controller. It allows to pass the data from the controller to the view.

What is the functionality of the Html.ActionLink  ?
Html.ActionLink is an HTML helper method that comes from the MVC framework. Html.ActionLink renders the HTML links and it has 2 parameters :

  1. Test to display in the link
  2. Action to perform

 What is a strong strongly typed view ?
It's a view that intends to render a specific domain type.
Example :


The view.cshtlm containe the domain model as shown below

@model PartyInvites.Models.GuestResponse

@{
    Layout = null;
}

In ASP.NET MVC where shall we do the input validation ? 
It typically applied in the domain model, rather then in the user interface. ASP.NET MVC supports declarative validation rules defined with attributes from the System.ComponentModel.DataAnnotations.

Example: Validation the email input.

[Required(ErrorMessage = "Please enter your email address")]
[RegularExpression(".+\\@.+\\..+",
ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }

What is the functionality of the Html.ValidationSummary  ?
When there are errors, the Html.ValidationSummary allows to display the error messages defined by the validation attributes.
Example:


What is the MVC convention folder for the CSS style sheets ?
 By convention, the CSS style sheets shall place into the Content folder.

What Model-View-Controller Pattern ?
Models :  it can be view models, domain models, or operations for manipulation of those data.
View : it's the user interface that renders the models
Controllers:  which process the incoming requests, select views to render to the user, perform operations on the model.

The figure below is from the book Pro ASP.NET MVC and it's easy to remember.



What are the LINQ Extension Methods ?


Extension Method Deferred Description
All No Returns true if all the items in the source data match the predicate
Any No Returns true if at least one of the items in the source data matches the predicate
Contains No Returns true if the data source contains a specific item or value
Count No Returns the number of items in the data source
First No Returns the first item from the data source
FirstOrDefault No Returns the first item from the data source or the default value if there are no items
Last No Returns the last item in the data source
LastOrDefault No Returns the last item in the data source or the default value if there are no items
Max
Min
No Returns the largest or smallest value specified by a lambda expression
OrderBy
OrderByDescending
Yes Sorts the source data based on the value returned by the lambda expression
Reverse Yes Reverses the order of the items in the data source
Select Yes Projects a result from a query
SelectMany Yes Projects each data item into a sequence of items and then concatenates all of
those resulting sequences into a single sequence.
Single No Returns the first item from the data source or throws an exception if there are
SingleOrDefault No Returns the first item from the data source or the default value if there are no items, or throws an exception if there are multiple matches
Skip
SkipWhile
Yes Skips over a specified number of elements, or skips while the predicate matches
Sum No Totals the values selected by the predicate
Take
TakeWhile
Yes Selects a specified number of elements from the start of the data source or selects items while the predicate matches
ToArray
ToDictionary
ToList
No Converts the data source to an array or other collection type
Where Yes Filters items from the data source that do not match the predicate




Sunday 24 November 2013

Typescript - Update the TodoMVC sample to use with the backbone and the jquery DefinitelyTypes

Typescript 0.9.1.1 - Update the TodoMVC sample to use the backbone and the jquery DefinitelyTypes 


This blog I will explain how to update the TodoMVC to use with the backbone 0.2.6 and the jquery 0.3.6 DefinitelyTypes.
Since you've come this blog. I very sure that are new to typescript therefore I will go through step by step from the download to the modification of the  typescript and run it.

1. Install TypeScript for the Visual Studio 2012.

You can download the TypeScript for the VS Studio 2012 and 2013 here. It's about 11.9 M and it's a self setup file.  Once it downloaded, double click on the TypeScriptSetup0.9.1.1.exe to install it.

2. Create the TodoMVC TypeScript Projec

Open the the VS 2012 and select from the main menu File -> New-> Project ... The popup below appears and the project Name TSTodoMVC.  Then click the OK button.

By default, it creates a simple runnable sample project. you can run the sample by clicking on the
 play button to run it in the IExplorer browser. You could run it in a different browser by right click on the default.htm file then select the Browse With ... on the context menu.

3. Update the solution with original TodoMVC source code that you can find it here 

  • Delete App.ts, the App.css and default.htm
  • Create the css and  the js folfers.
  • Copy the destroy.png and todos.css to the css folder.
  • Copy the todos.ts to the js folder
  • Copy the index.html

At this point you may have 2 CSS 3.0 errors

To fix the 1st error, change the cursor:normal to cursor:default. To fix the 2nd error, comment out 
 /* -ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#555555,EndColorStr=#222222); */

You can download the entire solution 


4. Install the Backbone and the JQuery DefinitelyTypes

In the steps in the following links :
  • Install the Backbone.DefinitelyTypes 
    • Run the following command in the Package Manager Console
      • PM> Install-Package backbone.TypeScript.DefinitelyTyped
  • Install the JQuery.DefinitelyTypes
    • Run the following command in the Package Manager Console
      • PM> Install-Package jquery.TypeScript.DefinitelyTyped

5. Modify the Todos.ts to use the Backbone and the JQuery DefinitelyTypes

Add the Backbone and the JQuery references at the beginning at the file.

/// <reference path="Scripts\typings\backbone\backbone.d.ts"/>
/// <reference path="Scripts\typings\jquery\jquery.d.ts"/>

Since we refer the above DefinitelyTypes, we shall remove the Backbone and the JQuery in the Todos.ts code.



There are few more modifications, however you can download the entire solution here.

Note: Type cast in the TypeScript is < casting type >

Example:
 this.allCheckbox = <HTMLInputElement> this.$(".mark-all-done")[0]; //casting



Friday 11 October 2013

WCF - Inject the Unity Container into the per call self host service

WCF - Inject the Unity Container into the per call self host service

Sometime you don't want use a singleton for sharing the transient data between per call services.  Therefore you need to use the Unit Container to inject the dependencies to your service. Here is the sample of how to do it.


Main Code :
      UnityServiceHostFactory wFactory = new UnityServiceHostFactory();
 
      try
      {
        ServiceHost wIosServiceHost = wFactory.CreateServiceHostWithType(typeof(DataAccessService));
        wIosServiceHost.Open();
        Console.WriteLine("running on endpoints:");
        foreach (var wServiceEndpoint in wIosServiceHost.Description.Endpoints)
        {
          Console.WriteLine(wServiceEndpoint.Address.ToString());
          Console.WriteLine("running");
        }
      }
 
      catch (Exception ex)
      {
        ... 
     }

UnityServiceHostFactory :

  public class UnityServiceHostFactory : ServiceHostFactory
  {
    private static IUnityContainer mContainer;
    public UnityServiceHostFactory()
    {
// create you container and register all the types
   
      mContainer = new UnityContainer();
      mContainer.RegisterType<DataAccess>();
     ... 
    }
 
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
      return new UnityServiceHost(mContainer, serviceType, baseAddresses);
    }
 
    public ServiceHost CreateServiceHostWithType(Type serviceType, Uri[] baseAddresses)
    {
      return new UnityServiceHost(mContainer, serviceType, baseAddresses);
    }
 
    public ServiceHost CreateServiceHostWithType(Type serviceType)
    {
      return new UnityServiceHost(mContainer, serviceType);
    }
 }
 
UnityServiceHost :
 public partial class UnityServiceHost : ServiceHost
  {
    public UnityServiceHost(IUnityContainer container, Type serviceType, params Uri[] baseAddresses)
      : base(container.Resolve(serviceType), baseAddresses)
    {
    }
 
    public UnityServiceHost(IUnityContainer container, Type serviceType)
      : base(container.Resolve(serviceType))
    {
    }
  }
 
 

WCF – Configure the entire self host service via the app.config only

WCF – Configure the entire self host service via the app.config only

Most the self host samples that your find on the web,  it shows you how to configure the service programmatically.

App.config:

  - The metadata can be access via the http://localhost:8080/DataAccessService/Mex.
  - The service can be access via the net.tcp://localhost:8081/DataAccessService


  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      
      <netTcpBinding>
        <binding   name="IosService_netTcpBinding"  maxReceivedMessageSize="2147483647" receiveTimeout="23:10:00">
          <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
          <security mode="None" />
        </binding>
      </netTcpBinding>
      
      <wsHttpBinding>
        <binding name="IosService_wsHttpBinding"  maxReceivedMessageSize="2147483647" receiveTimeout="23:10:00">
          <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
          <security mode="None" />
        </binding>
      </wsHttpBinding>   
      
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="com_cae.Miss.ProductAdapter.CdbAdapter.DataAccess.DataAccessService">
        <endpoint address ="" binding="netTcpBinding"  
                  bindingConfiguration="IosService_netTcpBinding" 
                  name="Endpoint"
                  listenUriMode="Explicit"
                  contract="com_cae.Miss.ProductAdapter.CdbAdapter.ClientServer.IDataAccessService" />
 
        <endpoint address="mex" binding="mexHttpBinding"  name="MexEndpoint" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <!-- For the metadata -->
            <add baseAddress="http://localhost:8080/DataAccessService/" />
            <!--- For service -->
            <add baseAddress="net.tcp://localhost:8081/DataAccessService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
Main Code :


      try
      {
        ServiceHost wIosServiceHost = wFactory.CreateServiceHostWithType(typeof(DataAccessService));
        wIosServiceHost.Open();
        Console.WriteLine("running on endpoints:");
        foreach (var wServiceEndpoint in wIosServiceHost.Description.Endpoints)
        {
          Console.WriteLine(wServiceEndpoint.Address.ToString());
          Console.WriteLine("running");
        }
      }
 
       catch (Exception ex)
       {
         ...
       }

Saturday 26 May 2012

Installing Windows Server 2008 R2 domain controller in the VMBox - Part 1

Installing Windows 2008 R2 server domain controller in the VMBox - Part 1

Why do we want to setup a domain controller on a VM ?
As a developer,  sometime I need to test the cross domain access, thus it's useful to have a  domain controller on the VM.


1. Download the VMBox from the oracle's web site https://www.virtualbox.org/wiki/Downloads

2. Download the Windows Server 2008 Server R2 64 bits iso file from the Microsoftt website for 180 days-trial.  the file name is 7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso and it's about 3GB.
 note : If your server trial-time is expired. You could extend the trial time by entered the following command at the dos command prompt.  "slmgr -rearm"


3. Run the VMBox

4.  Create the machine : Click on the Machine->New (or Ctrl-N), a popup Create New Virtual Machine appears, click Next.


5. Select the OS and the Version.

6. The next step is to select the memory for your VM.  I selected 4G of memory because I have 12G on my machine.

7. Select the hard disk size



  • Select the harddisk file type, use the default selection (VDI).
  • Select  Dynamically allocated virtual disk type. 
  • Select the  80G hardisk size.


 8. Setting the number of CPU.  By default, only 1 CPU is selected.  We want change to 4 CPUs.
Setting->System->Processor

9. Setting the Display to 128M Video Memory and Enable 2D Video Acceleration.

10. Setting the Network.  Select the Bridged Adapter so your could have access to the internet.

11. Setting the Shared Folder.  Click in the + folder on the right,  Select the folder that your want to share between your PC and the VM. 

Do not forget to select the Auto-mount.



12.  Setting the CD/DVD.  We want to map the Windows Server R2 iso file to the DVD drive.  Select the IDE Controller - Empty DVD, Then click on the DVD Icon on right in the Attributes section. Subsequently, chose the file 7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso




Now you are ready to boot-up your VM and start installing the Windows Server 2008 R2.



13.  Click on the Start button on the Oracle VM VirtualBox Manager. The Windows Server 2008 R2 is loading and start to install on the VM

14. Select English as the language to install.  The installation process will take about 10 minutes.







15. First time login, you need to enter a strong password for the Administrator account.

 "Hello001" 

Configure the Domain Controller

At this point, your Server is liked and Desktop. On start the Initial Configuration Tasks appears for configuring the server.



16. Setting the time zone.

 



Saturday 14 April 2012

WPF - Namespace One-to-Many

You develop WPF applications, you may realize that there are 3 types of namespace as shown below.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:sys="clr-namespace:System;assembly=mscorlib"        
xmlns:mylib1="http://schemas.mycorp.com/mylibrary/2012" 

This blog, I will only discuss about the namespace of type one-to-many and its purpose.
xmlns:mylib1="http://schemas.mycorp.com/mylibrary/2012" 
You develop a WPF library and in your library has many namespaces, if you decide refactoring your library namespace. Off course,you do not want all your client applications have to change their XAML codes. This is the main reason why you should provide one-to-many namespace.

How to do it ?

Example : you have a WPF library that has 3 namespaces : 
  • MyWPFLib.Commands
  • MyWPFLib.Controls
  • MyWPFLib.Pages

All you have to do, it's to add the namespace definitions to the AssemblyInfo.cs
[assembly: XmlnsPrefix("http://schemas.mycorp.com/mylibrary/2012", "mylib")]
[assembly: XmlnsDefinition("http://schemas.mycorp.com/mylibrary/2012", "MyWPFLib.Commands")]
[assembly: XmlnsDefinition("http://schemas.mycorp.com/mylibrary/2012", "MyWPFLib.Controls")]
[assembly: XmlnsDefinition("http://schemas.mycorp.com/mylibrary/2012", "MyWPFLib.Pages")]

You can download the example here.
http://www.4shared.com/zip/ZwX8Wc-x/NameSpace.html




Wednesday 28 March 2012

Debugging JavaScript with VS2010 + Intellisense

If you are a .NET developer and you want to learn JavaScript.  Definitely using VS2010 for debugging your JavaScript is your 1st choice.  Also VS2010 provides  intellisense for JavaScript. You can find more information about the intellinsense here.

Make your IE as a default browser.
Open the IE ->Tools->Internet Options->Programs-> Select "Make default" button.



Enable the Script Debugging Option from the Advanced tab.
deselect the 2 options "Disable script Debugging".



Create an empty web project.


Once you have created your project then add a new html page and name it as "index.htm".


It's  now ready to code your 1st JavaScript with VS2010.  You can copy a sample code from below.
Also do not forget to set the index.htm as the starting page.

<head>
    <title>Debug My JavaScript</title>
</head>
<body>
 
<script type="text/javascript">
<!--
 /*Email Check script credit-JavaScript Kit (www.javascriptkit.com) 200+ free JavaScripts here!*/
    //-->
    function emailcheck(cur) {
        var string1 = cur.email.value;
        if (string1.indexOf("@") == -1) {
            alert("Please input a valid email address!")
            return false
        }
    }
    window.status = "Hello Dac";

</script>
 <form onsubmit="return emailcheck(this)">
    <strong>Enter your email address please:</strong><br>
    <input type="text" size="20" name="email">
    <input type="submit" value="Submit!">
</form>
</body>

You should able to get the intellisense as shown in figure below.



Debugging.
Now, you debug the JavaScript code as you normally debugging the C# code. Set the break point at the line 12 and press the F5.  The IE will appear as the illustrated image below. 



Enter "bad email".  Click on the Submit button, the debugger will stop at the line 12 and you can examine the string1 variable.