serving the solutions day and night

Pages

Showing posts with label interview. Show all posts
Showing posts with label interview. Show all posts

Tuesday, August 16, 2011

ASP.NET Custom Errors(customErrors) and URL Mappings (urlMappings)

URL Mappings
  1. Open web.config file. (see MSDN)
  2. Create new urlMappings section within the system.web section.
  3. <urlMappings enabled="true">
    <add url="~/contactus.aspx" mappedUrl="~/index.aspx" />
    </urlMappings>
  4. If user types contactus.aspx, page mapped to the index.aspx.
  5. This approach won't work if you have 100 of pages to map.
  6. Best solution is to use regular expressions, but ASP.NET does not support. SEE
    URL Rewriting

Friday, June 10, 2011

ISNULL VS COALESCE

For example Production.Product table records
ClassColorProductNumber
cl1NullNull
cl2NullNull
Nullco3Null
Nullco4Null
NullNullpn5
cl6co6Null
cl7co7pn7


Sunday, May 8, 2011

Debug Directive

If the code is only for development environment not in the live or release environment use Debug Directive or Conditional attribute For exmple, Some of the code only run while in debugggin mode, but you don't want to shift to production server or code to run while in live

If the application/compilation running in the debug mode, then the debug code will execute, but if you complied the same code in the release mode, then debug code will not execute.

In Debug environment, output is
If Debug
No If
Conditional Debug
No Conditional

Saturday, September 18, 2010

C# - Program Structure, Data Types, Type Casting (Conversion)

Program Structure
//the using keyword is used to include the System namespace in the program.
using System;
//the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld.
namespace HelloWorldApplication
{
   //a class declaration, the class HelloWorld contains the data and methods
   class HelloWorld
   {
      // the mehod declaration
      void Print()
      {
//Comments
/*...*/
//
      }
   }
}
C# is case sensitive.
All statements and expression must end with a semicolon (;).

Data Types
Value types 
- value type variables can be assigned a value directly.
- bool, byte, char, decimal, double, float, int, long, sbyte, short, uint, ulong, ushort
- get the exact size of a type or a variable - sizeof(int)
Reference types
- The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. in other words, they refer to a memory location.
- Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.
- object, dynamic, and String.
- object obj = 100; //it will assign ar comiple time
- dynamic d = 100; //it will assign at run time
- String s ="C# code"; or @"c# code";
Pointer types (Unsafe Codes)
- store the memory address of another type.
- char* cptr;

Type Conversion (Type Casting) -  converting one type of data to another type, 2 forms
  - Implicit type conversion
  - performed by in a type-safe
  - int i = 123456789;
   long l = il
  - Derived d = new Derived();
   Base b = d;
  - Explicit type conversion
  - conversions are done explicitly  by users using the pre-defined functions. Explicit conversions require a cast operator.
  - double d = 1234.67;
   int i= (int)d; // 1234
  - type conversion methods -   ToBolean, ToByte, ToChar, ToString()
  - int i = 75; i.ToString();  

C# - System.Reflection

