ASP.NET

Introduction to .NET Framework 4.5.1

https://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx

http://www.tutorialspoint.com/asp.net/asp.net_multi_threading.htm

ADO.NET is a set of classes that expose data access services to the .NET developer. The ADO.NET classes are found in System.Data.dll and are integrated with the XML classes in System.Xml.dll.

There are two central components of ADO.NET classes: the DataSet, and the .NET Framework Data Provider.

Data Provider is a set of components including:

DataSet object represents a disconnected cache of data which is made up of DataTables and DataRelations that represent the result of the command.

The ADO.NET Object Model

What is main difference between GridLayout and FormLayout ?

GridLayout helps in providing absolute positioning of every control placed on the page. It is easier to develop page with absolute positioning because control can be placed any where according to our requirement. But FormLayout is little different only experience Web Developer used this one reason is it is helpful for wider range browser. If there is absolute positioning we can notice that there are number of DIV tags. But in FormLayout whole work are done through the tables.

How to Write to XML File ?

XmlTextWriter textWriter=new XmlTextWriter("filename.xml");

//WriteStartDocument and WriteEndDocument methods open and close a document for writing 

textWriter.WriteStartDocument() 

//write comment 

textWriter.WriteComment("this is my first xml file.") 

textWriter.WriteComment("i'm lovin it") 

textWriter.WriteStartElement("studentDB")//write first element textWriter.WriteStartElement("student") 

textWriter.WriteStartElement("name",""); 

textWriter.WriteString("sourabh");

textWriter.WriteEndElement(); 

textWriter.WriterEndElement();

textWriter.WriteEndDocument(); 

textWriter.Close(); 

Types of Serialization

Serialization can be of the following types:

    Binary Serialization

    SOAP Serialization

    XML Serialization

    Custom Serialization

Binary Serialization

Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically.  The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Convert.ToString can handle null value. Object.ToString() will throw an error if the object is null. 

so its alway best to use Convert.Tostring() when you are converting reference type to string. Value type cannot be null so you can use .ToString() for value types.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

According to MSDN, Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism.

In C#, every type is polymorphic. Types can be used as their own type or as a Object instance, because any type automatically treats Object as a base type.

Polymorphism means having more than one form. Overloading and overriding are used to implement polymorphism. Polymorphism is classified into compile time polymorphism or early binding or static binding and Runtime polymorphism or late binding or dynamic binding.

Compile time Polymorphism or Early Binding

The polymorphism in which compiler identifies which polymorphic form it has to execute at compile time it self is called as compile time polymorphism or early binding.

 

Advantage of early binding is execution will be fast. Because every thing about the method is known to compiler during compilation it self and disadvantage is lack of flexibility. 

Examples of early binding are overloaded methods, overloaded operators and overridden methods that are called directly by using derived objects.

Runtime Polymorphism or Late Binding

The polymorphism in which compiler identifies which polymorphic form to execute at runtime but not at compile time is called as runtime polymorphism or late binding.

 

Advantage of late binding is flexibility and disadvantage is execution will be slow as compiler has to get the information about the method to execute at runtime.

Example of late binding is overridden methods that are called using base class object.

http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C

Polymorphism means same operation may behave differently on different classes.

Example of Compile Time Polymorphism: Method Overloading

Example of Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism

Method Overloading

- Method with same name but with different arguments is called method overloading.

- Method Overloading forms compile-time polymorphism.

- Example of Method Overloading:

class A1

{

void hello()

{ Console.WriteLine(“Hello”); }

void hello(string s)

{ Console.WriteLine(“Hello {0}”,s); }

}

Example of Run Time Polymorphism

Method Overriding

- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.

- Method overriding forms Run-time polymorphism.

- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.

- Example of Method Overriding:

Class parent

{

virtual void hello()

{ Console.WriteLine(“Hello from Parent”); }

}

Class child : parent

{

override void hello()

{ Console.WriteLine(“Hello from Child”); }

}

static void main()

{

parent objParent = new child();

objParent.hello();

}

//Output

Hello from Child.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

http://www.c-sharpcorner.com/Interviews/answer/3499/C-Sharp-net-interview-question-show-different-types-of-collect

http://www.programcall.com/csnet/4/inheritance-and-polymorphism-in-csnet-with-examples.aspx

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

1. Page Level Output Caching

This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.

Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

* VaryByParam can take various "key" parameter names in query string. Also there are other attributes like VaryByHeader, VaryByCustom etc. Please refer to MSDN for more on this.

2. Fragment Caching

Even though this definition refers to caching portion/s of page, it is actually caching a user control that can be used in a base web form page. In theory, if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control. 

Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

<%@ Control Language="C#"%>

<%@ outputcache duration="60" varybycontrol="DepartMentId" %>

<script runat="server">

