Most Common C# and ASP.NET Faqs
by
chaitanya| Views: 522
C#
1. What is indexers
1.solution
In c# introduce new concept is Indexer. This is very useful for some situation. Let as discuss something about Indexer.
• Indexer Concept is object act as an array.
• Indexer an object to be indexed in the same way as an array.
• Indexer modifier can be private, public, protected or internal.
• The return type can be any valid C# types.
• Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.
this [Parameter]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
For Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace Indexers
{
class ParentClass
{
private string[] range = new string[5];
public string this[int indexrange]
{
get
{
return range[indexrange];
}
set
{
range[indexrange] = value;
}
}
}
/* The Above Class just act as array declaration using this pointer */
class childclass
{
public static void Main()
{
ParentClass obj = new ParentClass();
/* The Above Class ParentClass create one object name is obj */
obj[0] = "ONE";
obj[1] = "TWO";
obj[2] = "THREE";
obj[3] = "FOUR ";
obj[4] = "FIVE";
Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n");
Console.WriteLine("\n");
Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]);
Console.WriteLine("\n");
Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n");
Console.WriteLine("\n");
Console.ReadLine();
}
}
}
2.explanation
C# introduces a new concept known as Indexerswhich are used for treating an object as an array. The indexers areusually known as smart arrays in C# community. Defining a C# indexer ismuch like defining properties. We can say that an indexer is a memberthat enables an object to be indexed in the same way as an array.
this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
Where the modifier can be private, public,protected or internal. The return type can be any valid C# types. The'this' is a special keyword in C# to indicate the object of the currentclass. The formal-argument-list specifies the parameters of theindexer. The formal parameter list of an indexer corresponds to that ofa method, except that at least one parameter must be specified, andthat the ref and out parameter modifiers are not permitted.Remember that indexers in C# must have at least one parameter. Otherwise the compiler will generate a compilation error.
The following program shows a C# indexer in action
// C#: INDEXER
using System;
using System.Collections;
class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rajesh";
mc[1] = "A3-126";
mc[2] = "Snehadara";
mc[3] = "Irla";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]);
}
}
The indexers in C# can be overloaded just likemember functions. The formal parameter list of an indexer defines thesignature of the indexer. Specifically, the signature of an indexerconsists of the number and types of its formal parameters. The elementtype is not part of an indexer's signature, nor is the names of theformal parameters. The signature of an indexer must differ from thesignatures of all other indexers declared in the same class. C# do nothave the concept of static indexers. If we declare an indexer static,the compiler will show a compilation time error.
Indexers & Inheritance
Just like any other class members, indexerscan also participate in inheritance. A base class indexer is inheritedto the derived class.
//C#: Indexer : Inheritance
//Author: rajeshvs@msn.com
using System;
class Base
{
public int this[int indxer]
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1[0] = 10;
Console.WriteLine(d1[0]);//Displays 'Base SET Base GET 10'
}
}
Indexers & Polymorphism
A Base class indexer can be polymorphicalyoverridden in a Derived class. But remember that the modifiers likevirtual, override etc are using at property level, not at accessorlevel.
//C#: Indexer : Polymorphism
//Author: rajeshvs@msn.com
using System;
class Base
{
public virtual int this[int index]
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int this[int index]
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1[0]= 10;
Console.WriteLine(b1[0]);//Displays 'Derived SET Derived GET 10'
}
}
Abstract Indexers
An indexer inside a class can be declared asabstract by using the keyword abstract. Remember that an abstractindexer in a class carries no code at all. The get/set accessors aresimply represented with a semicolon. In the derived class we mustimplement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract indexer in action.
//C#: Indexer : Abstract
//Author: rajeshvs@msn.com
using System;
abstract class Abstract
{
public abstract int this[int index]
{
get;
set;
}
}
class Concrete : Abstract
{
public override int this[int index]
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1[0] = 10;
Console.WriteLine(c1[0]);//Displays 'SET GET 10'
}
}
Indexers & Properties
1. An index is identified by it's signature. But a property is identified it's name.
2. An indexer is always an instance member, but a property can be static also.
3. An indexer is accessed through an element access. But a property is through a member access.
Conclusion
The indexer is one of the key concepts of C#and are very interesting aspects of the language. I've given you enoughinformation to use indexer in your code and shown you some examples
2. Diff b/w procedure and index
Difference between Property and Indexer in C#
Posted by Rajesh Kumar on April 16, 2009
Indexers are like properties. Except for the differences shown in the following table, all the rules that are defined for property accessors apply to indexer accessors also.
Actual Difference are:
Property Indexer
Allows methods to be called as if they were public data members. Allows elements of an internal collection of an object to be accessed by using array notation on the object itself.
Accessed through a simple name. Accessed through an index.
Can be a static or an instance member. Must be an instance member.
A get accessor of a property has no parameters. A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicit value parameter. A set accessor of an indexer has the same formal parameter list as the indexer, and also to the value parameter.
Supports shortened syntax with Auto-Implemented Properties (C# Programming Guide).
Does not support shortened syntax.
This entry was posted on April 16, 2009 at 9:48 am and is filed under .Net. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
3. What is oopes------check it later
4. What is difference b/w class and object------check it later
5. Polymorphism and inheriantance and encaplisation---chek later
6. Difference between overloading and over riding—check later
7. Difference b/w interface and abstraction---check later
8. What is generic
9. hi,
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations
Generics Overview
*
Use generic types to maximize code reuse, type safety, and performance.
*
The most common use of generics is to create collection classes.
*
The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
*
You can create your own generic interfaces, classes, methods, events and delegates.
*
Generic classes may be constrained to enable access to methods on particular data types.
*
Information on the types used in a generic data type may be obtained at run-time by means of reflection.
Sample :-
// Declare the generic class
public class GenericList
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList list1 = new GenericList();
// Declare a list of type string
GenericList list2 = new GenericList();
// Declare a list of type ExampleClass
GenericList list3 = new GenericList();
}
}
second example
Why Generics?
Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time.
By allowing you to specify the specific types acted on by a generic class or method, the generics feature shifts the burden of type safety from developer to the compiler. There is no need to write code to test for the correct data type, because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
Also Generics got rid of disadvantage of array list by avoiding the type casting.
Let us go through the simple example with usage of Generics.
Implementation of Generics
The first step in generics is to create the list of generic template for which the class is applicable.
Let us take an example of creating Generic collection using the simple bank requirement below. Requirement is to create the collection of either Current Bank account or Savings bank account.
Create two classes.
1. Savings bank account
2. Current Bank account
SavingsBank.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericImplementation
{
class SavingsBank
{
protected string name;
protected int age;
private const float MIN_AMT_LMT = 10000;
private float accBalance;
public SavingsBank(string AccName, int age, string opType, float balanceAmt)
{
this.Name = AccName;
this.Age = age;
if (opType.ToLower().Equals("credit"))
{
this.DoCredit(balanceAmt);
}
else
{
this.DoDebit(balanceAmt);
}
}
public string Name
{
get
{
return name;
}
set
{ name = value;
}
}
public int Age
{
get
{
return age;
}
set
{ age = value;
}
}
public float TotalBalance
{
get
{
return accBalance;
}
set
{
accBalance = value;
}
}
public void DoCredit(float credBal)
{
TotalBalance = TotalBalance + credBal;
}
public void DoDebit(float debBal)
{
if (TotalBalance - debBal > MIN_AMT_LMT)
{
TotalBalance = TotalBalance - debBal;
}
else
{
throw new Exception("Balance should not be less than minimum amount " + MIN_AMT_LMT.ToString());
}
}
public override string ToString()
{
return " Account name :" + this.Name + " Age:" + this.age.ToString() + " Balance : " + this.TotalBalance.ToString();
}
}
}
Current Bank A/C:
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericImplementation
{
class CurrentBank
{
protected string name;
protected int age;
private float accBalance;
private const float MIN_AMT_LMT = 20000;
public CurrentBank(string AccName, int age,string opType,float balanceAmt)
{
this.Name = AccName;
this.Age = age;
if (opType.ToLower().Equals("credit"))
{
this.DoCredit(balanceAmt);
}
else
{
this.DoDebit(balanceAmt);
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public float GetCreditLimit
{
get
{
return MIN_AMT_LMT;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public float TotalBalance
{
get
{
return accBalance;
}
set
{
accBalance = value;
}
}
public void DoCredit(float credBal)
{
TotalBalance = TotalBalance + credBal;
}
public void DoDebit(float debBal)
{
if (TotalBalance - debBal > MIN_AMT_LMT)
{
TotalBalance = TotalBalance - debBal;
}
else
{
throw new Exception("Balance should not be less than minimum amount " + MIN_AMT_LMT.ToString());
}
}
public override string ToString()
{
return " Account name :" +this.Name + " Age:" +this.age.ToString() + " Balance : " + this.TotalBalance.ToString();
}
}
}
Now create a Generic bank account collection which can hold the collection of either Savings Bank account or Current bank account.
Generic Bank Collection:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace GenericImplementation
{
class GenericBankCollection : CollectionBase
{
public void Add(AccountType GenericObject)
{
InnerList.Add(GenericObject);
}
public void Remove(int index)
{
InnerList.RemoveAt(index);
}
public AccountType Item(int index)
{
return (AccountType)InnerList[index];
}
}
}
Usage:
Now we can use the Generic bank collection to hold either the savingsBankAccount or CurrentBankAccount collection.
Program.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericImplementation
{
class Program
{
static void Main(string[] args)
{
GenericBankCollection sbAccs = new GenericBankCollection();
sbAccs.Add(new SavingsBank("Sriram",34,"credit",1000));
sbAccs.Add(new SavingsBank("Saik",30,"debit",1000));
GenericBankCollection curAccs = new GenericBankCollection();
curAccs.Add(new CurrentBank("Mohan", 34, "credit", 1000));
curAccs.Add(new CurrentBank("Krishna", 30, "credit", 1000));
System.Console.WriteLine("Savings Accounts");
System.Console.WriteLine("=========");
foreach (SavingsBank savingsBank in sbAccs)
{
System.Console.WriteLine(savingsBank.ToString());
}
System.Console.WriteLine("Current Accounts");
System.Console.WriteLine("=========");
foreach (CurrentBank CurrentBank in curAccs)
{
System.Console.WriteLine(CurrentBank.ToString());
}
System.Console.ReadLine();
}
}
}
10. What is delegate
we can create a variable to point out the function.
If we want to use delegates , first we have to create parameters.
//create a delegate variable
string Function function Reference;
//store a reference to a matching procedure
FunctionReference=TranslateEnglishtoFrench;
private StringTranslateEnglishtoFrench(String English)
{
//code
}
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.
11. What is data reader and dataset---from nodes
12. Dataset and serialization
Serializing DataSets is a known problem in the development community. As everyone knows DataSet will be serialized only into xml irrespective of the formatter which is used.Due to the circular reference we can’t serialize and pass the DataTable to a web service in .Net 1.1(These issues have been solved in .Net 2.0). When we serialize a DataSet it will be serialized into the DiffGram format which is a very expensive scheme.
Mr.Ravindra vupula explained a method to effectively serialize the dataset with his DataSetSurrogate class.Mr.Dino Espisito introduced the concept of ghost serializer which dramatically reduces the complexities of Data Set .
Here I used a simple method to serialize Data Set. The class will be having one array list and two array members and it is marked as serializable.Serializing the class can be effectively done without any of the issues that is associated with Data Set.
[Serializable]
public class template
{
private ArrayList _data=new ArrayList();
private string[] _columns;
private string[] _types;
public ArrayList Data
{
get
{
return _data;
}
set{
_data = value;
}
}
public string[] Cols
{
set
{
_columns=value;
}
}
public string[] Types
{
set{
_ types=value;
}
}
}
Code for serialization is as follows.I used lzocompressor to compress the resultant binary data.lzocompressor is written in unmanaged code but is much faster than the available compressors written in managed code.
public byte[] SerializeData(DataTable dtInput)
{
template temp=new template();
object[][] jar=new object[dtInput.Rows.Count][];
BinaryFormatter bi=new BinaryFormatter();
for(int d=0;d {
jar[d]=dtInput.Rows[d].ItemArray ;
temp.Data.Add(jar[d]);
}
int colCount=dtInput.Columns.Count;
string[] ColName=new string[colCount];
string[] ColType=new string[colCount];
int k=0;
foreach(DataColumn dc in dtInput.Columns)
{
ColName[k]=dc.ColumnName;
ColType[k]=dc.DataType.FullName ;
k++;
}
temp.aCols= ColName;
temp.aTypes=ColType;
byte[] retBytes;
using(MemoryStream ms1=new MemoryStream())
{
bi.Serialize(ms1,temp);
retBytes=ms1.GetBuffer();
}
return retBytes;
}
Deserialization is the reverse process of this and that we can do easily like this.
13. Sterilization and deserlizations.
Introduction
In simple words, we can say an object conversion in text stream is serialization and text stream conversion in object of a class is called deserialization. Or we can say XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.
Let's say I have a complex object which has a hierarchy of classes. Now in case we need XML stream from this object, we will go for serialization. In the same manner, we have XML string and we want to convert this in a class and object format, we will go for deserialization.
Why Serialization and Deserialization
Let's say we have a very complex object and we need XML format for our XSLT rendering on HTML page. Then we have one option that we will write a XML file in the disk after parsing object variable and than load the XML file in XmlDocument object. But is it really a good approach? No, of course not. Why so. This is because in large applications, we have so many users and we will be writing files for every one. This will take lots of space as well as it is risky that might be files are shared among the users or any human being can read that file.
So what do we do now? Yes at this time, go with serialization, get an XML string and just load it to XmlDocument. This will be done in code.
This can be implemented with web services. When we have created a proxy of any web service and we need to send and receive response, it is very beneficial.
How Do We Achieve This
First note that for serialization and deserialization, we need to use System.Xml.Serialization, because we need to use XmlSerialization class which is provided in System.Xml.Serialization.
To understand this, we assume one example of Category and Items. We have two classes. One is Category and another is Items. Category has CategoryID, Category Name and Array of Item. While Item has Item ID, Item Name, Item Price and Item Quantity in Stock.
Collapse | Copy Code
public class Category
{
private int _CatID;
private string _CatName;
private Item[] _Item;
public int CateboryID
{
get
{
return _CatID;
}
set
{
_CatID = value;
}
}
public string CategoryName
{
get
{
return _CatName;
}
set
{
_CatName = value;
}
}
public Item[] Item
{
get
{
return _Item;
}
set
{
_Item = value;
}
}
}
Collapse | Copy Code
public class Item
{
private int _ItemID;
private string _ItemName;
private int _ItemPrice;
private int _ItemQtyInStock;
public int ItemID
{
get
{
return _ItemID;
}
set
{
_ItemID = value;
}
}
public string ItemName
{
get
{
return _ItemName;
}
set
{
_ItemName = value;
}
}
public int ItemPrice
{
get
{
return _ItemPrice;
}
set
{
_ItemPrice = value;
}
}
public int ItemQtyInStock
{
get
{
return _ItemQtyInStock;
}
set
{
_ItemQtyInStock = value;
}
}
}
Let’s First Understand Serialization
In our application, we have serialization function which is called by our click event or whenever this is required. In serialization, we have created one object of Category class and another is Item. Category holds one test category “Phone” and then it creates an array of Item class and stores to Category.Item.
Collapse | Copy Code
private void Serialization()
{
Category Cat = new Category();
Cat.CateboryID = 1;
Cat.CategoryName = "Phone";
Item[] Itm = new Item[5];
for (int i = 0; i < 5; i++)
{
Itm[i] = new Item();
Itm[i].ItemID = i;
Itm[i].ItemPrice = i * 10;
Itm[i].ItemQtyInStock = i + 10;
Itm[i].ItemName = " Item Name : " + i.ToString();
}
Cat.Item = Itm;
XmlSerializer ser = new XmlSerializer(Cat.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, Cat); // Here Classes are converted to XML String.
// This can be viewed in SB or writer.
// Above XML in SB can be loaded in XmlDocument object
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
}
Here Ser is the object of System.Xml.Serialization.XmlSerializer class. It gets the Type of Category class object by Cat.GetType(). ser.Serialize takes two parameters, one is string writer like a target object and another is Cat that is source object. This converts or Serializes Cat object and stores stream into a writer object. Now object is converted into XML string and we can find that by using stringbuilder’s object. Like sb.ToString(). This string can be loaded in XML document for further traversing.
Let’s have look at Deserialization
In our application, we have Deserialization function which is called by our click event or whenever this is required. In deserialization, we have created one object of Category class.
Collapse | Copy Code
protected void DeSerialize(string XmlString)
{
Category Cat = new Category();
XmlDocument doc = new XmlDocument();
doc.LoadXml (XmlString);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(Cat.GetType());
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is, e.g.:
Category myObj = (Category)obj;
Now Ser
}
XMLString for DeSerialization
Collapse | Copy Code
1
Phone
0
Item Name : 0
0
10
1
Item Name : 1
10
11
2
Item Name : 2
20
12
3
Item Name : 3
30
13
4
Item Name : 4
40
14
In the above code, we are passing one XML string. This will be converted into a form of object. Here XML string is loaded into XmlDocument object and then XmlNodeReader is reading from it. Now XmlSerialize object is created and we let it know the type of object by Cat.GetType(). Now Ser object knows that it has to convert XML into an object of Category Type. Now ser.Deserialize(reader) takes XML from reader object and converts into an Object. Later this object is cast into category. If we add this object into watch and view, we will find that it has created the class hierarchy.
Example:2
In this article, I am going to show how to Serialize and DeSerialize an object (can be a collection object or an object) into XML format using ASP.NET System.Xml.Serialization.XmlSerializer class.
Introduction
Before I explain how to Serialize and DeSerialize an object, let me tell you why to serialize. We should serialize an object if we want to store the object instance into the disk or we want to store the object into Session or Cache (storing serialized object into Cache or Session works faster than storing the object directly) or pass the object between applications regardless of which platform they have hosted on and technology they are built in.
Now why to use XML Serialization? As XML is an open standard, XML stream can be processed by any application, as needed regardless of platform. XML Serialization coverts (Serializes) the public fields and properties of an object, or parameters and return values of method, into an XML stream.
Background
Required namespace to Serialize and DeSerialize an object in this artilce are:
1. System.IO
2. System.Xml
3. System.Xml.Serialization
In order to show how to Serialize and DeSerialize an object, I will create a class called MyClass that will have two public variable named name and address. My code for this class is as follows
public class MyClass
{
public string name = string.Empty;
public string address = string.Empty;
}
Setting values for the public variables
I have set this class value as following
MyClass myClass = new MyClass();
myClass.name = "Sheo Narayan";
myClass.address = "Washington DC, US";
How to Serialize an Object
To Serialize and object, we need few instances of the in-built classes. So lets first create an instance of a XmlDocument class from System.Xml namespace. Then create an instance of XmlSerializer class from System.Xml.Serialization namespace with parameter as the object type. Now just create an instance of the MemoryStream class from System.IO namespace that is going to help us to hold the serialized data. So all your instances are there, now you need to call their methods and get your serialzed object in the xml format. My function to Serialize an object looks like following.
///
/// Serialize an object
///
///
///
private string SerializeAnObject(object obj)
{
System.Xml.XmlDocument doc = new XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
try
{
serializer.Serialize(stream, obj);
stream.Position = 0;
doc.Load(stream);
return doc.InnerXml;
}
catch
{
throw;
}
finally
{
stream.Close();
stream.Dispose();
}
}
This is a generic function and you can use this function to pass any type of object that can be serialized, even you can serialize a collection object. This method will return a string that is nothing but our serialized object in XML format. I will call my above function like this
string xmlObject = SerializeAnObject(myClass);
My class will look like following after serialization (XML contents).
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Sheo Narayan
Washington DC, US
How to DeSerialize an Object
To DeSerialize an object you need an instance of StringReader, XmlReader and XmlSerializer class in order to read the xml data (Serialized data), read it into XmlReader and DeSerialize it respectively. So in brief my function to DeSerialize the object looks like following.
///
/// DeSerialize an object
///
///
///
private object DeSerializeAnObject(string xmlOfAnObject)
{
MyClass myObject = new MyClass();
System.IO.StringReader read = new StringReader(xmlOfAnObject);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType());
System.Xml.XmlReader reader = new XmlTextReader(read);
try
{
myObject = (MyClass)serializer.Deserialize(reader);
return myObject;
}
catch
{
throw;
}
finally
{
reader.Close();
read.Close();
read.Dispose();
}
}
This function return an object so to covert that object into my class I will have to unbox it. In order to avoid boxing and unboxing, you can simply specify your class name as a parameter to these functions. To get my class from serialized xml I will call above function like following and extract its properties or use in the way i want.
MyClass deSerializedClass = (MyClass) DeSerializeAnObject(xmlObject);
string name = deSerializedClass.name;
string address = deSerializedClass.address;
14. What is private and public an assemble from our site merithub
15. Gac
The Global Assembly Cache or the popular acronym GAC refers to the machine-wide code cache in any of the computers that have been installed with common language runtime. The GAC or the Global Assembly Cache in .NET Framework acts as the central place for registering assemblies.
All running applications that constitute development environments such as Web Matrtix, Visual Studio.NET, etc., can all use the registered assemblies. The registering process of COM components in the server where ASP application are running is similar to adding an assembly to the Global Assembly Cache and the difference is that adding an assembly in Global Assembly Cache is much easier when compared to the act of registering COM components in a server with ASP applications.
In the first step you need to get the assemblies installed in the Global Assembly Cache for an effective sharing of assemblies. It is highly recommended to keep assembly dependencies separately and only in case of unavoidable necessity or an unambiguous need for sharing should you keep all the assemblies in the application directory itself. Further, there is no necessity for you to get all your assemblies installed in the Global Assembly Cache so as to make the assemblies accessible to COM interrupts or unmanaged code.
There are many ways with which you can install an assembly into the Global Assembly Cache and one such way is using an installer that is compatible with the Global Assembly Cache. Besides using the best method of using a Global Assembly Cache compatible installer for deploying assemblies, you can also make use of a tool that has been specifically developed for installing the assemblies into the Global Assembly Cache and the popular SDK is one such Global Assembly Cache tool developed for .NET Framework. Another easy method of installing assemblies into the Global Assembly Cache is through using the drag and drop option in Windows Explorer.
In any organisation, LAN administrators are vested with the responsibility of controlling access to various files and folders in WINNT directory by users and such LAN administrators accord read, write and execute permissions to users depending upon their hierarchy and roles in the organisation. LAN administrators make use of access control list that is available within the operating system and when the Global Assembly Cache is installed in the WINNT directory, the said Cache will inherit the access control list fully. You, as an administrator or a person responsible for the security of files, have to ensure that only people who have administrative privileges alone are able to access and delete files from the Global Assembly Cache.
You also need to ensure that you provide a strong name for the assemblies installed in the Global Assembly Cache, and note to perform all the integrity checks without fail on all files that constitute the installed assembly whenever you add or remove any assembly to or from the Global Assembly Cache. The main purpose of the carried out integrity check is to ensure that the files or the assemblies in the Global Assembly Cache are not tampered with, either intentionally or unintentionally.
16. Explain validation controls -- from textbox
17. User and custom control
http://support.microsoft.com/kb/893667
18. How to acces textbox from masterpage in webpage
19. Access textbox value from user control in to web form
Sol response.redireact(“from name.aspx”,true)
In properties postback(url form1.aspx);
Go to secondpage
Textbox txt=previouspage.findcontrol(txtfirst name);
20. Wt is navigation controls---check it in textbxook
21. Diff is structure and class
The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.
When we create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.
It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values.
It is an error to initialize an instance field in a struct.
There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.
A struct is a value type, while a class is a reference type.
Example :2
Functionally structures and classes are similar. In fact, you can use structures in almost exactly the same way that you use classes. The only formal difference between a class and a structure is that in a class the members are private by default, while in a structure they are public by default.
So for example:
class sample
{
private:
int data;
public:
void fun()
{
// some code
}
};
is similar to
struct sample
{
private:
int data;
public:
void fun()
{
// some code
}
};
Though in principle we can use a structure at every place where a class is used, in most situation programmers prefer to use structures to group data, and classes to group both data and functions.
22. Menu control
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/navigation/menu.aspx
http://msdn.microsoft.com/en-us/library/ecs0x9w5.aspx
23. How to revers a string
24. Wt is aschronization
This article was contributed by ChandraMohan Lingam.
Environment: ASP.NET, C#
Introduction
Have you ever used ASP.NET Application data caching functionality? Have you run into situations when data in the cache was inconsistent or was just not what you expected? The chances are you are running into synchronization issues when using the cache. An ASP.NET cache object has an application-wide scope and allows you to share data with several instances of the same page or multiple pages across the application. To be beneficial, the cache needs to be accessible to all the pages and to be really useful, there should be some control on who is updating the cache. If too many threads update the contents of a particular key, data will be corrupted.
Sample Application Install
1. Unzip CacheSync.zip to C:\Inetpub\WWWRoot\CacheSync.
2. Create a virtual directory CacheSync in IIS and point to C:\Inetpub\WWWRoot\CacheSync.
3. This sample needs access to the NorthWind database. Update the connection string in Web.config:
4.
Synchronization Issues—Simple Demo (SimpleDemo.aspx)
To demonstrate the synchronization issues, let's consider a simple example. We are going to store a list of values in the cache from one instance of the page and read the data from another instance of page. Assume that the process to update the cache takes a couple of seconds (to simulate the delay in making the database call and some time-consuming processing of data). When the cache is being updated by one thread, any thread can potentially read inconsistent data.
Open the page SimpleDemo.aspx from two instances of the browser. From one instance, call the "Update Cache" method and from the other instance of the browser, call the "Read" method.
private void btnWrite_Click(object sender, System.EventArgs e)
{
Cache["Key"] = "empty";
Thread.Sleep(5000); //simulate a delay
Cache["Key"] = System.DateTime.Now;
}
private void btnRead_Click(object sender, System.EventArgs e)
{
txtOut.Text = Cache["Key"].ToString () ;
}
It is clear from the above example that cache data can be in an invalid state. Allowing threads to read this invalid data can result in unpredictable application behavior.
The cache access behavior we want is to allow multiple threads to read the cache simultaneously but restrict the write access to one thread.
Solution 1—Lock the Writes (SynchronizationLockWrites.aspx)
Let's bring some order to the write operation. The .NET framework provides a synchronization primitive called "lock". This allows a thread to acquire a lock on an instance of an object. What this means is that only one thread can acquire a lock on the object and other threads have to wait until the original thread releases the lock. Now, let's modify the cache update code to include locking. This sample pulls a list of product names from the Northwind database after locking the cache object. Please update the connection string.
Note: Acquiring a lock directly on the caching object is not recommended and will prove to be disastrous in terms of performance.
private void UpdateCacheFromDB()
{
lock(Cache)
{
Cache.Remove ("Key");
ArrayList arData = new ArrayList ();
...
// Read from northwind database and update arData arraylist.
...
// Simulate a delay
Thread.Sleep (5000);
Cache.Insert ("Key", arData);
}
}
If you run the SynchronizationLockWrites.aspx sample again, you will notice that we haven't eliminated the problem yet. All we have made sure of is that only one thread can call the cache update method and other update calls will be queued. When some thread is writing in the cache, it is still possible for other threads to read the data.
So, let's redefine our cache behavior:
1. Multiple threads can read cache data simultaneously.
2. Only one thread can update the cache at any time.
3. When a thread is updating the cache, all the threads that want to read the cache data should wait until the update is complete.
Solution 2—Reader/Writer Locks (SynchronizationReaderWriter.aspx)
The .NET framework provides another thread synchronization primitive called Reader Writer locks. If you look at MSDN help for reader/writer locks, it "Defines the lock that implements single-writer and multiple-reader semantics." It is perfect because it meets all our requirements. It allows simultaneous reads and one write. And when a write is happening, no other thread can read the cache. Now, let's rewrite the cache update and cache read methods.
private void UpdateCache()
{
try
{
// Acquire writer lock
rwl.AcquireWriterLock (10000);
try
{
if (!CacheExpired)
{
return;
}
Cache.Remove ("Key");
ArrayList arData = new ArrayList ();
...
// Read from northwind database and update arData arraylist.
...
// Simulate a delay. Remove in production code
Thread.Sleep (5000);
Cache.Insert ("Key", arData);
LastRefreshTime = System.DateTime.Now;
}
finally
{
// Release writer lock
rwl.ReleaseWriterLock ();
}
}
catch (Exception ex)
{
throw ex;
}
}
// Cache Read method
private void btnRead_Click(object sender, System.EventArgs e)
{
if (CacheExpired)
{
UpdateCache();
}
try
{
rwl.AcquireReaderLock (10000);
try
{
...
// Read cache
...
}
finally
{
rwl.ReleaseReaderLock ();
}
}
...
}
// Verify whether the cache data is stale
private bool CacheExpired
{
get
{
DateTime currentTime = System.DateTime.Now;
TimeSpan ts = currentTime.Subtract (LastRefreshTime);
return (ts.TotalSeconds < 0 || ts.TotalSeconds >
ApplicationConfiguration.RefreshInterval);
}
}
This solution uses a time stamp to determine when the cache was last refreshed. It uses a web.config "CacheRefreshInterval" configuration to determine whether the cache is stale. You may wonder whether you really need to store the time stamp information. Why not use cache expiration policy that is available in the cache framework? The problem with that approach is that you have to really look at the cache to determine whether the cache has data for a specific key. This will once again open up a can of worms because some other thread can potentially be in the process of updating the values for the key.
Now, let's run the sample again. If you click on the "update cache" method from one page and click on "read cache" from another page, the read page actually waits for the update to complete. This is perfect because the cache access is totally controlled and the data is guaranteed to be valid (assuming all downstream databases and applications are working correctly). This implementation is much robust and the read method automatically refreshes the cache if the data is stale.
But, the big problem in this approach is that the code is really messy and getting too complex. In addition, you need to make sure the locks are acquired and released correctly. If you don't release the lock properly or acquire locks in the wrong order, the application will deadlock and go into an inconsistent state.
If you are using a cache to store different types of data (for example, a list of products, a list of sales tax by state, and so forth), you really have to use different instances of reader/writer locks to make the application scalable. If you use one instance of reader/writer lock to control access to all the cache data, a thread updating product list will force a thread reading sales tax by state to wait.
One option is to move all this cache update and read logic to a base class and derive all the pages from the base class. The problem in taking this approach is that the base class will get really heavy and any change to the base class can potentially have a negative impact on the other pages.
Solution 3—Proper Locking Using a Lock Construct (SynchronizationLock.aspx)
Let's consider another solution for solving this problem. The previous solution was too complex to use. Let's attempt a simpler solution using locks. In this approach, we are going to use locks and timestamps to control access to the cache. We use flags to verify whether the cache has expired; if it has, the update cache method will be called.
In this solution, we are going to acquire a lock on a static string variable when updating the cache. The only purpose of this string variable is to help in synchronization. It is much more scalable than acquiring locks directly on the cache object.
private void UpdateCache()
{
lock(lockString)
{
if (!CacheExpired)
{
return;
}
Cache.Remove ("Key");
ArrayList arData = new ArrayList ();
...
// Read from Northwind database and update arData arraylist.
...
// Simulate a delay. Remove in production code
Thread.Sleep (5000);
Cache.Insert ("Key", arData);
LastRefreshTime = System.DateTime.Now;
}
}
private void btnRead_Click(object sender, System.EventArgs e)
{
if (CacheExpired)
{
UpdateCache();
}
object obj = Cache.Get ("Key");
if (obj == null)
txtOut.Text = "Cache is empty";
else
{
txtOut.Text = "";
lstOutput.DataSource = (ArrayList) obj;
lstOutput.DataBind ();
}
}
This option behaves similarly to the previous solution, but with reduced complexity.
Solution 4—Using Utility Classes and an External Cache (SynchronizationConsumer.aspx)
Using an ASP.NET cache has a drawback; that drawback is that you can use the cache only for Web applications. If you have a Windows service or a window application, you need some other mechanism to maintain the cache information.
The Microsoft Caching Application block is a potential solution that will work for a variety of .NET solutions. The problem with the MS Caching application block is that it carries a lot of overhead and has a lot of features that may not be useful for your application. So, if you want a lightweight caching layer that offers high performance at the cost of limited features, march ahead because we are going to build one. This approach moves the cache synchronization logic to a dedicated class and the consumers don't have to worry about synchronization issues.
The generic singleton cache class bizCache is implemented in bizCache.cs. The bizProducts class is responsible for pulling data from the Northwind database and keeping the cache up to date. It is also responsible for handling all synchronization issues. This class is implemented in bizProducts.cs. Any .NET application that wants to use the bizProducts class can do so with a single line of code and not worry about synchronization issues.
// Sample consumer
private void btnRead_Click(object sender, System.EventArgs e)
{
lstOutput.DataSource = bizProducts.GetInstance
().GetproductTypes ();
lstOutput.DataBind ();
}
Here we have consolidated all the caching logic into a class. This class does not depend on ASP.NET and can be used in all .NET applications.
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption
25. How to get identity value in sql server
26. Wt is member ship concept and logic concept
http://www.4guysfromrolla.com/articles/121405-1.aspx
27. Wt is http handler
http://www.15seconds.com/issue/020417.htm
http://support.microsoft.com/kb/307985#1a
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=392
28. Wt is http module
http://weblogs.asp.net/fmarguerie/archive/2004/11/18/265719.aspx
http://www.c-sharpcorner.com/UploadFile/hemantkathuria/ASPNetHttpModules11262005004251AM/ASPNetHttpModules.aspx
29. Wt is data class---bllayer
30. Wt are collection in .net
1. Array list
2. Stack
3. Que
4. Hash table
31. How many ways we can handle error handling concepts in asp.net
32. How to get browse by using javascript
Navigate.appversion
33. Wt are the .net authentication
http://msdn.microsoft.com/en-us/library/ff647070.aspx
http://authors.aspalliance.com/aspxtreme/webapps/aspnetauthentication.aspx
34. Wt is hippa
35. Wt are function in javascript and methods
36. Diff between char and archer
http://www.orafaq.com/faq/what_is_the_difference_between_varchar_varchar2_and_char_data_types
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=46345
37. Wt is stored procedure
A stored procedure is a group of SQL statements compiled into an execution plan and stored under a unique name in the database. It is then executed as a unit. Stored procedures in SQL Server and Oracle are similar to queries in Access. However, stored procedures are much more flexible and powerful than queries,
38. User defined functions
Auser-defined function (UDF) is a prepared code segment that can accept parameters, process some logic, and then return some data. According to SQL Server Books Online, UDFs in SQL Server™ 2000 can accept anywhere from 0 to 1024 parameters, although I must confess I have never tried to pass 1024 parameters into a UDF. Another key characteristic of UDFs is that they return a value. Depending on the type of UDF, the value can be used by the calling routine to continue processing its data. Thus, if a UDF returns a single value (a scalar value), the calling routine can use that value anywhere a standard variable or a literal value can be used. If a UDF returns a rowset, the calling routine can loop through the rowset, join to it, or simply select columns from it.
http://msdn.microsoft.com/en-us/magazine/cc164062.aspx
39. Diff between stored procedure and functions
The Text property exposes the Transact-SQL or other script
that defines the referenced Microsoft? SQL Server? 2000
database object.
The FunctionName property specifies the function name to call in the Microsoft? ActiveX? script associated with a script task or step.
40. Wt is a cursor
A cursor is a set of rows together with a pointer that identifies a current row.
In other word, Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, its like recordset in the ASP and visual basic.
Typical syntax of cursor is
DECLARE @fName varchar(50), @lName varchar(50)
DECLARE cursorName CURSOR -- Declare cursor
LOCAL SCROLL STATIC
FOR
Select firstName, lastName FROM myTable
OPEN cursorName -- open the cursor
FETCH NEXT FROM cursorName
INTO @fName, @lName
PRINT @fName + ' ' + @lName -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursorName
INTO @fName, @lName
PRINT @fName + ' ' + @lName -- print the name
END
CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor
http://www.mssqlcity.com/Articles/General/UseCursor.htm
41. Wt is trigger
http://www.go4expert.com/forums/showthread.php?t=15510
42. Wt is index
http://www.mssqltips.com/tip.asp?tip=1206
http://www.simple-talk.com/sql/learn-sql-server/sql-server-index-basics/
http://odetocode.com/articles/70.aspx
43. Wt are database default
44. Primary key and unique key
The column holding the primary key constraint cannot accept null values.whereas colum holding the unique constraint can accept null values assume that t3 is a table with two columns t1 having primary key constraint and t2 having unique constraint if u try to insert null into t2 it will accept that values whereas column t1 will not accept null
45. Quarry analyzer
46. Diff b/w where and where having
Having clause is usually used with Group By clause although it can be used without itoo. 'Having' is just an additional filter to 'Where' clause.Where' clause applies to the individual rows whereas 'Having' clause is used to test some condition on the group(usually aggregate methods) rather than on individual rows.
http://www.codeproject.com/KB/database/Where_Vs_Having_Clause.aspx
47. Wt is joins
http://www.mssqltips.com/tip.asp?tip=1667
http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/
48. Wt is views
Sol:--
http://www.sql-server-performance.com/articles/dev/views_in_sql_server_p1.aspx
http://www.sql-server-performance.com/articles/dba/view_basics_p1.aspx
http://www.ilopia.com/Articles/SQLServer/Views.aspx