"The CTS distinguishes between two fundamental categories of data types – value types and reference types.
Reference types (including String and Object, as well as arrays and most user-defined types such as
classes and interfaces) store only a reference to their data on the stack – the data itself is stored in a different area of memory known as the heap."
Value Type and Refrence "The new copy goes to that function and new stogare for that is created.the original value is not changed.Stored on the stack.
Where as an instance of a reference type represents a pointer or reference to the data (stored on the heap).In refrence type only refrence goes to that place the original value get changed. Stored on the heap."
Boxing and Unboxing "Boxing is process of converting value type to refrence type.
Unboxing is process of converting refrence(object) to value type"
Type Conversation "Implicit conversation the conversation is automatically done like int to bit,float to int.
Explicit conversation the conversation is done explicitly done.by Convert.toInt32"
Modifiers List
New Hide base class method of the same signature.
Public Acess from anywhere
protected Within that class and inherieted class
internal With in the same assembly.
private Only with in that scope
internal protected same assembly and inhereted class
static shared by all & no instance is required
virtual Overriden by derived class(Must be Overlodded),gives the permission to the derived class to modify the base class features in that derived class.
abstract Difine the signature but don't implement.An abstract class is a class that cannot be instantiated. Its purpose is to act as a base class from which other classes may be derived.
override Method override virtule and abstract method
sealed Mehod cannt be overedden(inherited)
extern Implemented externally,in different language
Method parameter without using ref,out and parm value of the variable will not be retained when post back
value paremeter The value of the actual parameter that is passed by value to a method is not changed by any changes made to the corresponding formal parameter with in the body of the method. Public stitic void change(int m)
Ref parameter It does not create any new storage area.It only pass the refrence.Value changed in the method will change the value .Ex void change(ref int m)
OutputParemeter Simmiler to the ref parm. ,don't create any space.When formal paramert is declared as out ,parameter in the calling method also declared as out. Ex void add(out int x) { x=100 } int m;output( out m);
Parameter arrays Can Define no. of argument using what we know at parameters.Ex void add(Params int[] x) { }
Array Represent simmiler type of data. Ex. One-dimention,two-dimention,Jagged array. Object System.Array class Ex int[,] age= new age[2,3];
"int[] intArray = new int[3];
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
"
"Can array store data of diffrent type?
No,But can be achived by the object array"
Array list Ability to grow dinamically.Two method Sort() method in the alphabtic order and To sort in reverse order, apply Sort() then Reverse() method .
Ary.CopyTo() vs Clone "Array.copy store in data and structure.
Array.clone store in only structure."
String & String Builder "String are IMMutable Means we cannot modify the string{System.String }, string str=""abc""+""drf""+""ghi"".
here there are 4 string means every addition to the string will create new instance of string in te heap..
"
"SringBuild Are Mutable can modify ,grow dynamically.StringBuilder is better
than string{System.Text};Add on the same instance.
Ex StringBuilder sb=new StringBuilder();
sb.Append(""ram""); or sb.insert(""Sd"");"
Ascent: String when added, new string inststance is created.
Static Class Only staic member declared,Cant be instantiated,No instance contructor,They are seald
"The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors(declare instance default)
"
Structures "Simmiler to class.They are light weight than class, Simple, Easy to copy,
Allocated and De-allocated Automaticaly.It have perameterized constructor only,No Distructor,No inheritance,No New, Sored on Stack
Ex
struct MyStruct{
public int x;
public int y;
pubic MyStrut(int i) {
x=y=i; //Parameterized constructor only,No inheritance(But interface),no distructor
}
}
"
"class MyClient{
public static void Main() {
MyStruct ms = new MyStruct(10);
ms.x = 10;
ms.y = 20;
}
}"
"Similarity between structure and class
Both have constructor but ,Event ,Property ,fields ,Method,Delegate,interface but struct need cant have paramenter less cinstructor etc.
"
"Diffrence between structure and class
1. Structure are value type so stored on stack.. Class are reference type stored on heap So class can be declared as “new" & object created.Class deallocated by the GC.
2. Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
3. Class have distructor but struct don't have.
4. Object are not destroyed by the GC in structure since value type but in class by GC."
"Struct StudentRecord {
public string name;
public float gpa;
public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}"
"Do not define a structure unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (integer, double, so on).
It has an instance size smaller than 16 bytes.
It is immutable.
It will not have to be boxed frequently.
EX:
StudentRecord stu = new StudentRecord(""Bob"", 3.5f);
StudentRecord stu2 = stu;
stu2.name = ""Sue"";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue"
Abstract An abstract class is a class that cannot be instantiated. Its purpose is to act as a base class from which other classes may be derived.
Interfaces An interface is a special type of abstract class. It provides the signature, but no implementation of all its members. Therefore, an interface cannot define data fields, constructors,static metds, and constats. Only instance methods, events, properties, and indexers are permitted, and of course, must be abstract. Like an abstract class
Interface Abstract
All method are public Can be restricted by private
No method body Can have method body,but not in the abstract method.`
Multiple Inheritance Single
Instant created No instant(new)
Generalized Not
Difficult to change,Add value afer making Easy here,by making private.
All method ,event , property ,index are compulsary inhereted not
Generalization,All method compusary added? All the method not to be inherited from the abstract class,secondly atleast one method is abstract.
Example Abstract "// Abstract Classes
using System;
abstract class BaseClass // Abstract class
{
protected int _x = 100;
public abstract void AbstractMethod(); // Abstract method
public abstract int X { get; }
public abstract int Y { get; }
}
class DerivedClass : BaseClass
{
public override int X // overriding property
{
get { return _x + 10; }
}
static void Main()
{
DerivedClass o = new DerivedClass();
o.AbstractMethod();
Console.WriteLine(""x = {0}, y = {1}"", o.X, o.Y);
}
}"
Reversing a string "Char[] sTest = ""INDIA"".ToCharArray();
Array.Reverse(sTest);
String strReverse = new String(sTest);"
Getting first Char strin "string str = ""Ramesh is good"";
string abc1 = str.Substring(0, 1); //Return R
string abc2=str.Substring(0, 2); //Return Ra
string abc3 = str.Substring(2); //Return mesh
"
Constant vs readonly Contant value cannot be changed.Read only the value can be changed at run time only once.
"A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants.
"
"public abstract class oops
{
public readonly string sRead=""dev"";
public const string sCont = ""ram"";
public oops()
{
sRead=DateTime.Now.ToShortDateString();
//sCont = DateTime.Now.ToShortDateString();/gives error
}
}"
Write vs WriteOnly Former output without new line character Ex console.write("dev") console.write("kum"). Output=Dev kum.. Later gives formated output same dev next line kum
Enumerations They a re user-defined integer type which provide a way for name to number. Ex enum Shape{ Circle,Squire}
Delegate They are function pointer that they point towards the function.For this the signature should match of method.
Multicast Deleage This is functionpointer points to more than one function.
Ex "public delegate void adddel();
public class testdel
{
public static string str = """";
public static void add1()
{ //str=""delegate Example1""; }
public static void add2()
{ //str = ""delegate Example2""; }
}"
"//testdel obj = new testdel();
adddel objdel = new adddel(testdel.add1); //single delegate
objdel += new adddel(testdel.add2); //multicast delegate
objdel += new adddel(testdel.add3); //multicast delegate
objdel.Method.ToString(); "
Events A notisfication from a class to the client.Based on delegate we must first declare events.Based on publisher and suscriber. Ex Declare delegae,Declare event & envoke event.
The event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code. The delegate can have one or more associated methods that will be called when your code indicates that the event has occurred.
"Suppose you built a Clock class that fires a NewHour event at the top of every hour.
Here's how that class—and a delegate defining the signature of NewHour handlers—might be declared:
Note:Event and deleagete name are same.
public delegate void NewHourHandler (int hour); //DELEGATES
public class Clock : MarshalByRefObject {
public event NewHourHandler NewHour; //EVENT
...
}
Clock clock = new Clock ();
clock.NewHour += new NewHourHandler (OnNewHour);
.
public void OnNewHour (int hour){ //FUNCTION
// NewHour event received
}"
Indexers Are location indicators and used to acess class object , Just like acessing element in the array.Indexed Properties are simply property methods that have a mandatory parameter. The mendatory parameter is semantically treated like an index
"public class clsIndex
{
public String [] name=new String[5];
public string this[int index] {
get {
return name[index];
}
set {
name[index]=value;
}
}
}
clsIndex obj = new clsIndex(); Calling index
obj[0] = ""dev"";
obj[1] = ""raj"";
obj[2] = ""shyam"";"
Can have abtract,inheritance,polymrphism but in the abstract index it will not have a body.
Property It is prefered over member variable bcoz they provide data validation. Contain two get & set.Indexer are the default property.
Contructor Method inside the class with same name as class, with no return type.Not even void .Get created when new instance is made.
"1) Mostly public,no void
2) Can have parameters and no return value
3) Some time private ,no inheriacance"
"public class MyClass{
public int x;
pubic MyClass(int i) { //no void,no return type
x=i;
}
}"
Static Constructor "A constructor for a class, rather than instances of a class. The static constructor is called when the class is loaded.
"
"1) Cannot be Overloaded
2) Its without parameters & can access only static member.Note: Structure have parameterized constructor.
3) No access modifier,called only once in application domain"
"public class classStaticConstructor{
public int iCount;
static string iStat;
public classStaticConstructor() { //normal con,Without Parameters
iCount = 100;
iStat = ""Name"";
}
static classStaticConstructor() {
// iCount = 1000; //Runtime compilation error
iStat = ""Name Name"";
}
}"
" classStaticConstructor oj = new classStaticConstructor();
classStaticConstructor oj1 = new classStaticConstructor();
//Step first static then normal contructor
//Secone time only first is called no static contructor called
//Cannot declate not static varible in static constructor but staic in norml con
//no acess modifier no paramenters
//Cannot be Overloaded
"
Distructor For clean up, ~Class1().Function gets called up when that object is not in used.
declare a pure virtual function in C#? "Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation.
"
Object Oriented Programing
Concept Of OOPS Inheritance, Polymorphysm, Encapsulation, Abstraction
Abstraction Abstraction is the process that identifying the crucial behavior of an object & elimination irrelevnt details,Forming gernalized concept. Ex "just give me the higlight".Depend on the mind of developer. Only takes relevent details for designing of appropriate class.
Encapsulation Binding data and method(Function) together.It is a container where data and method are kept together.It done to hide the functionality of class.Ex. Class where data & function are combined.
Data Hiding & Information Hiding: Part inside the encapsulation,Restrict data by using access modifier like public,private,Protected.
Inheritance The Inheritance concept is used to declare a new class, called a derived class, based on an existing class, known as a base class. Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class
Polymorphims Capablity of one object to behave in multiple ways with same name & difftent parameters.
Two types:
a) Compile time/Early binding/Overloading
"(Early binding) Ex Overloding.
Can have different return type & paraments. Only method name should be same."
Overloading
public class clsOverloading
{
public string name(int i)
{
return "qwee";
}
public void name(int i,string s)
{
}
}
Note: Can have different return time
clsOverloading OO = new clsOverloading();
OO.name(2, "AA");
OO.name(200);
b) Run time /late binding / Overriding
(late binding) Overrding: Virtual base class-Override derived.
Example
Class AA { void virtual add() { } }
Class BB:AA { void override add() { } } Note:Both should have the same return type¶ters
Base Class
1)Calling Base class by making base.GetNameADD() in the drive class
" BB oji = new BB();
oji.GetNameAdd();"
" 2) AA objBase = new AA();
objBase.GetNameAdd(); "
" 3) BB ojk = new AA();
ojk.GetNameAdd();"
Cannot implicitly convert type 'AA' to 'BB'.Base to derive. An explicit conversion exists (are you missing a cast?) WARNING compile time.(Casting big to small)
Drived Class
////calling Drived Class
BB objDriv = new BB(); //Type1
objDriv.GetNameAdd();
AA objq = new BB(); //Type2 ok drive to base
objq.GetNameAdd();
BB objBS = new BB(); //Type3 Making new in drived class OK
objBS.GetNameAdd();
Polymorphysm can be possible without inheritance ?
"• Yes.
•Example is overloading, which takes place in a single class
"
If we keep virtual but remove overrides it will not give error but vise versa it will give compile time error. To add the virtual,Abstarct.
Sealed Method "Derived class cannot override/inherit this method.Always used inplace of override. Ex
Public class AA {
void virtual add() { }
}
Class BB:AA {
void sealed add() { }
}
"
Int 32 bit
Char 16 bit
Exe VS Dll "* You can create an objects of Dll but not of the EXE.
* Dll is an In-Process Component whereas EXE is an Out-Process Component.
* Exe is for single use whereas you can use Dll for multiple use.
* Exe can be started as standalone where dll cannot be."
Inner Class As the name implies, an inner class is a class that is defined inside another class
Partial Class used to split the definition of a class or struct or interface across multiple source files. Each source file would contain a section of the class definition and all parts are combined when the application is compiled.Spliting helps mutiple programer to work independently.
Cannot have the same name method.
Ex "// File1.cs
public partial class Order
{ private GetOrderDetails() { ... } }
// File2.cs
public partial class Order
{
public RetrieveOrder() { GetOrderDetails(); ... }
}"
Generic class Generic classes are classes that can hold objects of any class. Containers such as Lists, Arrays, Bags and Sets are examples
Generics in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared. Using generics, a class template may be declared that may follow any type as required at runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this generic class.
"public class classGen<T>
{
void add(T objType)
{
string str = objType.ToString(); ;
}
}"
classGen<int> objGen=new classGen<int>();
"They are tad similar to C++ templates. With the object class, theres no type safety duringcompile time. casting is necessary in Asp.1.1 . Also, using the object class for value types has a performance impact. .Generic classes make use of generic types that are replaced with specific types as needed. This allows for typesafety. The system.collections.Generic namespace gives you access to generic versions of the stack, dictionary,sorted dictionary, list and queue classes.Advantages: Binary code reuse, performance, easy of reading, typesafety.
"
Collection Any class that allows for gathering items into lists and for iterating through those items.
Debug vs Trace Debug runs in the build Mode,Trace in both build and relese mode
System.Diagnostics namespace has two main classes that deal with tracing - Debug and Trace. Tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds & release that have the TRACE symbol defined.It means that use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.
Trace Trace.Write("Custory", "Page Load has fired."); //Show trace log in default color(black)
Trace.Warn("Custom Category", "Warning: Page Load has fired."); //Same but in red
"whats the difference between convert.ToInt() and parse.int()
a) the first does work for null value .
b) the later does not work for null value. "
What will happen we have catch with return will it go to the finallize ? Yes
string str=null; will show null with exception InvalidOperationException
throw exception "Helps to catch user defined exception. In the following example, an IOException is raised by creating an instance
of the IOException class.
void OpenFile(File f) {
...
if ( !f.Exists() )
throw new IOException(""File doesn't exist"");
...
}"
Attribute " Allow to add some more Additonal declarative information to type(Class,Method)
two type
PreDefined : Which already exist & accessed through rutimeEx Assembly ,WebMethod,version,Seralized
Custom Defined: Which you add your self by extending the system.Attributes & System.Type"
Obsolete Attribute Obsolete provides a warning when an older version of a member method, is used. An informative message promoting the use of the newer method is generated at compile-time.
"public class Math {
[Obsolete (""Use Math.Absolute() instead."")]
public static int Abs(int n) { return (n < 0) ? -n : n; }
}
'Use Math.Absolute() instead.'"
Example Interface interface ISampleInterface {
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{ //method inplementation
}
}
ISampleInterface obj = new ImplementationClass();// Declare an interface instance.
obj.SampleMethod(); // Call the member.
Two void method in 2 interface with same name?
Upto compiler to deside.Now error.
Two different return type method in 2 interface with same name?
Cannot be called compile time error.
Try Catch R-System
case 1 if there is error in the try it will skip try >> catch >> finnaly and then last statement.
case 2 if there is error in the try and in catch then it will go the catch then it will go the finnaly but it will not execute last statement.
"1
try
{
2, 3, 4
}
catch
{
5, 6(error), 7
}
fnnaly
{
8, 9
}
10"
Q34. can we put a break statement in a finally block?
Ans. The finally block cannot have the break, continue, return and goto statements.
Cont stmt inside for loop The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.
Try Catch
"int x = 10; int y = 0;
int z;
try
{
try
{
z = x / y;
}
catch (Exception ex1)
{
Response.Write(""sds1"");
}
finally
{
Response.Write(""sd2"");
}
}
catch (Exception ex)
{
Response.Write(""sd3"");
}
"
"int x = 10;
int y = 0;
int z;
try
{
try
{
z = x / y;
}
catch (Exception ex1)
{
Response.Write(""sds1"");
}
}
catch (Exception ex)
{
Response.Write(""sd3"");
}
"
If there is error inside the try it will catch 1 not the catch 2.but go to all the finnaly block
Inheritance A B C
Caling B class from the C class
B obj=new C();
C# Vb.net Description
Seald NonInheritable Class
Seald NonOverridable Method
Abstract MustInherit Class
Abstract MustOveride Method
virtual Overridable
Static Shared
Oveloads
Static
Class AA:BB Implements Inherit Interface
Class AA:BB Inherits Inheritance of class
new Shadow
~C Finilize Destroyed
using Imports
void x Sub x
this Me
base MyBase
delegate AddressOff
indexer Default
Stirng[] as=new String; Dim aa(1,4) as array Array
For each I in aa next
ConvertTo.int32 Ctype,Cint(23.3)
MessageBox.Show("hi"); MsgBox("hi")
Virtual-overrides Overridable-overrides
Option Strict off casting is must
Option Explecit ON variable should be declared
Array Dim a(20) as string
for each c in a
Next
Redim
Preserve
Error andler On error Statement go to
Try-Catch-Finnaly statement
Topic Covered Not properly remember
Code-->>MSIL----(JIT)--------->>Machine Code
Dotnet Its an Env. For dev. Windows ,web app. ,services and components using multiple programing language.
Dotnet Framework Is a Plateform to build,deploy and running the application like windows,web,console & web services.Consist of CLR,Framework Class Library,Intefaces(asp.net & window forms).
Structure CLR
Class Library
Interface
CLR The CLR is the execution engine for .NET Framework applications. It's a run time that convert MSIL code to machine Code,It manages the execution of all .NET assemblies.Its function are 1)Code Management 2)Memory managemt 3)Verify Type Safty 4)Sequrity 5)Garbage Collection.
CTS (Common Type System)CTS defines all of the basic types that can be used in the .NET Framework and the operations performed on those type.That is Interopertablity.Int means same to be used in C#,vb.net,C++ posible only by CTS.Ex String.
CLS Common Language Specification.Set of common convention used to promote interoperatablity between prog. Language and .net Framework.Its a subset of cts.Componet written in C# will be shared by the other lang. vb.net.
Note Need wrapper class to call the componet written in the other language.
IL MSIL is also called is IL
CLI Common Language Infrastructure.Allow application to be written in different language.
MSIL / IL / JIT MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.Generated by all the .NET language compilers.
JIT JIT means Just In Time compilation which means the code is being compiled just before it is supposed to run.It convert MSIL code to machine code.
Type of Jit
Pre Jit Compile the source code into native language in single compilation.Done at the time of development.
Eco JIT Compile only those method that are called only at run time.& Compile method removed when not required
Normal Jit Compile only those method that are called only at run time.Then it store it in the cache for the first time.But when next time is required it get it from the cache.
NGEN "JIT take longer startup time (because the code takes some time to compile) but more efficient compilation (since the compiler has more information about the target system etc.).
NGen is used to pre-JIT code which yields faster startup time but the compiler produces less efficient code because it has less information."
Assembly Primary Building block of dot net framework.A software single output unit.It contain MSIL code.Are Self Describing unit [metadata ,menifest].
Menifest Describe information about the assembly itself. These are called assembly attributes. Like [assembly: AssemblyCompany("MyCompany, Inc.")],Ex Assembly Name,Version,Culture Information
Type Metadate Describe about the content of assembly like classes, properties, methods and parameters and return values.
MSIL It's by itself a programing language.Its instruction set programing language that is generated when we compile dotnet code.
Resporce File "Resources are nonexecutable parts of your program (specified in .Resources files) such as images, icons, or message files.
"
Type Of assembly
Public/Shared Assembly that can be shered by the applaction,Also called as GAC,Stored in GCA.
Private Localized assembly is called as private.Stored in single app. In same app. Direcory.Not sharable
Satelite An assembly containing localized resources for another assembly (customize app. In diff. Languages and culture)
ILDASM [ Intermediate Language Disassembler] tool for viewing and understanding the internal structure of assemblies ex ildasm.exe
GAC "Global assembly cache stores assemblies specifically
designated to be shared by several applications on the compute.
"
" snk -K shape.snk
[Assembly AssemblyKeyFile[""""shape.snk""""]
compile and shape.dll generated
Drag & drop in GAC or cmd promt type GacUtil /I shape.dll"
Two Assembly in the GAC "Suppose we have two assembly in the GAC(A-1.1.187.1990,B-1.1.187.1993).When we try to access it will take the latest assembly.But to select the older once we have to use () in web.config
<bindingRedirect oldVersion="1.1.187.1990" newVersion="1.1.187.1993">
"
Version in Assembly Major,Minor,Build,Revision
Strong Name The unique combination of the assembly name, version no, culture identity and public key token is called a strong name.It consist assemply identiry.
Diff. Namespace and Assimbly Logical naming scheme ,is preceded with a dot-separated hierarchical name. Controled by developer.Assembly contain information from more than one name- space, and conversely, a single namespace may be spread across several assemblies.
Managed and Unmanaged Code Managed code is code that is written to target the services of CLR. For target the services, code must provide a minimum level of information (metadata) to the runtime. C#,Vb.net code are managed.C++ is unmanaged.Can be managed by __gc keyword.
Adv "Automatic garbage collection, memory mangmnt,security,type
checking,versioning. Managed code is compiled for the .NET run-time environment(CLR).
Unmanaged code includes all code written before the .NET Framework was introduced—this includes code written to use COM, native Win32, and VB 6. Because it does not run inside the .NET environ ment, unmanaged code cannot make use of any .NET managed facilities."""
Managed Date Closely related to managed code is managed data--data that is allocated and de- allocated by the CLR garbage collector.
Dll hell problem assoited with version of application.
Internationatization: Create applications that are ready to cater(provide food) to different countries of world.Two part lacolization,Globalization.
Globlization and Localization App. Created for muliple culture.Use by correct currency,date,time,sorting rule.System.Globalization
Searilization Process of converting object into stream of bites.Used in the remoting and webservices.
Web services uses the Xml Seralization and remoting uses binary & soap formater.
Diffgram,SoapTemplete,Idisctionary(HashTable)
DiffGram "Its an XML format that is used to identify current and original versions of date element.When sending and retriving data from a dataset from XML web services(web services) diffgramm is automaticaly used. Diffgram format is divided into3 sections current Data,original data,error section.When the ADO.NET DataSet is serialized as XML (for example, when returning a DataSet from an ASP.NET XML Web service method), the XML format used for DataSet serialization is known as DiffGram.Ex <DataInstance>,<diffgr:before>,<diffgr:errors>
."
Need to serialize Object "We need to serialize the object,if you want to pass object from one computer/application domain to another.Process of converting complex objects into stream of bytes that can be persisted or transported.Namespace for serialization is System.Runtime.Seri _alization.The ISerializable interface allows you to make any class Serializable.Used in remoting and webservices NET framework features 2 serializing method.Object can be xml,array,dataset,class etc
1.Binary/Soap Serialization 2.XML Serialization
"
Reflection It extends the benefits of assembly by allowing developers to inspect and use it at runtime.Its basically – seeing the contents of an Assembly file. Namespace: System.Reflection
Boxing & Unboxing Conversion of value type to refrence type object.Value type store in stack memory convverted into Heap.
Casting{implecit//Explicit} Automatic Conversion is implecit.
Adv. Of C# 1) fully Object oriented programing language. 2) Rich built in functionality. 3)Automatic Memory management 4)No registration and versioning issue 5)Xcopy Deployment 6)Easy build Web Services.
COM Component Object Model, Reusable piece of code. ex[.ocx,.dll,tlb] in dotnet its .dll.Dot net might use lots of stuff arround in program in the form of COM.These are called through "wrraper class" or RCW in dot net can be called same as assembly.
A component is a subprogram or part of a program designed to be used by other programs.Binnary reuse the piece of s/w,Contain one or more class,have ext .dll
Using in the Dotnet.We have to use interface System.ComponentModel.IComponent interface.
CCW used to connect when we refer the .net object to other com
RCW:opposite
MVC "Model:DataSet, DataView, Bussines component tied to Web/ Windows
View: Web form, Xml, Xls, Windows Form
Controler:Page Code behind.cs.Help in comunication between two
"
Garbage Collection Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy.
Finize : Finalize clearing object from the memory automaticaly by garbage collector.No code written,Called as soon as leave the code,Distructor
Dispose: Dispose by the programer explicitly.Used by Idisposible interface by despose method
Mannually call the GC : System.GC.Collect()
Supress the finilize : GC.SurpressFinilize()
Dispose * Dispose() is called by the user.Its deterministic.Its explicit, meaning you code Dispose() up and explicitly call it in your application or system code.
Finalize Finalize() is called by the runtime (the GC).no guarantee that Finalize() will be called immediately when an object goes out of scope .It's non-determisistic means you code Finalize() up but u never actually call it —its called behind the scenes by the .NET GC mechanism.
How does the generational garbage collector in the .NET CLR manage object lifetime?
It divides the objects into three generations.
The first generation is used for short lived objects and is collected often (its cheap to collect it). The other two generations are used for longer term object.
Non-deterministic finalization Non-deterministic finalization means that it is not known when the object's finalizer is called since it is called when the GC decides to collect the object and not when the object falls out of scope etc.
using() The using statement defines a scope at the end of which a given object will be disposed.Using the 'using statement' helps not to forget disposing of a disposable object.
Idisposable IDisposable is an interface used to define a way to dispose of objects in a deterministic manner.
How does it support deterministic finalization? When the 'using statement' scope ends the Dispose() method is automatically called on the given object.
How to instruct the garbage collector to collect unreferenced data?
System.GC.Collect() method.
Why doesn't the .NET runtime offer determi nistic destruction? Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap.
"public class classDispose : IDisposable
{
public classDispose()
{ //Constructor
}
~classDispose()
{
Dispose(); //Calling dispose from the finalize
}
public void Dispose()
{
GC.SuppressFinalize(this); //Supressing finilize
}
}
"
DBMS Database management System.S/w to manage Database.
RDBMS Relational database management System.Specify the relationship between tables.Ex. Sql,Oracle,dbase,Acesses
Normalization It is used to remove redudency and inconsistancy with in the data.
"1) Rmove inconsistanly by add/deleting record.
2) Remove duplicacy.
3) Increase Storage space.
"
Denormlization Process of inducting the redudency & inconsistancy in the data.
"1) Increase speed of query and better performance.
2) Increase duplicacy.
3) Reduce the table & joins.
"
Moving data base 1. BCP: Data Tranformation services transport data from one server to another
2. dettaching and attaching databases
3. replication
4. DTS
5 BACKUP/RESTORE
6. logshipping
7. INSERT…SELECT
8. SELECT…INTO
9. creating INSERT scripts to generate data.
Backup Type 1. Full database backup
2. differential database backup
3. transaction log backup
4. filegroup backup.
Replication & Type Replication is the process of copying/moving data between databases on the same or different servers.
* Snapshot replication
* Transactional replication (with immediate updating subscribers,with queued updating subscribers)
* Merge replication
Transaction A transaction is a sequence of operations performed as a single logical unit of work.
ACID Atomic: work as unit,all will done or none
Consistant: Once done the state will be persisted.
Isolated: When tarnsaction is working no other will interfare till compled
Durable: Once completed it will be there if system fails.
Type of Lock Intent, Exclusive, Update, Shared
Lock esclation Process of removing low level lock into high level lock.
TRANSACTION ISOLATION LEVEL "Serialized : Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction. Its safest isolation level & is the default.
Repeatable Read :Same. Any type of new data can be inserted during a transaction.
Read Committed :Transaction cannot read data that is being modified by another transaction that has not committed.
Read Uncommitted A transaction can read any data, even if it is being modified by another transaction. Its least safe isolation level but allows the highest concurrency.
"
UPDATE_STATISTICS Used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables
DBCC commands DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.Ex. - DBCC CHECKDB,DBCC SHRINKFILE[shrink files in the current database],DBCC SHRINKDATABASE(shrinks all files in a database),DBCC CHECKTABLE.
Collation "Basically the sort order.3 type of sort order
1)Dictionary case sensitive
2)Dictonary - case insensitive
3)Binary
"
Cursor Cursors allow row-by-row prcessing of the resultsets.
"DECLARE cur_cust_order cursor SCROLL for
select * from cust_order
OPEN cur_cust_order
FETCH NEXT FROM cur_cust_order
WHILE @@FETCH_STATUS= 0
FETCH NEXT FROM cur_cust_order
//Check for the status
update cust_order set name='sds kumar' where id =1
IF (@@error<>0) -- tells if there is error or not
PRINT 'Update not valid'+ @@error
CLOSE cur_cust_order
DEALLOCATE cur_cust_order Note: Have defind cursor as Scroll means go forward and back word.
"
"declare @offid varchar(100)
declare @mail varchar(100)
Declare cursor c1 For
select * from office…open c1
Fetch Next From C1
Into @Offid,@Mail
While @@Fetch_Status==0
Begin
''Wokd to be done
End
Close C1
Deallocate C1
"
"FETCH <position> INTO <Variables>
"
"<position> Fetch are[
Next-next row in cursor,
Last-last row,
Prior-before row, //baickword searching
Absulute 3-next 3rd row form current ,
Relative 3-3 rows backword.]
"
SELECT @@CURSOR_ROWS --tells about the no of row we got
@@FETCH_STATUS Used to mov to the next row. If @@fetch_status=0: means Succcessly fetched row. If -1 means faild to fetch,-2 means row fetch is missing or removed.Cursor will fetch when it 0 and will end fetching when reaches to -2
@@CURSOR_ROWS "=0 no;N no of rows;-1 dynamic cursor.status change as new row added.M value of record in recordset"
CURSOR_STATUS "return output parameters"
"Direction
[FORWARD_ONLY | SCROLL]
It is usually best to use a FORWARD_ONLY cursor, faster of the two, SCROLL is used for back and forth in a cursor in a stored procedure."
Type
Static cursor types fetch all rows resulting from the SELECT statement, and copy them to a temporary table.
Keyset Same above & it obviously requires some unique key to be identified by SQL Server.
Dynamic fetches the data as you request it, so unlike the previous types, the actual row that will be fetched is not known until you fetch it.
Forward only Forword fetching one next---
Union and UnionALL "The UNION will remove duplicates from the result set by default. You can use the UNION ALL to keep the duplicates in the result set.Order by can be in one select statement may be in the last query. SELECT au_lname FROM authors
UNION ALL
SELECT lname FROM Employee
ORDER BY au_lname
"
Triger Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. Type After Trigger and Instead of Trigger . There are two table inserted(new value) & deleted table(old value)
Trigger firing order "CREATE TRIGGER delete_update_test
ON test_trigger AFTER DELETE, UPDATE
AS
PRINT 'You just deleted or updated a row!'
GO
EXEC sp_settriggerorder delete_update_test, first, 'delete'
EXEC sp_settriggerorder delete_update_test, last, 'update'
"
Desabling Trigger "ALTER TABLE tablename DISABLE TRIGGER ALL
ALTER TABLE tablename ENABLE TRIGGER ALL
"
After Trigger The type of trigger that gets executed automatically after the statement that triggered it completes is called an AFTER trigger. An AFTER trigger is a trigger that gets executed automatically before the transaction is committed or rolled back.
Ex.: "CREATE TRIGGER delete_test
ON test_trigger AFTER DELETE
AS
PRINT 'You just deleted a row!'
"
Instead Of Trigger A trigger which gets executed automatically in place of triggering actions i.e., INSERT, DELETE and UPDATE is called an INSTEAD OF trigger. Get executed before the pk and fk are cheched unlike After Trigger.
Ex.: "CREATE TRIGGER DEL_JOIN
ON join_view
INSTEAD OF DELETE
AS
DELETE Table1
WHERE a IN (SELECT a1 FROM deleted)
DELETE Table2
WHERE a IN (SELECT a2 FROM deleted)
"
Sp_helptrigger User_Master-help for the trigger
Trigger Magic Table "Events Inserted Deleted
Insert inserted row Empty
Delete Empty deleted row
Update new row Old row
"
Current Identity "'@@Identity
@@scope_identity()
ident_current('tablename')"
Can store trigger called from the function procedure Triggers cannot be called directly. Instead they are fired automatically when you perform an insert/update or delete on a table that has triggers. Therefore, you cannot call a trigger in a stored procedure. You can perform an insert / update or delete that will force a trigger to fire. As to the second part of your question, you can absolutely execute stored procedures in the source code of a trigger.
Delete & Truncate Commad Delete:Remove rows based on condition,Less speed since log is maintained,Reset Identity,Cannot remove all rows which have Forign key attached becoz it is not logged & it cant activate trigger.Cannot be rollback.Cant TRUNCATE table whick have forign key attached
Stored procedure in the function=Yes Stored procedure in trigger=Yes
Join Left outer join,rigth outer join,Full outer join
Inner Join,Outer join, Cross Join
Self Need to join the table to itself
equi Both table emp & dept must be equal
inner Find only mattaching rows
left outer join Jeft field of table A will matching rows & non matching as null.
natural join Its is based on all collumn in two table that have same name or same column.
New feature in Sql Server 2005
1 .Net CLR integration:we can write trigger,sp,function,user data type from the .net application
2 New Xml Data Type:varbinary(max) new data type in place of large image and text store xml.
3 Xquery:New xQuery suport is been used
4 Improved Error-Handling:Try-Catch
5 DDL trigger: Trigger created on Create/Alter/Drop/Server
6 Multiple Active Result Set(MARS):Return multiple statement as the result set ex return table
7 Pivot table,Sinle increment
Service Broken: Technology for building db intensive distributed application that are sequire,reliable & scaleble. It store messae
New Server Notification
Sqlserver Reporting Services
New in replication
DeadLock Situation where no one is able to get the lock.
Locking "1) Shared Lock
2) Update Lock
3) Intent Lock
4) Excluscive Lock"
Lock Esculation Conveting low level lock(row,page) to higher lock(table lock)
UDF "1) Scaler value function
2) Mutiple table value function
3) Single table value function"
Key Primary Key :no null value,make on clusterd index
Unique Key :can have 1 null,Non Clustered,No forign Key Created
Alternate Key:After marking pk the leff key from candidate key are alternate key
Candidate Key: All the key that can be made primary key
Composit Key: combination of two or more coloums which can be pk
Select * from customer group by having count(id) >0
NEWID(),GetDate()
Authenetication Mode "Windows Authenetication: Trusted,default Login
Sql Server Authenetication : Untrusted,have login & pwd"
Sql Profiler Track connection to the sql server, which scrit is runnning which job have failed.
Clustered Index The leaf level of a clustered index is the actual data itself and the data is resorted in case of clustered index.Data sored on Stack.Made on PK by default.But if we don't have the primary.We can create on the other key. Clustered index will shift if we make pk to that column.
Use *frequently used queries.
*Provide a high degree of uniqueness.(PK)
*used in range queries.>< between etc
Disadva Columns undergo frequent changes:Cause whole row to move be row in physical order.
Non Clustered Here index of the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.Max-249 per table.Data stored on heap.
Use large search,Minimum Update,large record set,join,where condition
Disadv Take more space,Slow down insert,del,mod in non-clusterd index so make min.
Fill Factor Tells how the page index are created.There is no free space.When new entry is entered the page splits.Default fillfactor=0& max=100
Composit Index Index on two or more coloumns.Both cluster and non cluster index can composet index.Ex: Composit index on price & book Name
Example Create [unique][clustered][nonClustered] index idx_customer customer(cust_id)
Extended Stored procedure An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement.Yes we can also initilize COM object.
2005 Inhancement
Top New is that it can take parameter value.earlier it was constant
"DECLARE @n int;
SET @n = 10;
SELECT TOP(@n) ProductID, Name, ProductNumber, ListPrice FROM Production.Product ORDER BY ListPrice DESC
"
"SELECT TOP(6) WITH TIES ProductID, Name, ProductNumber, ListPrice
FROM AdventureWorks.Production.Product ORDER BY ListPrice DESC.Returns another rows even if the rows are more."
OUTPUT The OUTPUT clause returns information about rows affected by an INSERT, UPDATE, or DELETE statement.
This result set can be returned to the calling application and used for requirements such as archiving or logging.
DECLARE @DeleteLog AS TABLE (LogID INT, LogEntry VARCHAR(MAX))
DELETE OutputTest
OUTPUT DELETED.ID, DELETED.Description INTO @DeleteLog WHERE ID = 1
SELECT * FROM @DeleteLog //Display the the deleted row
common table expression (CTE) "Its a temporary named result set derived from a simple query within the scope of a SELECT, INSERT, DELETE,
UPDATE, or CREATEVIEW statement.
WITH ManagerEmployees(ManagerID, EmployeesPerManager) AS
(
SELECT ManagerID, COUNT(*)
FROM HumanResources.Employee
GROUP BY ManagerID
)
SELECT ManagerID, EmployeesPerManager
FROM ManagerEmployees
ORDER BY ManagerID
"
Example of Output Stored Procedure
alter procedure add_get_user
@userid int,
@age int,
@username varchar,
@count int output
as
begin
INSERT INTO custUser(userid, Age, userName)VALUES(@userid,@age,@username)
set @count =(select count(*) from custuser)
end
declare @count int
exec add_get_user 1,29,'devesh',@count
SELECT authorcount=@count
SqlConnection con = new SqlConnection("server=DEVESH-859FF0F8;database=cms;uid=sa;pwd=");
SqlCommand com = new SqlCommand("add_get_user",con);
com.CommandType = CommandType.StoredProcedure;
//insert value
com.Parameters.Add("@userid",SqlDbType.Int).Value=2;
com.Parameters.Add("@Age",SqlDbType.Int).Value=28;
com.Parameters.Add("@userName",SqlDbType.VarChar).Value="dev";
//return value
SqlParameter prm=com.Parameters.Add("@count",SqlDbType.Int);
prm.Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
int xx=(int)prm.Value;
Response.Write(xx);
Dataware Houses and Data Mining Data warehouses support business decisions by collecting, consolidating, and organizing data for reporting and analysis with tools such as online analytical processing (OLAP) and data mining. Although data warehouses are built on relational database technology, the design of a data warehouse database differs substantially from the design of an online transaction processing system (OLTP) database.
"Data Mining is a Data Warehouse Tool
Data mining is a technology that applies sophisticated and complex algorithms to analyze data and expose interesting information for analysis by decision makers. Whereas OLAP organizes data in a model suited for exploration by analysts, data mining performs analysis on data and provides the results to decision makers. Thus, OLAP supports model-driven analysis and data mining supports data-driven analysis.
"
Fact Tables a fact table must address the business problem, business process, and needs of the users. Without this information, a fact table design may overlook a critical piece of data or incorporate unused data that unnecessarily adds to complexity, storage space,
OLAP OLAP or Online Analytical Processing services make it possible to analyze high-level of aggregation of data and trace patterns. As cetogry of S/W tools that provide analysis of data stored in a database.
Mesure of OLAP "Measures define a measurement entity and are used in facts objects. You can calculate measures with an SQL expression or map them directly to a numerical value in a column. An aggregation function summarizes the value of the measure for dimensional analysis.
Measures become meaningful within the context of a set of dimensions in a cube model. For example, a revenue of 300 is not meaningful by itself. When you put a revenue measure in the context of dimensions, such as Region and Time, the measure becomes meaningful: the revenue for New York in January is 300. Common examples of measures are Revenue, Cost, and Profit.
A measure is defined by a combination of two properties: an SQL expression list and an aggregation list. Table columns, attributes, and measures are mapped to a template to build SQL expressions. The resulting SQL expressions are then used as input for the first aggregation function of the measure. If a measure has more than one aggregation, the aggregation functions are performed in the order that they are listed, with each subsequent aggregation taking the previous aggregation's result as its input. If the SQL expression for the measure only references other measures, the aggregation function is optional. The aggregation function is optional because the referenced measures provide the aggregation.
"
What are fact tables and dimension tables in OLAP ?
Fact Tables
A fact table must address the business problem, business process, and needs of the users. Without this information, a fact table design may overlook a critical piece of data or incorporate unused data that unnecessarily adds to complexity, storage space, and processing requirements.
Fact tables contain business event details for summarization. Fact tables are often very large, containing hundreds of millions of rows and consuming hundreds of gigabytes or multiple terabytes of storage. Because dimension tables contain records that describe facts, the fact table can be reduced to columns for dimension foreign keys and numeric fact values. Text, blobs, and denormalized data are typically not stored in the fact table.
Localization "Resgen abc.resx abcd.resources
/al: abcd.resources
/out: a.dll
/c:en-US
"
"Thread.CurrentThread.CurrentUICulture=new cultureinfo(""en-EN"");
Assembly OA=new Assembly.LoadFIle(""C://a.dll"");
ResourceManager oRm=new ResourceManager(""abcd"",OA);
string str=oRm.GetString(""ID"");"
CurrentCulture , CurrentUICultur Fist tells the how framework handle date time etc,seconnd determines which satellite assembly is used when loading resources.
How do you detect the user' s culture? Use the Request object' s UserLanguages array. The value at element 0 corresponds to one of the culture codes used by the CultureInfo class. For example:
SLang = Request.UserLanguages(0)
"Server.transfer vs
Response.redirect
" "1. Both takes to the new page.
2. res.redirect tell the server but res.transfer dont tell server, so faster.
3..server.trensfer takes to new page with out chanaging url.
4. server.trensfer dont take to the new server.but redirect does.
"
"5. server.transfer can get the textbox to the next page
server.Transfer(""a.aspx"")
Request.Form(""textBox1"");"
Server.execute Takes to the next page do calculation and comes back on same page
Inetinfo.exe, aspnet_isapi.dll &aspnet_wp.exe in page loading process "inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter. aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.
"
DataSet Collection of datatables[classess].
Typed Dataset vs Untyped Dataset. "Typed dataset have schema.It have refrence to xml file.Untyped don't have.Typed gives easy acess to the content that user inform thru programingfrom the underlying schema.Simple and handy.Full structure gets copied,
Untyped only data get copitd.Ex
String s=ds.table[0].column[0] //Typed
s=ds.table[""customer""].Rows[0].item[""custid] //untyped
"
Bubble Event Datagrid,Datalist have many child control which cannot be generated.They are generated by bubble event.
Mail "[System.web.Mail]
Mailmessage and Smtp class defined insystem.web.mail.Ex
Mailmessage ms=new mailmessage()
ms.to.from.subject.body=""""
Smtpmail.smtpServer=""localhost""
smtpmail.sent(ms)
"
Web Garden Enviornment Multi-processor setup i.e single server.When application is hosted by multiple processes on the same server.
Implement webGarden="true" in web.config file. Make from false to true.There are more attribute that relate to web garden in the same tag called cpuMask.
Web Farm Multi-server scenario.Application loded on the multiple server.That envoirnment is called web farm.Ex. Many server in each state india.When load on one server is excess then the other server step in to bear the burden.This bearing is based on varios model they are.
1.RoundRobin(all server share load equally).
2.NBL(economical)
3.HLB(expensive but can scale up to 8192 server)
4.Hybrid(of 2 and 3).
5.CLB(component based load balancer)
Session State "In web.config. We have 3 state
(A) mode=""inproc"" (WebGarden fastest, when u have very few customer)
(b) mode=""State server""(WebFarm)
(c) mode=""SqlServer""(WebFarm) Ex Stateserver is faster butsqlserver isMost reliable in most mission critical application.
"
Session State "There are three type to manage session state
1.Inproce(webGarden):Session stored on sameservr aspnet_wp.exe.Fastst,Lst Relbl
2. State Server(webfarm) :OutProcess,Store session one other server,Start the services,(Asp.net State Services)(contol/Admin/services).Load shiftes.Dedecated server.
3. Sql server(webfarm).OutProcess,SqlServer store session in the another database and new table.Reliable but slow"
Stored Procdure "cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(""@App_ID"", SqlDbType.VarChar).Value = App_Id;
cmd.Parameters.Add(""@Loan_Number"", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
returnLoanNumber = cmdt.Parameters[""@Loan_Number""].Value.ToString();
"
Transaction in asp.net "con-Connection ::: com=SqlCommand
SqlTransaction tran = new SqlTransaction();
com.Transaction = con.BeginTransaction();
com.Connection = con;
com.Transaction=tran;
try {
//com.ExecuteNonQuery() //insert1
//com.ExecuteNonQuery() //insert2
tran.Commit();
} catch {
tran.Rollback();
}"
string str1= cmd.ExecuteScalar()
Sequrity
Authentication Ensure that users are who they say they are.
a) windows By IIS
1) Anamous any one can acess by default login & Pwd["none"]
2) basic Only with uid/pwd can acess.Drawback send pwd unecripted across n/w
3) Integrated Windows Same,send encripted pwd
4) Digest Use IIS ,Rely on O/s
b) forms By form
c) passport By special body Microsoft
d) None No authen,Any one can access
get/setAuthCookies(txtname.text,false)[RedirectFormLoginPage(txtname.text,false][FormAuthentication.SignOut]
Authorization Permission to acess certain page on portal
Impersonation Allow asp to take identy of user.This allow window ACL(acess control list) letting us to implement sequrity with mimimum capacity
By default, the username for the anonymous logon account takes the form IUSR_COMPUTERNAME, in which COMPUTERNAME is the name of the server.
Deleagtion Higher form of impersonation
Role Based Security lets you identify groups of users to allow or deny based on their role in the organization.Built in groups, including Administrators, Users, and Guests
"< authorization >
< allow roles=""Domain NameAdministrators"" / >"
<deny roles="/>"
State Management "Client Side : Query string, Cokkies,Hidden text,View State
Server Side : Application, Session,Caching,Context,DataBase
"
Cokkies(Client) "Just within a single page.Drawback it can be deleted/tempered.Ex
HttpCookie cookie = new HttpCookie(""mycookie"");
cookie.Values.Add(""mystate"", ""myval"");
cookie.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Add(cookie);
Get Cookies :- HttpCookie cookie = Request.Cookies[""mycookie""];
string myval = cookie.Values[""mystate""];
"
"Create Permanent Cookies
Response.Cookies(“name")="Sachin";
Response.Cookies(“name").Expire=date.maxValue;
"
"Turn Off Cookies:
Cookies.Discard
"
View state(Client) "Stored on the page can make the page large heavy.
Ex. EnableViewState=""""false"""" at page directive
ViewState[""""mydata""""] = """"dev"""";
"
"Encrypt View State? EnableViewStateMac=false;
Dissable View State? EnableViewState=false; for page derictive,Web.config
"
Query string (Client)
Hidden field Store client site value on the server.
Application State(server) Application state is shared among all clients. This state is valid until the server restarts.
Session State(server) "Session state is associated with a browser session. The session is invalidated with a timeout (by default 20 minutes).
Ex :-
Session.Abandon();
"
Caching In multiple user access web appl. Result in slowing down the speed.Improve speed by stroging the data locally on local hard disk.
"Cache
" "Similar to application state, cache is shared. However, there's much better control when the cache should be invalidated.
Ex:-
Response.Cache.SetNoStore();
//Prevent browser from cache.
"
Type of Cashing(left)
Output Caching Data is cached for the entire page or portion of page.Used when have large amout of data.We can spicify Expiry policy.Reduce n/w trafic on Server hard drive.Attributes A) Duration B)Location 3)VaryByParam
Fragmnt Cacing Cashing only the part of page.Done by UserControl. Ex top pg portion display user stock profile & bottom display the histrocal data in grid if we cache the gridpart in user control.We cached fragement cache.
Data Caching Fully fledge caching tech.Data are stored in dataview,Done progratically.
SQL Cache Dependencies. A SQL Cache Dependency enables you to reload cached data automatically when data changes in a database table. You learn how to use both polling and push SQL Cache Dependencies.
DataRelation ds.Relation.Add("Dev",ds.table[0].columns[0],ds.tables[1].columns[0])
Validation Req,Range,Regular Exp,Comare,Custom,validator Summary. 3R2CV
Deployment Project In VS 2005 IIS is not required vs have its own server:Visual Web Developer Web Server.But when we deploy the application it requires the IIS
IIS must be configured for running the application
Copy to Remote Directly to remote machine vise-versa.menu->Copy File.By command line :aspnet_compiler –v /BegVCSharpWebsite
Pre Compiling give the dll.With precompiling, the assemblies are created before the files are copied to the target Website.
"Step:
1. Make folder d:/precompiledWed
2. aspnet_compiler –p d:/ctmms –v / d:/precompiledWeb"
"""-p =physical path
–v / specifies how root references within the Web pages should be resolved.
last define Target path"
After this all the file will be copied
Windows Installer "Setup Project ,Its msi.Advantage that no need to create a virtual directory manually.Already created.Start a setup.exe program, and the complete setup is done automatically.
"
STATE MANAGEMENT Problems with ASP Session State
lIMMITATION Process dependent. ASP session state exists in the process that hosts ASP; When the process is recycled or fails, session state is lost.
Server farm limitations. As users move from server to server in a Web server farm, their session state does not follow them.
Cookie dependent. Clients that don't accept HTTP cookies can't take advantage of session state. Some clients believe that cookies compromise security and/or privacy and thus disable them, which disables the cookies.
Session Handling inprocess,OutProcess(stateserver & Sql Server)
INprocess:Deafault,On same sever,aspnet_state.exe
OutProcess: stateserver & Sql Server. Both required serialization since session stored on diffret server.
State Server Step1: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_state
step2: in web.config
<configuration>
<sessionstate
mode="stateserver" //change from inproc to stateserver
cookieless="false" //can be true if client dont want cookies on server imp
timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=<user id>;password=<password>"
server="127.0.0.1"
port="42424"
/>
</configuration>
step3: Start and restart IIS
Sql Server creating the ASPState database and tables.Run state.sql script
it will create two table and several usp to store data.
Change in web.config make
mode="sqlserver"
sqlconnection=........
In fact, we could cluster the SQL Servers such that if one SQL Server happened to be unavailable, another server that was replicating its data could take its place. This
provides a level of reliability that was not available in ASP.
"Performance and Comparision
• InProc - Fastest, more memory is consumed on web server, and it affect performance.
• StateServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you're storing lots.
• SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 25% slower than InProc. Same warning about serialization as in StateServer.
"
"Robustness
• InProc - Session state will be lost if the worker process (aspnet_wp.exe) recycles, • StateServer -Solve the session state loss problem in InProc mode. Allows a webfarm to store session on a central server. (Asp.net State Services).Single point of failure at the State Server.
• SQLServer - Similar to StateServer. Moreover, session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster,
"
File Extention
.ashx Http handler file
.asmx Web Services file.
.rem Remoting file.
.soap Web Services SOAP file
.asax Application file.
.config Configuration file.
.axd Trace viewer file.
.webinfo net project file.
.licx Licenced control file.
Http modue Whenever those events occur, ASP.NET invokes the interested HTTP modules so that the modules can play with the request.
register Http Handler " Add following settings in web.config file
<httpHandlers>
<add verb=""*"" path=""*.15seconds"" type=""MyHandler.NewHandler, MyHandler""/>
</httpHandlers>"
Note :
If we remove the web.config file than also the web page will run but we cant debug
We can install two dot net framework in the same operating system
Which method of HttpHandler gets invoked when request is received?
"
Answer: ProcessRequest(System.Web.HttpContext context) gets invoked"
What are different steps involved in implementing http handler?
Answer: 1. Write a class which implements IHttpHandler interface
2. Register this handler in web.config or machine.config file.
3. Map the file extension (.15seconds) to ASP.NET ISAPI extension DLL
(aspnet_isapi.dll) in Internet Services Manager.
Clipboard The clipboard is where your data is stored when you copy or cut some text or an image or a file or a folder.also used to transfer the data accross diffrent process.
Copy text into clipboard Clipboard.SetDataObject(textBox1.Text,true);
Retrive text from Clipboard "if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
textBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
else
textBox1.Text = ""The clipboad does not contain any text"";"
Collection classes "The .NET Framework provides specialized classes for data storage
and retrieval.These classes provide support for stacks, queues, lists, hash tables. "
Marshling Marshaling performs the necessary conversions in data formats between managed and unmanaged code.CLR allows managed code to interoperate with unmanaged code usining COM Marshaler(Component of CLR).
Page Life Cycle "i. Page_Init //no view state info
ii.Page_LoadViewState //Load view state that contian the last time the page
iii. Page_LoadPostData //
iv. Page_Load
v. Page_RaisePostDataChanged
vi. Page_RaisePostBackEvent :Button.Click + Button.Command
vii. Page_PreRender
viii. Page_SaveViewState
ix. Page_Render
x. Page_Dispose
xii. Page_Error (this is raised whenever there is an exception at the page level). "
Stop client side validtion of entire page Page.Validate = false;
Disable client side script in validators EnableClientScript = false.
Register a client side script from code-behind Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.
" System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(""<script language='javascript'>"");
//sb.Append(""{"");
sb.Append(""function show(){"");
sb.Append(""alert('hi ram-------');"");
sb.Append(""}"");
sb.Append(""</script>"");
//used when StringBuilder used for the servier side js
Page.RegisterClientScriptBlock(""clientscript"",sb.ToString()); //1below form tag
//Page.RegisterStartupScript(""clientscript"", sb.ToString()); //1aboove form tag
Button2.Attributes.Add(""onclick"",""javascript:show();"");"
Tracing Difference between Trace and Debug?
Two classes that deal with tracing - Debug and Trace class.
They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined,
whereas tracing from the Trace class only works in builds that have the TRACE symbol defined.
It means use
System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds,
System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.
Tracing is actually the process of collecting information about the program's execution.
Debugging is the process of finding & fixing errors in our program. Tracing is the ability
of an application to generate information about its own execution.
<trace enabled=false .../> in web.config or page derective
Trace.Warn & Trace.Write. :NOTE The only difference between Trace.Warn & Trace.Write is that the former has output in red color.
trace.axd : To view the trace output in the trace.axd file of the project.
5 tracing levels in System.Diagnostics. TraceSwitcher
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
Where is the output of Systm.Diagnotics.TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace.
Error in the Traeing log into file
You can analyze these log files to find the cause of the errors by Trace Listeners.
Thread & Process Process is the instance of running application.Thread is an execution stream of the process.A process can have multiple thread. When process start it gets mamory area.If there are multiple thread each thread will get memory to strore it local variable.It can also use global varibale common to all thread.Ex MS window & insance
DefaultButton,SetFocus in <Form>
Uploading File "File only upload 4mb that is 4096kb.For large file set maxRequestLength parameter of <httpRuntime> section in web.config file. string str = FileUpload1.PostedFile.FileName;
String s = System.IO.Path.GetFileName(str);
FileUpload1.PostedFile.SaveAs(@""E:\test\"" + s);"
Crystal Report "using CrystalDecisions.Shared;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;
using System.Drawing.Printing;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.ReportSource;
using System.Data.OracleClient;
ReportDocument rpt = new ReportDocument();
DataTable dtTable;
dtTable = GetDataTable(); conn--comm--get ds--return ds.Table[0].
if (dtTable.Rows.Count <= 0)
{
lblMsg.Text = ""No record found to display."";
return;
}
rpt.Load(Server.MapPath(""rptAvailableMaterialList.rpt""));
rpt.SetDataSource(dtTable);
CRV.DisplayGroupTree = false;
CRV.ReportSource = rpt;
CRV.DataBind();
"
DataGrid
"1) Select row on column chage
e.Item.attributes[""OnMouseover""]=""this.style.background='pink'"";
2) Find Controls
e.items.FindControl(""btnShow""); //finding button
e.items.ItemIndex; //primary key
e.items.Cell[0].Controls[0].ToString() //find text in the grid
e.item[i].findcontrol(""txtname"").text
3) ItemCreated : Every time
ItemDataBound : Every time
ItemCommand : Every time1,2 + click event
4) Confirm Deletion
Button btndel = e.Item.FindControl(""cmddel"")
btndel.Attributes.Add(""onclick"", ""return if(confirm('Are You Sure You want to delete?')==true{ return true }else{ return false }"")
5) val retValue=Windows.ShowModelDilog(""abc.aspx"",null,""""); Get Value from other page
"
"FIll combobox
ddlName.Datasource=dr;
ddlName.DataTextField=""firstName"";
ddlName.DataValueField=""id"";
ddlName.DataBind()
ddlName.Items.Add();
ddlName.item.FindText(dr[1]).selected=true"
" ListItem lst_item = new ListItem();
lst_item.Text = ""---Select---"";
lst_item.Value = ""0"";
DropDownList.Items.Insert(0, lst_item);
ListItem lst_item1 = new ListItem();
lst_item1.Text = ""---Not Assigned---"";
lst_item1.Value = ""-1"";
DropDownList.Items.Insert(1, lst_item1);"
"Event Paging_DataGrid()
AllowPaging=true
PageSize=10
dg.CurrentPageIndex=e.NewPageIndex;
Databind()
Causes with paging with deletion
//Delete
try {
myDataGrid.DataBind();
}catch{
myDataGrid.CurrentPageIndex = 0; //Make current page index=0
BindData();
}
"
"Sorting
AllowSorting=true
Two Way sorting
myAdapter.Fill(ds,""tblPerson"");
DataView dv = new DataView(ds.Tables[""tblPerson""]);
// Two way sorting LOGIC
if( (numberDiv%2) == 0 )
dv.Sort = e.SortExpression + "" "" + ""ASC"";
else dv.Sort = e.SortExpression + "" "" + ""DESC"";
numberDiv++;
myDataGrid.DataSource = dv;
myDataGrid.DataBind();
Cancle
DataGrid1.EditItemIndex = -1;
BindGrid();
Dg_UpdateCommand()
Dg_EditCommand
dgrdProduct.EditItemIndex=e.Item.ItemIndex ;
BindViewGrid();
Dg_DeleteCommand()"
"BoundColumn Lets you control the order and rendering of the columns.
HyperLinkColumn Presents the bound data in HyperLink controls.
ButtonColumn Bubbles a user command from within a row to an event handler on the grid.
TemplateColumn Lets you control which controls are rendered in the column.
EditCommandColumn Displays Edit, Update, and Cancel links in response to changes in the DataGrid control's EditItemIndex property."
Page Base Class System.Web.UI.Page
User Control Basecls System.Web.UI.UserControl
Web Services System.Web.Services.WebService
System.collections interfaces System.Collections.ICollection;
System.Collections.IComparer;
System.Collections.IEnumerator;
System.Collections.IEnumerable;
System.Collections.IList;
Thread A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.
Distributed app. In .Net Remoting/webservices
Multi-tasking It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.
Multi-threading When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.
Current Thread Thread.CurrentThread method
Pause Thread Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.
Sleep for infinite Period Thread.Interupt() method.
Suspend and Resume "It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until
the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state."
Seep Thread Thread.Sleep Method Thread's execution can be paused by calling the Thread.Sleep method.
Infinite time sleep Thread.Sleep (System.Threading.Timeout.Infinite).
Prevent a deadlock Ans. Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.
Priority in thread "v ThreadPriority.Highest
v ThreadPriority.AboveNormal
v ThreadPriority.Normal
v ThreadPriority.BelowNormal
v ThreadPriority.Lowest"
* What is deadlock? How we can elimate the risk?
"A good and careful planning can avoid deadlocks.There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to other thread, ThreadState property which you
can poll and act accordingly etc."
* This data structure is "Thread Safe" what does that mean?
* What are locks and why we need them? When working with shared data in threading how do you implement synchronization ?
* What are sockets? What is the difference between TCP and UDP sockets?
* How we can communicate betweem two processes?
* What is the procedure of communicating between two threads?
* What are the different states of a thread?
Type of Thread Forground and backgroud thread
"An application doesn't end until all of its foreground threads have ended. It can, however, end with background threads running. Background threads are automatically terminated when the application that hosts them ends.Hatrueve IsBackGround=true
"
In practice, a thread that terminates another thread often wants to pause until the other thread has terminated. The Thread.Join method lets it do just that
"thread.Abort (); // Ask the other thread to terminate
thread.Join (); // Pause until it does"
Class Description
AutoResetEvent Blocks a thread until another thread sets the event
Interlocked Enables simple operations such as incrementing and decrementing integers to be performed in a thread-safe manner
ManualResetEvent Blocks one or more threads until another thread sets the event
Monitor Prevents more than one thread at a time from accessing a resource
Mutex Prevents more than one thread at a time from accessing a resource and has the ability to span application and process boundaries
ReaderWriterLock Enables multiple threads to read a resource simultaneously but prevents overlapping reads and writes as well as overlapping writes
WebServices Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Rely on XML-based protocols, messages, and interface descriptions for communication and access. SOAP over HTTP is the most commonly used protocol for invoking Web services.
"1.Web services are written as plain text files with extention .asmx
2.You generate a proxy source code for this .asmx file first into VB or C# source code using a utility provided with .NET (more on that later)
3.You then compile the source code into a DLL file (actual proxy dll)which makes the ""Web Service"" component .Added by web refrence.Then dll will be creted in the bin folder.
4.You can consume a web service from any type of application that supports HTTP e.g. Console, WinForms and WebForms or even plain old ASP.
"
At Runtime "<appSetting>
<add key=""conwes"" value=""http:www.localhost/web/services.asmx""/>
</appSetting>
"
"Localhost.ExwebService obj=new Localhost.ExwebService();
obj.URL=System.Configuration.ConfigurationSetting.Appsettings[""conwes""];
string ss=obj.sesstion() //Method in the web services"
Its like the COM component.Which help to provide services on "WEB".Communication is done through SOAP protocal which is in the xml formate.
Namespace "Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web
"
WSDL.exe Now that we have our web service source code file ready(asmx), we need to convert it into VB source code. To do this .NET comes with a utility called WSDL.EXE
Tool to generate proxy of class wsdl.exe
Type supported "Classes & structs, Arrays of classes & structs Class and struct types with
public fields or properties. The public properties and fields are serialized.
Classes must have a default constructor that does not accept any parameters more....DataSet, Arrays of DataSet,XmlNode, Arrays of XmlNode"
Sequrity in web services "username-password:Database Authenticatio
SSL: Secure socket layer : Tranfaring data encripted
IP Address Restriction:Only valid Ip wil access
Web services Enhancement:Toolkit from MS that add operation which will secure web services
Windows Authetication:
Form based:"
Creating proxy dll using visual studio.nET?
"Add a web reference..." . Now select the web service and that's it ! VS.NET will automatically create a proxy for you and place in your web application's bin directory.
Overloading: "1. Make wsiProfile.none
2. Messagename diffrent
3. Function name same"
Handling Exception in Webservices "1)Network Exception(called Webexception):System.net
2)Soap Exception:System.web.services.protocals"
State Management Application,Session
"[webMethod(description=""session"",EnableSession=true)]
public void add()
{ Session[""sdsd""]=""india"";
}"
Cashing yes,[WebMethod(CacheDuration=60)]
Transaction in the web services [WebMethod(TransactionOption=System.EnterpriseServices.TransactionOption.Required)]
Disabled : Indicates that the XML Web service method does not run within the scope of a transaction.
[WebMethod(TransactionOption= TransactionOption.Disabled)]
NotSupported,Supported,Required,Required New,Dissable
"What is the attribute for webservice method? What is the namespace for creating webservice?
[WebMethod]
using System.Web;
using System.Web.Services; "
UDDI Universal Description & Discovery Language:It's a place where we register the web services.WWW.uddi.org. Here we discover and publish the web services
WSDL Web Services Description Language,It Describe about the web Services to the consumers by its public methods,data type,Paramerts,return values.It will eventualy replace disco files.WSDL.exe craeate .wsdl file.Which instruct the client how to intract with the services
DISCO List of WSDL doc.Used to Group common web services together.
XML Web Service Wire Formats To enable universal communication, XML Web services communicate using open wire formats, which are protocols understandable by any system capable of supporting the most common Web standards. SOAP is the key protocol for XML Web service communication.
async Specifies the mode of remote method invocation.
serviceUrl The URL of a Web Service.
Soap "Simple access protocal. Help in transporting the message.
Many thing like uid & pwd can be transfered by soap header.
Soap header devided into 3 parts: Soap Envelop, Soap Header, Soap Body"
SOAPHeader SOAP headers like array that overrides the default SOAP header generated by the WebService.
Protocal HTTP GET,POST: Send the request to the webservices by the query string
SOAP:-Send by Xml,SOAP can send not only the name/value pairs but also some complex object like datatypes,class,objects.It uses XML that is pure text so firewalls not created so much problem because its easily converted in to HTML
Some web service classes derive from System.Web.WebServices while others do not ?
Those asp net Web Service classes which employ objects like Application, Session, Context, Server, and User have to derive from System.Web.WebServices.
CAO vs SAO "Client Activated objects are those remote objects whose Lifetime is directly Controlled by the client. This is in direct contrast to SAO. Where the server, not the client has complete control over the lifetime of the objects.
Client activated objects are instantiated on the server as soon as the client request the object to be created. Unlike as SAO a CAO doesn't delay the object creation until the first method is called on the object. (In SAO the object is instantiated when the client calls the method on the object)"
singleton and singlecall. "Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance.
Single Call types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system."
Web Services and Remoting Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.
Both Remoting and Web Services are ways of communication between applications.
Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.
difference * ASP.NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP
* Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation
* ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.
* Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.
* In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET.
* Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.
Serialization Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization / Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).
Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
Can I customise the serialization process?
Yes. XmlIgnore,XmlElement
XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement]attribute, which can be used to specify the XML element name to be used for a particular property or field.
SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.
Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. It may mean it is a poor choice for loading configuration settings during startup of a GUI application.
errors when I try to serialize a Hashtable XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
formatter A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
Resource Files & uses Resource files are the files containing data that is logically deployed with an application.These files can contain data in a number of formats including strings, images and persisted objects. It has the main advantage of If we store data in these files then we don't need to compile these if the data get changed. In .NET we basically require them storing culture specific informations by localizing application's resources. You can deploy your resources using satellite assemblies.
need to serialize We need to serialize the object,if you want to pass object from one computer/application domain to another.Process of converting complex objects into stream of bytes that can be persisted..Namespace for serialization is System.Runtime.Serialization.The ISerializable interface allows you to make any class Serializable.NET framework features 2 serializing method.
1.Binary Serialization 2.XML Serialization
What is inline schema, how does it works?
Schemas can be included inside of XML file is called Inline Schemas. This is useful when it is inconvenient to physically seprate the schema and the XML document. A schema is an XML document that defines the structure, constraints, data types, and relationships of the elements that constitute the data contained inside the XML document or in another XML document. Schema can be an external file which uses the XSD or XDR extension called external schema. Inline schema can take place even when validation is turned off.
Why would you want to use serialization?
A. The two most important reasons are to persist the state of an object to a storage medium so an exact copy can be re-created at a later stage, and to send the object by value from one application domain to another. For example, serialization is used to save session state in ASP.NET and to copy objects to the Clipboard in Windows Forms.
It is also used by remoting to pass objects by value from one application domain to another.
Persistent Storage
It is often necessary to store the value of the fields of an object to disk and then, later, retrieve this data. Although this is easy to achieve without relying on serialization, this approach is often cumbersome and error prone, and becomes progressively more complex when you need to track a hierarchy of objects. Imagine writing a large business application, that contains thousands of objects, and having to write code to save and restore the fields and properties to and from disk for each object. Serialization provides a convenient mechanism for achieving this objective.
Marshal by Value
Objects are valid only in the application domain where they are created. Any attempt to pass the object as a parameter or return it as a result will fail unless the object derives from MarshalByRefObject or is marked as Serializable. If the object is marked as Serializable, the object will automatically be serialized, transported from the one application domain to the other, and then deserialized to produce an exact copy of the object in the second application domain. This process is typically referred to as marshal-by-value.
Type Binary Serialization
Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.
The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags.
XmlSerializer While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.
The following items can be serialized using the XmLSerializer class:
· Public read/write properties and fields of public classes
· Classes that implement ICollection or IEnumerable
· XmlElement objects
· XmlNode objects
· DataSet objects
· Only colleaction are serialized not the public property for point 2
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayList
Dim objFileStream As FileStream
Dim objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)
objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayList
Dim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatter
Dim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.
Ex
Dataset
XmlSerializer ser = new XmlSerializer(typeof(DataSet));
// Creates a DataSet; adds a table, column, and ten rows.
DataSet ds = new DataSet("myDataSet");
DataTable t = new DataTable("table1");
DataColumn c = new DataColumn("thing");
t.Columns.Add(c);
ds.Tables.Add(t);
DataRow r;
for(int i = 0; i<10;i++){
r = t.NewRow();
r[0] = "Thing " + i;
t.Rows.Add(r);
}
TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, ds);
writer.Close();
What is the difference between in-proc and out-of-proc?
out-of-proc requires marshaling between two processes and thus slower.
What technology enables out-of-proc communication in .NET?
Remoting.
Attributes <%@ WebService attribute="value" [attribute="value"…] %>
Class : Specifies the class implementing the XML Web service that is automatically compiled the first time the XML Web service is accessed after changes.Webservices can resides any place in,out,in bin etc
CodeBehind : Specifies the source file implementing the XML Web service, when the class implementing the XML Web service does not reside in the same file and has not been compiled into an assembly and placed in the \Bin directory.
Debug :Indicates whether the XML Web service should be compiled with debug symbols. true , otherwise, false.
Language :Specifies the language used when compiling all inline code within the XML Web service file (.asmx). The values can represent any .NET-supported language, including C#, VB, and JS, which refer to C#, Visual Basic .NET, and JScript .NET, respectively.
What are the events fired when web service called?
3 Tier Architecture
Many Layers Custom Control - Containing your customized Common Controls.
DataSet layer - Containing typed datasets.
DataAccess layer - Containing Data Access.
Controller Layer - Containing Controller function.
UI Layer - Presentation and so on there can be many layers.
For using one layer in another u just need to add a reference to that project.
Type 2 Software architects are a confused lot. Communicating with each other is a challenge. There is always a discussion about what goes in what layer ( or tier) and logical vs Physical separation. Even the definition of Data Tier specially is open to interpretation. Here are my views on Presentation, Data access and Data layers.
So a Layer becomes a Tier if it could be physically separated from the layers consuming it.. Now coming to a typical 3-Tierarchitecture. Here we talk about a
1. UI "Layer"
2. Business Logic "Layer"
3. Data "Layer".
Presentation layer I would say that while creating a 3-tier application, ignore the existence of the web servers. The UI layer, Presentation layer is a part of ASP.NET worker process and not a part of "pure" web server. If by any chance or coincidence it happens that the web servers contain other files apart from the plugin to the ASP/JSP runtime, just treat it outside of the presentation layer. If you feel these files are important, bring them in into your application distributable rather than keeping them outside.
Business Logic Layer Business Logic Layer contains all the business logic. This is the only interface that the Presentation layer calls. The conventional application architecture defines that the presentation layer and business logic layer should be kept on separate physical machines. Hence they should be "Tiers". Why?more security layes and more sclable
Data Layer Some say the Data layer is the database or the file system ( i.e. Raw Data)
Layer and Tier: The layers reside on the same machine, same runtime ( CLR) and any object visible to one layer can be passed to the other either by Value or by Reference. However the tiers could be on different machines or on different runtimes, hence the data has to passed by Value only - as serialized objects. The other difference is a lookup - you need to allow UI Tier code to look up and call remote App tier methods. .NET remoting, web services, RMI, remote invocation of EJB's all provide infrastructure for doing the same
Now coming to physical architecture:
a typical way to keep the tiers in a web application is
<Firewall> Web Tier <Firewall> App Tier (Business logic + Data access layers) <> Data Tier (Database/file system).
It is entirely possible to load all tiers into the same machine, but it is important to take care of not being dependant on references when going across tiers.
Microsoft Windows DNA Architecture "Architecture selected was Windows DNA architecture. Its scalable architecture based on Microsoft technlogy & specially
suited of intranet/internet application.With Windows DNA application can be portioned into n-tiers, Each tiers proform some specific task.Elogistic is 3 tire application."
Windows DNA offers a proven blueprint for those who want to build distributed business applications using Internet technologies.
Central to Windows DNA is the concept that applications should be logically separated into partitions, called tiers."Partitioning an application increases its scalability -- in other words, the software's ability to support a large number of simultaneous users," Avalani says. " It also makes the application more manageable and easier to update.
The three tiers of Windows DNA are:
•Presentation Interaction between user and application.Top tier of application.Made by HTML,DHTML,ASP,ASP.net,Java script & Crystal reports
•Business logic "Its middle tier it supports business related services for the presentation tier/User Interface.Most of the business rules and process are part of this.Its bridge between the user Interface and the Data layer. Use all the ActiveX component in vb & vb.net.Uses XML for exchanging data between the User Interface and Business Tier
Ex: Data Services,Security management Services,Encryption Services,Error handling Services,Messages Services
"
•Data storage "eLogistic uses Sql Server 2005 as back end.Uses Unicode support for storing multi-lingual data. Database:
a)ESS masters Database: All masters eg office,employee,global parameters
b)ESS Country database: According to the arch. it uses production and preview for each country for every user logedin
"
It's important to note that these three tiers are separations within the application. The deployment of the application can span any number of computers.
COM
Avalani notes that Windows DNA is based on a programming model called COM (Component Object Model). The COM model has come into widespread use since its introduction by Microsoft and it is an integral part of many Microsoft applications and technologies, including Internet Explorer and the Office suite of applications.
That means developers can create COM components using the tools and languages they're familiar with, such as Visual Basic, C, C++ and Java.
Work to be seen JOB DEVIDED,Scope of person:Task assign, Monitering,Daily Tracking
Time and flexiblety like time 30 days and we may finish in 25 days.Tell team to finish in 15 days,If leave.Dont tell the team. Adjustment.
Job in Excel.Give proper time.
Check warn with soft heart.