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?

Thursday, December 16, 2010

pay per post

Should the ruler thirst around the humane refund?

Wednesday, March 24, 2010

SQL Interview Questions

  • What is a Key?
  • Types of Key?
  • What is Primary Key?
  • What is Secondary Key?
  • What is Unique Key?
  • What is Foreign Key?
  • What is Composite Key?
  • What is Surrogate Key?
  • What is Candidate Key?
  • What is Alternate Key?
  • Difference between Primary & Unique key?
  • Difference between Primary & Alternate & Secondary key?
  • Difference between Primary & Foreign Key?
  • What is the need of Composite key?

Web services interview questions

  • Explain WebMethod Attribute in Asp.Net Web Service.
  • What is the Web service protocol stack?
  • What is SOAP?
  • What is WSDL?
  • What is XML-RPC?
  • What is UDDI?
  • What is DISCO?
  • What is DISCOMAP?
  • What namespaces are imported by default in ASMX files?
  • What are the steps to create a web service?
  • What is the need to create a web service?
  • Can you use User-Defined Types in Web Services?
  • Can two different programming languages be mixed in a single ASMX file?
  • How to perform authentication in webservices?
  • How to handle exceptions in webservices?
  • What is SOAP Exception in webservices?

Tuesday, March 23, 2010

.Net Interview Questions

  • What is MVP model?
  • What is MVC model?
  • Difference between MVC & MVP model?
  • Which model is tightly coupled?
  • Which model is loosely coupled?
  • What is ORM Model?
  • What is full form of ORM?
  • Why ORM?

.Net Interview Questions

  • Difference between string & string builder?
  • How we can create fix size string builder object?
  • Difference between ref & out variable in c#?
  • Difference between server.transfer & response.redirect?
  • What kind of exception is generated by server.transfer & response.redirect?
  • How we can handle exception generated by  server.transfer & response.redirect?
  • Difference between IEnumerable & IEnumerator?

.Net Interview Questions

  • What do mean by Architecture?
  • What is .net  Architecture?
  • What is connection pooling?
  • How connection pooling works?
  • What is max/min size of pool in .net?
  • Can an application work with 0(zero) number of pool?
  • Where we can define pool size?
  • How we can create pools dynamically?
  • What happens with application when max connection pool reach?
  • Mention steps which are required while creating connection between .net & sql for data access?

Friday, July 24, 2009

How to convert string to TitleCase

Call: GetTitleCase("RAJESH GOEL")

using System.Globalization;
using System.Threading;

private string GetTitleCase(string Text)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
return textInfo.ToTitleCase(Text.ToLower());
}

Result : Rajesh Goel

Regex Expressions

Replace all special characters from string using REGEX EXPRESSION

If you want to replace special characters from string, then just need to use below expressio:
Regex.Replace(value, @"[^\w-\/]", "-")

Like:

ReplaceSpecialCharacter("(you don't need to insta/ll the software and you don't need--to register)")

private string ReplaceSpecialCharacter(string value)
{
return Regex.Replace(value, @"[^\w-\/]", "-");
}

Result:
-you-don-t-need-to-insta/ll-the-software-and-you-don-t-need--to-register-

Wednesday, July 22, 2009

Different type of errors in ASP.Net

Object must implement IConvertible


Error Code:
StringBuilder itemNumbers = new StringBuilder();
DataView DV = DS.Tables["Products"].DefaultView;
int DVRowCount = DV.Table.Rows.Count;
if (DVRowCount > 0)
{
foreach (DataRow dr in DV.Table.Rows)
{
sItemNumbers.Append(Convert.ToString(dr["Prod_Id"]));
sItemNumbers.Append(",");
}

ArrayList oArrParam = new ArrayList();
oArrParam.Add(new Parameter("@itemNumbers", itemNumbers, ParamDirection.Input, DbType.String));
}

The problem: you need to convert string builder value to string. The code should look like this:

ArrayList oArrParam = new ArrayList();
oArrParam.Add(new Parameter("@itemNumbers", itemNumbers.ToString(), ParamDirection.Input, DbType.String));}

Monday, July 20, 2009

Claim Code

e6d4ycrgma

