Thursday, June 9, 2011

IEnumerator & IEnumerable

Enumerators are helpful in iterating through data. IEnumerator and IEnumerable both exists in System.Collections and works only on non-generic collections. All collections like ArrayList are created by implementing IEnumerable.

With the help of both Interfaces we can create our own collection.
IEnumerable

IEnumerable interface have only one method GetEnumerator() that returns IEnumerator.
1. public IEnumerator GetEnumerator();

IEnumerator

IEnumerator interface have 2 methods and 1 property:
1. void Reset()              --> Method
2. bool MoveNext()      --> Method
3. object Current           --> Property
 
Rest()
Void Rest(), this method resets current location to start point and sets rese value to "-1".
public void Reset()                                          
{                                                                     
    iIndex=-1;                                                   
}                                                                     
 
MoveNext()
bool MoveNext(), this method helps in taking you to the required location in collection and in response returns bool flag value. If MoveNext() method get any value on current location then it will return true otherwise it will return false.

public bool MoveNext()                                  
{                                                                     
    return(++iIndex);                                        
}                                                                    

Current
object Current, this property return element of the collection by specifying location.

public object Current                                       
{                                                                     
    get                                                              
    {                                                                 
         return(Orders[iIndex]);                          
    }                                                                
}                                                                     

Wednesday, June 8, 2011

URL Rewriting in ASP.NET 4.0

URL Rewriting.

1. What is URL Rewriting?

What we do in normal scenerio is, we send some information to page in query string like:
http://www.productsite.com/productdetail.aspx?productid=10001
With the help to "URL Routing" new feature in ASP.NET 4.0 we can write hassel free URL rewriting code very easily. In 4.0 there is no need to write any handle aur module for Rewriting.

By using URL Rewriting we can convert above url to like
http://www.productsite.com/productdetail/10001
In this URL we are passing "10001" information to product detail page with the help of Routing.

The following table shows valid route patterns.

{controller}/{action}/{id}                       /Products/view/10001
{table}/Details.aspx                                /Products/Details.aspx
product/{action}/{entry}                        /product/show/123
{reporttype}/{year}/{month}/{day}       /sales/2008/1/5
{locale}/{action}                                   /US/show
{language}-{country}/{action}              /en-US/show


2. How to use Routing in ASP.NET Form:

protected void Application_Start(object sender, EventArgs e)
{
      RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
     routes.MapPageRoute("",
     "Product/{action}/{productid}",
     "~/productdetail.aspx");
}
MapPageRoute method that take 3 arguments (sting,string,string) is a method of RouteCollection() class. MapPageRoute method create an object to Route and add it to RouteCollection().


3. How to set Default Value:

void Application_Start(object sender, EventArgs e)
{
     RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
     routes.MapPageRoute("",
     "Product/{action}/{productid}",
     "~/productdetail.aspx",
     true,
     new RouteValueDictionary
     {{"productid", "10001"}, {"action", "view"}});
}

MapPageRoute(String, String, String, Boolean, RouteValueDictionary) methos that take 5 arguments.


4. How to set contraints in Routing:

void Application_Start(object sender, EventArgs e)
{
     RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
     routes.MapPageRoute("",
     "Product/{action}/{productid}",
     "~/productdetail.aspx",
     true,
     new RouteValueDictionary
    {{"productid", "10001"}, {"action", "view"}},
    new RouteValueDictionary
    {{"productid", "[0-9]{5}"}});
}

If your URL doesn't match the patter then Route will not handle this request.

There are two ways to define constraints:
1. Regular expressions (While checking Regular expression it calls IsMatch method of Regex, and it will treat expression as case sensitive.)

2. Objects implement the IRouteConstraint interface (It calls Match method of IRouteConstraint interface to validate and Match method will return bool variable as a result to indicate wheather the object is valid or not)


5. How to access query string value on page

    Response.Write(Page.RouteData.Values["productid"]);
6. Key classes that ASP.NET 4.0 use for Routing:

  • Route
  • DynamicDataRoute
  • RouteBase
  • RouteTable
  • RouteCollection
  • RouteCollectionExtensions
  • RouteData
  • RequestContext
  • StopRoutingHandler
  • PageRouteHandler
  • RouteValueDictionary
  • VirtualPathData

Saturday, June 4, 2011

How do you convert a string into an enum


object Enum.Parse(System.Type enumType, string value, bool ignoreCase)

Define Enum:
 
enum Weekday
   {
      Sunday,
      Monday,
      Tuesday,
      Wednesday,
      Thursday,
      Friday,
      Saturday
  }

 Weekday wd = null;
string weekDay = "Monday";

First check is it enum that you are going to convert exists or not, otherwise it will
return an exception:

if (Enum.IsDefined(typeof(Weekday), weekDay))
wd = (WeekDay) Enum.Parse(typeof(Weekday), weekDay, true);
else
Response.Write("Enum does'not exist.");

Sunday, May 29, 2011

New Features in C# 4.0 Framework

List of new features in C# 4.0 framework.
  1. Dynamic programming
  2. Named and optional parameters
  3. Covariance and Contravariance

Thursday, May 26, 2011

How to do FTP in C#

FtpWebResponse ftpResponse = null;

FtpWebRequest ftpRequest = null;

ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + m_Server + "/" + Path.GetFileName(sFileNameWithLocation) + "");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(sUserName, sPassword);

FileInfo fi = new FileInfo(sFileNameWithLocation);
byte[] fileContents = new byte[fi.Length];

using (FileStream fs = fi.OpenRead())
{
    fs.Read(fileContents, 0, Convert.ToInt32(fi.Length));
}

using (Stream writer = ftpRequest.GetRequestStream())
{
    writer.Write(fileContents, 0, fileContents.Length);
}

ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
Response.Write(ftpResponse.StatusDescription);

Write Byte array to a file

public void WriteByteArrayToFile(byte[] bArray, string fileName)
{
    FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(bArray);
    bw.Close();
}



Wednesday, May 25, 2011

Convert/Migrate Web Service to WCF service

Step 1: Create an empty Web Application














Step 2:  Add new Web Service in this project














Now we can see the dummy code that is generated by Web Service default Template.
















Here we have a WebService class inherited from System.Web.Services.WebService. Class also have  a web method “HelloWorld” that returns “Hello World” string.

Step 3: Add reference of System.ServiceModel in your project.















Step 4: Add “ServiceContract” and “OperationContract” on class and method, and add
using System.ServiceModel; on the top of the code




















Step 5: Add WCFService in same project.
















Step 6: Remove WCF Service interface “IWCFService” and Class “WCFService.svc.cs” files.



















Step 7: Right click on .svc and .asmx file and Go to view Markup.

.svc markup view:

< %@ ServiceHost Language="C#" Debug="true" Service="ConvertWebServiceToWCFService.WCFService" CodeBehind="WCFService.svc.cs" %>

.asmx markup view:

< %@ WebService Language="C#" CodeBehind="WebService.asmx.cs" Class="ConvertWebServiceToWCFService.WebService" %>



Step 8: Change .svc and .asmx markup as below


.svc markup view:

< %@ ServiceHost Language="C#" Service="ConvertWebServiceToWCFService.WCFService" %>

.asmx markup view:

< %@ ServiceHost Language="C#" Service="ConvertWebServiceToWCFService.WebService" %>



Step 9: Changes in Web.Config file. Open config file.

Add below settings under tag.



< compilation debug="true" targetFramework="4.0">

< buildProviders>

< remove extension=".asmx"/>

< add extension=".asmx" type="System.ServiceModel.Activation.ServiceBuildProvider, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

< /buildProviders>

< /compilation>

< httpHandlers>

< remove path=".asmx" verb="*" />

< add path="*.asmx" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />

< /httpHandlers>




Add this also in web.config file of service.

< system.serviceModel>


< services>

< service name="MyService" behaviorConfiguration="MyServiceTypeBehaviors">

< endpoint contract="ConvertWebServiceToWCFService.WebService" binding="mexHttpBinding" address="mex" />

< /service>

< /services>

< behaviors>

< serviceBehaviors>

< behavior name="MyServiceTypeBehaviors">

< serviceMetadata httpGetEnabled="true" />

< serviceDebug includeExceptionDetailInFaults="true" />

< /behavior>

< behavior name="">

< serviceMetadata httpGetEnabled="true" />

< serviceDebug includeExceptionDetailInFaults="false" />

< /behavior>

< /serviceBehaviors>

< /behaviors>

< serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

< /system.serviceModel>





Step 10: Finally you can see Conversion is working fine:





Tuesday, May 24, 2011

Design Pattern Interview Questions

1. What are design patterns and why there is a need of design patters?
2. How many types of Design patters are there?
3. What is Singlton pattern?
4. Why we use Singlton pattern?
5. What is Abstract Factory pattern?
6. What is Factory Pattern?
7. Difference between Factory and Abstract Factory pattern?
8. Can we use Static variable in place of Singlton pattern?