System.Reflection -  Reflection objects are used for obtaining type information (attribute, assembly, late binding methods & properties  at run time.

namespace UnitTestVM
{
    [TestClass]
    public class ReflectionClass
    {
        public static int Id;
        public static string Name;

        public static void ReflectionMethod()
        {
            Type type = typeof(ReflectionClass); // type pointer
            Debug.WriteLine("Fields Info");
            FieldInfo[] fields = type.GetFields(); // Obtain all fields
            foreach (var field in fields) // Loop through fields
            {
                string name = field.Name; // attribute name
                object obj = field.GetValue(null); // attribute value
                System.Type typ = obj.GetType();  //attribute type
                Debug.WriteLine(name + " = " + obj + ", " + typ );
            }

            Debug.WriteLine("Assembly Info");
            System.Reflection.Assembly info = typeof(System.Int32).Assembly;
            Debug.WriteLine(info); //get assembly information

            Debug.WriteLine("Custom Attributes");
            System.Reflection.MemberInfo member = typeof(ReflectionClass);
            object[] att = member.GetCustomAttributes(true);
            for (int i = 0; i < att.Length; i++) Debug.WriteLine(att[i]);
           
            Debug.WriteLine("Method Info");
            MethodInfo[] mi = type.GetMethods();
            for (int i = 0; i < mi.Length; i++) Debug.WriteLine(mi[i]);
           
            Debug.WriteLine("Member Info");
            MemberInfo[] memi = type.GetMembers();
            for (int i = 0; i < memi.Length; i++) Debug.WriteLine(memi[i]);
           
            Debug.WriteLine("Property Info");
            PropertyInfo[] pi = type.GetProperties();
            for (int i = 0; i < pi.Length; i++) Debug.WriteLine(pi[i]);
        }
    }

 
    [TestClass]
    public class SOAPTest
    {
        [TestMethod]
        public void ReflectionTestMethod()
        {
            ReflectionClass.Id = 123;
            ReflectionClass.Name = "C#";
            ReflectionClass.ReflectionMethod(); // Invoke reflection methods

        }
    }
}  

Fields Info
Id = 123, System.Int32
Name = C#, System.String
Assembly Info
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Custom Attributes
Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute
Method Info
Void ReflectionMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Member Info
Void ReflectionMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Void .ctor()
Int32 Id
System.String Name
Property Info

Friday, September 10, 2010

C# - Generics, Boxing, Unboxing

Generics
- C# is a strongly typpe language, when using C# you should declare a type prior to storing data in it.
- Generics types to eliminate redundant code, type safety, code re-usability and performance.
- create generic interfaces, classes, methods, events and delegates.
- Generic can be defined by putting the <T> sign after the class or method name. instead of "T" you can use any word.
- Generic data type obtained at run-time by using reflection.
- Generics allow you to write a class or method that can work with any data type.
- System.Collection.Generic namespace contains Collection<T>, Dictionary<TKey, TValue>, List<T>, Queue<T>, Stack<T>

Type Safety Example
ArrayList obj = new ArrayList();
obj.Add(50);
obj.Add("Dog");
obj.Add(new TestClass());

foreach(int i in obj) Console.WriteLine(i);
//the code will compile, but run time iteration will through 'InvalidCastException' occurred when it print "Dog", bcz it is not integer, the code will print 50.

GenericClass<int> intObj = new GenericClass<int>();
intObj.setItem(0, 50);
intObj.setItem(1, "Dog"); //compiler error, the compiler doesn't compile the code.

Performance
Generics are faster than other collections such as ArrayList. In non-generic colloection, boxing and unboxing overhead when a value type is converted to reference type and vice-versa.

ArrayList  obj = new ArrayList();
obj.Add(50);    //boxing- convert value type to reference type
int x= (int)obj[0]; //unboxing

GenericClass<int>, an int type is generated dynamically from the compiler, boxing and unboxing no longer occurs.

GenericClass<int> obj = new GenericClass<int>();
obj.Add(50);    //No boxing
int x= obj[0]; // No unboxing

Code reuse - A Generic class can be defined once and can be instantiated with many different types.
GenericClass<int> intObj = new GenericClass<int>();
GenericClass<char> charObj = new GenericClass<char>();        

Generic Class Example
using System;
using System.Collections.Generic;

namespace GenericClassApplication
{
   public class GenericClass<T>
   {
      private T[] obj = new T[5]; // define an Array of Generic type with length 5
   
      public T getItem(int index)
      {
         return obj[index];
      }
   
      public void setItem(int index, T value)
      {
         obj[index] = value;
      }
   }
 
   class Program
   {
      static void Main(string[] args)
      {
//instantiate generic with int
         GenericClass<int> intObj = new GenericClass<int>();
         for (int i = 0; i < 5; i++) intObj.setItem(i, i*2);
         for (int i = 0; i < 5; i++) Console.WriteLine(intObj.getItem(i)); //0 2 4 6 8
       
         //instantiate generic with char
         GenericClass<char> charObj = new GenericClass<char>();      
         for (int i = 0; i < 5; i++) charObj.setItem(i, (char)(i*2));
         for (int i = 0; i < 5; i++) Console.WriteLine(charObj.getItem(i));
      }
   }
}


Generic Methods Example
using System;
using System.Collections.Generic;

namespace GenericMethodApplication
{
   class Program
   {
      static void Swap<T>(ref T a, ref T b)
      {
         T temp;
         temp = a;
         a = b;
         b = temp;
      }
   
      static void Main(string[] args)
      {
         int a=10, b=20; //a = 10, b = 20
Swap<int>(ref a, ref b); //a = 20, b = 10

         char i = 'I', j ='J';
         Swap<char>(ref i, ref j); //i = 'J', j = 'I'
      }
   }
}

Generic Delegates Example
using System;
using System.Collections.Generic;

delegate T GenericDelegate<T>(T n);
namespace GenericDelegateApplication
{
   class DelegateClass
   {
      static int n = 10;
      public static int Sum(int i)
      {
         n += i;
         return n;
      }
   
      public static int Times(int i)
      {
         n *= i;
         return n;
      }
      public static int getValue()
      {
         return n;
      }
   
      static void Main(string[] args)
      {
         //create delegate instances
         GenericDelegate<int> gd1 = new GenericDelegate<int>(Sum);
         GenericDelegate<int> gd2 = new GenericDelegate<int>(Times);
       
         gd1(5); //calling the methods using the delegate objects,
         getValue(); //15
       
         gd2(2);
         getValue(); //30
      }
   }
}

Boxing - Boxing is used to store value types in the garbage-collected heap. A referece type is allocated on the heap.
int i = 123;
object o = i; //implicit conversion of a value type to the reference type (object).

stack heap

i
-----
| 23 |
-----
int i=123;

o
---                -----
|     |--------->  |int |
---                |----|
object o =i;     |123 |
       -----

Unboxing -  an explicit conversion from the reference type(object) to a value type. A value type is allocated on the stack
int j = int(o);

j
-----
| 23 |
-----
int j =(int)o;

Friday, April 23, 2010

C# Questions

struct vs Class
  • structs are value types that can contain data and functions
  • structs are value types and do not require heap allocation.
  • structs directly store their data in the struct, classes store a reference to a dynamically allocated object.
  • structs are useful for small data structures
  • structs can affect performance
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • A struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • With classes, multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable.
  • With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • structs do not support user-specified inheritance, and they implicitly inherit from type object
Public struct PointStruct
{
 public int x;
 public int y;

 public PointStruct(int x, int y)
 {
  this.x = x;
  this.y = y;
 }
}

static void Main(string[] args)
{
 PointStruct ps = new PointStruct();
 ps.x = 10;
 ps.y = 10;
 Console.WriteLine(“Initial struct values are “ + ps.x +”, “+ ps.y);
 ModifyStructPoint(ps);
 Console.WriteLine(“After ModifyStructPoint, struct values are “ + ps.x +”, “+ ps.y);
}

void ModifyStructPoint(PointStruct newStruct)
{
 newStruct.x = 20;
 newStruct.y = 20;
 Console.WriteLine(“Inside ModifyStructPoint()”);
 Console.WriteLine(“Modified values are “ + newStruct.x +”, “+ newStruct.y);
}

Initial struct values are 10,10
Inside ModifyStructPoint()
Modified values are 20,20
After ModifyStructPoint, struct values are 10,10
class PointClass
{
 public int x;
 public int y;

 public PointClass(int x, int y)
 {
 this.x = x;
 this.y = y;
 }
}

static void Main(string[] args)
{
 PointClass pc = new PointClass(10,10);
 Console.WriteLine(“Initial class values are “ + pc.x +”, “+ pc.y);
 ModifyClassPoint(pc);
 Console.WriteLine(“After ModifyClassPoint, class are “ + ps.x +”, “+ ps.y);
}

void ModifyClassPoint(PointStruct newPoint)
{
 newPoint.x = 20;
 newPoint y = 20;
 Console.WriteLine(“Inside ModifyClassPoint()”);
 Console.WriteLine(“Modified values are “ + newPoint.x +”, “+ newPoint.y);
}

Initial class values are 10,10
Inside ModifyClassPoint()
Modified values are 20,20
After ModifyClassPoint, struct values are 20,20

Sunday, April 4, 2010

C# Code

C# Functions
<%@ Page CodeBehind="about_us.aspx.cs" Language="c#" AutoEventWireup="false" Inherits="localhost.about_us" %>

#region "Member Variables"
private int intUserID;
private string strSalutation;
private string strFName;
#endregion "Member Variables"

Saturday, April 3, 2010

ASP.NET State Management - Viewstate VS Session Variables


ASP.NET State Management - Viewstate VS Session Variables

ViewState

vscount.aspx
private int count;
protected void Page_Load(object sender, EventArgs e)
{
    count = Convert.ToInt32(ViewState["count"]);
}

protected void btnCount_Click(object sender, EventArgs e)
{
    count++;
    ViewState["count"] = count;
    lblView.Text = ViewState["count"].ToString();
}

protected void btnView_Click(object sender, EventArgs e)
{
    Response.Redirect("sesview.aspx");
}

ASP.NET State Management

ASP.NET State Management
A Web application is stateless. For example, by default if a user enters information into a text box on an HTML Web page, that information is sent to the server. However, it is not returned to the browser in the response. ASP.NET help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:

  1. View state
  2. Control state
  3. Hidden fields
  4. Cookies
  5. Query strings
  6. Application state
  7. Session state
  8. Profile Properties

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways.

Application state, session state, and profile properties all store data in memory on the server.


Extension Methods, DataSet & DataReader

Extension methods help you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method.

For example, let us assume Car.dll is the 3rd party DLL and source is not available.
Car Class Library - Details.CS
namespace Car
{
    public class Details
    {
        public string Wheel(string cartype)
        {
            if (cartype=="CORROLA")
                return "Two";
            if (cartype == "JEEP")
                return "Four";
            else
                return "No Wheel";
        }
    }
}