private int _Departmentid=0;

public int DepartMentId

{

get{return _Departmentid;}

set{_Departmentid =value;}

}

//Load event of control

void Page_Load(Object sender, EventArgs e)

{

lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = " 

+ _Departmentid + "\n";

}

</script>

<asp:Label id="lblText" runat="server"></asp:Label>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:ms="urn:schemas-microsoft-com:xslt" version="1.0" exclude-result-prefixes="msxsl">

  <xsl:output method="xml" indent="yes" />

  <xsl:template match="/OrderDataSet">

    <Orders>

      <xsl:for-each select="OrderTable">

        <Order>

          <LoadNumber>

            <xsl:value-of select="LoadNumber" />

          </LoadNumber>          

        </Order>

      </xsl:for-each>

    </Orders>

  </xsl:template>

</xsl:stylesheet>

<?xml version="1.0" encoding="utf-8"?>

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="OrderDataSet">

    <xs:complexType>

      <xs:sequence>

        <xs:element maxOccurs="unbounded" name="OrderTable">

          <xs:complexType>

            <xs:sequence>

              <xs:element minOccurs="0" name="LoadNumber" type="xs:unsignedInt" />

              <xs:element minOccurs="0" name="SourceSystem" type="xs:string" />              

              <xs:element minOccurs="0" name="ModifiedDate" type="xs:dateTime" />

            </xs:sequence>

          </xs:complexType>

        </xs:element>

      </xs:sequence>

    </xs:complexType>

  </xs:element>

</xs:schema>

public ValidateXmlReturnType ValidateXml(XmlReader xmlReader, string xsdString) {  _ValidationResult = true;  _ErrorMsg = string.Empty;  string validationErrorMsg = string.Empty;  // Set the validation settings.  XmlReaderSettings settings = new XmlReaderSettings();  settings.ValidationType = ValidationType.Schema;  settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;  settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;  settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);         //Add the XML schema to an XmlSchemaSet and add to XmlReaderSettings.  XmlSchemaSet schemas = new XmlSchemaSet();  XmlReader schemaReader = null;  XmlReader newXmlReader = null;  try  {             schemaReader = XmlReader.Create(new StringReader(xsdString));      schemas.Add("", schemaReader);       settings.Schemas.Add(schemas);      newXmlReader = XmlReader.Create(xmlReader, settings);              while (newXmlReader.Read())      {   if (!string.IsNullOrEmpty(_ErrorMsg))   break;      }  }         catch (System.Xml.XmlException xmlException)  {      OnValidationFailed(xmlException.Message);  }  finally  {       if (schemaReader != null)       {   schemaReader.Close();   schemaReader = null;       }     if (newXmlReader != null)     {      newXmlReader.Close();      newXmlReader = null;     }  }  return new ValidateXmlReturnType(_ValidationResult, _ErrorMsg);   }    //Event handler to execute the validation and return the result.   void ValidationCallBack(object sender, ValidationEventArgs e)   {    OnValidationFailed(e.Message);    }    private void OnValidationFailed(string exceptionMessage)   {    if (_ValidationResult != false)    {     _ValidationResult = false;    }    if (!string.IsNullOrEmpty(_ErrorMsg) && !string.IsNullOrEmpty(exceptionMessage))    {     _ErrorMsg += System.Environment.NewLine;    }    _ErrorMsg += exceptionMessage;   }

TransformSourceXmlToTargeXmlUsingXslt

string contractPath = lmsInfo.LMSContractFolderPath + "\\" +      ProcessStatus.Success.ToString() + "\\" +      lmsInfo.LMSOperationName + transactionID + ".xml";  // Load the Xml doc. XPathDocument myXPathDoc = new XPathDocument(contractPath); //mark su add XSL parameter to pass current Datetime as creation time XsltArgumentList xslArg = new XsltArgumentList(); xslArg.AddParam("CreateDate", "", string.Format("{0:MM/dd/yyyy HH:mm:ss}", DateTime.Now)); 

XslCompiledTransform myXslTrans = new XslCompiledTransform(); XmlReader reader = XmlReader.Create(new MemoryStream(new System.Text.UnicodeEncoding().GetBytes(lmsInfo.Xslt)));  // Load the Xslt.  myXslTrans.Load(reader);  string responseFolderPath = this.GenerateXMLFileNameWithPath(transactionID, lmsInfo);  // Create the output stream. XmlTextWriter myWriter = new XmlTextWriter(responseFolderPath, null);  // Do the actual transform of Xml myXslTrans.Transform(myXPathDoc, xslArg, myWriter);  myWriter.Close(); reader.Close();  // Now Copy xml file from LMSResponse folder to LMSArchive folder. FileInfo file = new FileInfo(responseFolderPath); file.CopyTo(lmsInfo.LMSArchiveFolderPath + "\\" + lmsInfo.LMSOperationName + transactionID + ".xml"); file = null;

http://www.4guysfromrolla.com/articles/022305-1.aspx

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication. Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.

 Microsoft® Security Support Provider Interface (SSPI) is the well-defined common API for obtaining integrated security services for authentication, message integrity, message privacy, and security quality of service for any distributed application protocol.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

ArrayList -

1) Namespace System.Collections contain ArrayList ( This namespace is added by default when we we creat any aspx page in C#)

2) Create ArrayList :