Saturday, July 18, 2009

Keyboard shortcuts for ASP.NET

Build keywords
F5 - Start Debugging
Ctrl + F5 - Start Without debugging
Shift + F5 - Stop Debuggig
Ctrl + Shift + B - Builds your project
Ctrl + Break - To stop bild process

Comment keyword
Ctrl+ K +C - Comments Selection
Ctrl+ K + U - Uncomments Selection

Right Click keyword
Shift + F10

Collapse/Expand keyword
Ctrl + M + O - Collapse to Definitions
Ctrl + M + L - Collapse All and Expand All
Ctrl + M + M - Collapse and Expand a Single region

Find keyword
Ctrl-F/Ctrl + Shift + F : Shows "Find" dialog
Ctrl-H/Ctrl + Shift + H : Shows "Replace" dialog
Ctrl-G : Shows "Find" line number dialog

Breakpoint keyword
F9 : Toggle breakpoints
Ctrl + Shift + F9 : Clears all breakpoints
Ctrl + D + B : Open breakpoint window for function - need to specify function name

Windows keyword
Ctrl + D + B : Open breakpoints window
Ctrl + D + I : Open immediate window

Full Screen keyword
Shift + Alt + Enter :- To see full screen view

Scroll forward/backwards
Ctrl-Tab: Scroll forward through open windows
Ctrl-Shift-Tab: Scroll backwards through open windows

Attach the debugger to a process
Ctrl-Alt-P : This is insanely useful for debugging ASP.NET web sites without having to start the project in debug mode

Code/Designer windows
F7 : Show the code windows
Shift-F7 : Show the designer window

Bookmark keyword
Ctrl + B + T : Toggle code bookmark
Ctrl + B + E : Enable bookmark
Ctrl + B + P : Previous bookmark
Ctrl + B + N : Next bookmark
Ctrl + B + C : Clear bookmark

Open windows keyword
F4 :- Opens the Properties window
Ctrl + Alt + X :- Opens the Toolbar window
Ctrl + W + S :- Opens the Solution Explorer window
Ctrl + W + L :- Opens the Server Explorer window
Ctrl + W + C :- Opens the Class Viewer window
Ctrl + Shift + E :- Opens the Resource view window

Toggle character keyword
Ctrl + T : Toggle character

Snippet keyword
Ctrl + K + X - Insert Snippet

Intellisence keyword
Ctrl + Space - Intellisence

Line operations keyword
Ctrl + Enter - Insert a new line above the current line
Ctrl + x/Ctrl + L - Delete current line

Undo/Redo keyword
Ctrl-Z / Ctrl-Y: Undo typing / Redo typing

Navigate Forward/Backward
Ctrl + - : Navigate Backward
Ctrl + Shift + -: Navigate Forward

Friday, July 17, 2009

New Features of Visual Studio 2008 for .NET Professionals

New Features of Visual Studio 2008 for .NET Professionals
1. LINQ Support
2. Expression Blend Support
3. Windows Presentation Foundation
4. VS 2008 Multi-Targeting Support
5. AJAX support for ASP.NET
6. JavaScript Debugging Support
7. Nested Master Page Support
8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
9. Organize Imports or Usings
10. Intellisense Filtering
11. Intellisense Box display position
12. Visual Studio 2008 Split View
13. HTML JavaScript warnings, not as errors
14. Debugging .NET Framework Library Source Code
15. In built Silverlight Library
16. Visual Studio LINQ Designer
17. Inbuilt C++ SDK
18. Multilingual User Interface Architecture - MUI
19. Microsoft Popfly Support
20. Free Tools and Resources
21. We can use for Commercial

Wednesday, July 15, 2009

Features of CLR (Common Language Runtime)

Acronym of CLR is Common Language Runtime. It is heart of the .NET framework. It is the runtime that converts a MSIL code into the host machine language code, which is then executed appropriately. All Language have runtime and it is the responsibility of the runtime to take care of the code execution of the Program. For example, VB6 has MSVBVM60.DLL and Java has Java Virtual Machine etc. Similarly, .NET has CLR. Following are the responsibilities of CLR.

- Support for developer services (profiling, debugging)
In unmanaged code, when a program generates an exception, the kernel suspends the execution of the process and passes the exception information to the debugger by using the Win32 debugging API. The CLR debugging API provides the same functionality for managed code. When managed code generates an exception, the CLR debugging API suspends the execution of the process and passes the exception information to the debugger.

- Code Access Security(CAS)
The common language runtime (CLR) supports a security model called code access security for managed code. In this model, permissions are granted to assemblies based on the identity of the code.

A code group contains a permission set (one or more permissions). Code that performs a privileged action will perform a code access demand which will cause the common language runtime (CLR) to walk up the call stack and examine the permission set granted to the assembly of each method in the call stack. The code groups and permission sets are determined by the administrator of the machine who defines the security policy.

The security policy that determines the permissions granted to assemblies is defined in three different places:
1. Machine policy
2. User policy
3. Host policy

- Exception handling
You can handle following type of exceptions using /clr
1. Structured Exception Handling (SEH).
2. C++ exception handling.
3. CLR exceptions.

A CLR exception is any exception thrown by a managed type.
The System::Exception class provides many useful methods for processing CLR exceptions and is recommended as a base class for user-defined exception classes.

- Code management
The Microsoft .NET Framework has two main components.
1. Common Language Runtime (CLR)
2. .NET Framework class library.

The concept of code management is a fundamental principle of the CLR, and applications that the CLR manages are called "managed applications" or "managed code."

- Application memory isolation
Application Memory Isolation means that applications does not need to worry about allocation/de-allocation of memory, everything will be handled by the CLR. GC is the component in CLR which takes care of memory management.

- Access to metadata (enhanced type information)

- Managing memory for managed objects
One of the major productivity benefits that the common language runtime (CLR) offers developers of managed code are:
1. Garbage Collector (GC) makes sure any memory allocated on the managed heap is cleaned up after it is no longer needed.
2. It saved countless hours of developers while debugging difficult problems arising from memory leaks.
3. It also saves time in released memory, and double-freeing memory.

Garbage collection is a mechanism that allows the computer to detect when an object can no longer be accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called a "finalizer," which is written by the user). Some garbage collectors, like the one used by .NET, compact memory and therefore decrease your program's working set.

- Conversion of IL to native code.

- Interoperation between managed code, COM objects, and pre-existing DLL's (unmanaged code and data)

- Automation of object layout

- Verification of type safety
Type-safe code is code that accesses memory structures only in well-defined ways. For example, given a valid object reference, type-safe code can access memory at fixed offsets corresponding to actual field members. However, if the code accesses memory at arbitrary offsets inside or outside the range of memory that belongs to the object, then it is not type-safe. When assemblies are loaded in the CLR, prior to the MSIL being compiled using just-in-time (JIT) compilation, the runtime performs a verification phase that examines code to determine its type-safety. Code that successfully passes this verification is called verifiably type-safe code.

-
Host Protection Attributes (HPAs)
The CLR provides a mechanism to annotate managed APIs that are part of the .NET Framework with certain attributes that may be of interest to a host of the CLR. Examples of such attributes include:

1. SharedState, which indicates whether the API exposes the ability to create or manage shared state (for example, static class fields).
2. Synchronization, which indicates whether the API exposes the ability to perform synchronization between threads.
3. ExternalProcessMgmt, which indicates whether the API exposes a way to control the host process.

Given these attributes, the host can specify a list of HPAs, such as the SharedState attribute, that should be disallowed in the hosted environment. In this case, the CLR denies attempts by user code to call APIs that are annotated by the HPAs in the prohibited list.

.Net Vs. Java - Similarities

Common Language Infrastructure (CLI - CLI is called the Common Language Runtime or CLR) and .NET languages such as C# and VB have many similarities to Sun's JVM and JAVA. Both are based on a virtual machine model that hides the details of the computer hardware on which programs run. MICROSOFT uses theirs Common Intermediate Language (MSIL - intermediate byte-code) , and SUN uses theirs Java bytecode. On DOTNET byte-code is always compiled before execution, either Just In Time (JIT) or in advance of execution using the ngen.exe utility. With JAVA the byte-code is either interpreted, compiled in advance, or compiled JIT.