ArrayList stringArrayList = new ArrayList();

Here we dont need to specify object type arraylist going to contain,store different type of objects/items/

3) In ArrayList each item is stored as an Object so while reteriving we can get object only.

4) It is like Array of Objects.

List<T> -

1) Namespace System.Collections.Generic List<T> ( we need to add namespace if we want to use Generic Types)

2) Create List<T>:

List<string> stringList = new List<string>();

i.e. List<type> nameOfList = new List<type>(); & type means object type which List<T> going to hold.

3) In List<T> , it can hold/contain only type of object which is mentioned while initialising the List<T>

Just like in above example stringList will only contain object of type string, the type supplied as generic parameter.

4) It is newly added in .Net 2.0 & onwards, fast processing no need of casting explicitly.

Lets see one example.

string first = “First String”;

string second = “Second String”;

int firstInt = 1;

int secondInt = 2;

ArrayList stringArrayList = new ArrayList(); // No need to specify the object type,can store anything.

stringArrayList.Add(first); // string type

stringArrayList.Add(second); // string type

stringArrayList.Add(firstInt); // Can contain any type so no problem in storing int

List<string> stringList = new List<string>(); // Need to specify the object type, will contain only string types.

stringList.Add(first);

stringList.Add(second);

1) Lets consider Case :

stringList.Add(firstInt); // adding int in string type List.

we will get the exceptions below as List need to contain only string types. others are not allowed.

1) ‘The best overloaded method match for ‘System.Collections.Generic.List<string>.Add(string)’ has some invalid arguments’

2) ‘Argument ’1′: cannot convert from ‘int’ to ‘string’

2) Lets consider another case :

string abcd = stringArrayList[1];

Suppose if we try to get an ArrayList item without using the casting then we can get following exception, as arraylist contain Objects only we need to cast as pre our requirments.

We will get Exception –

‘Cannot implicitly convert type ‘object’ to ‘string’. An explicit conversion exists (are you missing a cast?)’

We can avoid it as

string abcd = stringArrayList[1].ToString(); 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

Here is a short example with Integer:

int [] numbers = { 2, 3, 4, 5};

int [] numbersCopy = numbers;

numbersCopy[2] = 0;

Console.WriteLine(numbers[2]);//Display 0

Console.WriteLine(numbersCopy[2]);//Display 0 !!! Both = Same reference

But if you do :

int [] numbers = { 2, 3, 4, 5};

int [] numbersClone = (int[])numbers.clone();

numbersClone[2] = 0;

Console.WriteLine(numbers[2]);//Display 4

Console.WriteLine(numbersClone[2]);//Display 0 !!! Not the same :)

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Collection: - Collections are basically group of records which can be treated as a one logical unit.

.NET Collections are divided in to four important categories as follows.

Indexed based.

Key Value Pair.

Prioritized Collection.

Specialized Collection.

Let’s begin with Indexed based and key value pair.

 

Indexed based: - It helps you to access the value of row by using the internal generated index number by the collection.

Key Value Pair: - It helps you to access value by the user defined key.

Below is the example of country collection for Indexed based and key value pair.

When you want to access India through Index based you have to write like below code.

MessageBox.Show(myarray[0]); //for array MessageBox.Show(mylist[0]);  //for list

Now, when we want to access the same output “India” by Key value pair.

MessageBox.Show(myhash["IND"].ToString()); //for hashtable

Prioritized Collection: -It helps us to get the element in a particular sequence.

Specialized Collection: -It is very specific collections which are meant for very specific purpose like hybrid dictionary that start as list and become hashtable.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Reflection:

                            string executionDirPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                            Assembly a = Assembly.LoadFrom(Path.Combine(executionDirPath, this.TargetListener.CustomDllName + ".dll"));

                            Type aType = a.GetType(this.TargetListener.CustomDllName + "." + this.TargetListener.CustomDllType);

                            object aInstance = Activator.CreateInstance(aType);

boolReturn = (Boolean)aType.InvokeMember("PerformOperation", BindingFlags.InvokeMethod, null, aInstance, args1);

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

All the data types in .net are classified in to value types and reference types.  

Value Types

----------------

Value types include the following:

Reference Types

----------------------

Reference types include the following: