Monthly Archives: May 2010

Extension Methods

They are static methods that can be invoked like an instance method. Static methods can be declared only in Static classes. Let’s see how extension methods are declared.
public static void ExportToExcel(this DataSet ds)
{
//do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
public static class Extensions
{
public static void ExportToExcel(this DataSet ds)
{
//do something…
}
}
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel();

Leave a comment

Filed under C#

Auto-Implemented Properties

Auto-Implemented Properties

In C# 2.0 properties are declared as follows:

private int iEmpId;
private string strEmpName;

public int EmpId
{
get { return iEmpId; }

set { iEmpId = value; }
}

Samething is redfined in C#3.0 using auto-implemented properties like:
public class AutoProperties
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public int Age { get; private set; } // read-only
}
Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

Leave a comment

Filed under C#

HttpHandlers

Using http handlers we can add new functionalities to Web Server. Files with new extensions like .text for a text file can be handled by Web Server by using http handlers. The future of customization can lead to hosting .jsp pages in IIS by finding adequate ISAPI extensions.

To create customized http handler we need to Create a C# class library as “Examplehandler” and implement IHttpHandler interface.

eg: maps all HTTP requests for files with file name extension .New to the class MyHandler.New

<configuration>
   <system.web>
      <httpHandlers>
         <add verb=”*” path=”*.New” type=”MyHandler.New,MyHandler”/>
      </httpHandlers>
   <system.web>
</configuration>

eg: To configure Web services to enable calls from Ajax enabled client script, we need to register the ScriptHandlerFactory HTTP handler in web.config.

<httpHandlers>

   <remove verb=”*” path=”*.asmx”/>

      <add verb=”*” path=”*.asmx” validate=”false”     type=”System.Web.Script.Services.ScriptHandlerFactory,     System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>

</httpHandlers>

Firstly you need to remove the default httphandler assigned to *.asmx

Leave a comment

Filed under .Net

Typed DataSet

Typed DataSet includes Type-safe into Dataset fields so as to protect it from runtime mismatch. These classes inherit directly from DataSet class.

eg: Runtime error using normal Dataset

1. Using DataSet:

 //Create DataAdapter

SqlDataAdapter daEmp = new SqlDataAdapter(“SELECT empno,empname,empaddress FROM EMPLOYEE”,conn);

//Create a DataSet Object

DataSet dsEmp = new DataSet();

//Fill the DataSet

daEmp.Fill(dsEmp,”EMPLOYEE”);

//Let us print first row and first column of the table

Console.Write(dsEmp.Tables[“EMPLOYEE”].Rows[0][0].ToString());

//Assign a value to the first column

dsEmp.Tables[“EMPLOYEE”].Rows[0][0] = “12345”;//This will generate runtime error as empno column is integer

  2. Using Typed DataSet:

 //Create DataAdapter

SqlDataAdapter daEmp = new SqlDataAdapter(“SELECT empno,empname,empaddress FROM EMPLOYEE”,conn);

//Create a DataSet Object

EmployeeDS dsEmp = new EmployeeDS ();

//Fill the DataSet

daEmp.Fill(dsEmp,”EMPLOYEE”);

//Let us print first row and first column of the table

Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());

//Assign a value to the first column

dsEmp.EMPLOYEE[0].empno = “12345”;//This will generate compile time error.

 Typed dataset is very much similar to a normal dataset; the only difference is that the schema is already present for the same. And any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset. Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema.

  Typed DataSet can be generated in two ways,

 1) Using Visual Studio .NET IDE.

2) Using XSD.exe (Using VS.Net command prompt)

Open VS.Net command prompt and Type XSD /? For the help on this exe.

 Creating a Typed DataSet using Visual Studio .NET IDE

 Let me explain a step by step procedure to create a Typed DataSet,

 1. Open VS .Net IDE and Click on File -> New -> Project and Select Console Application.

2. Enter name for the project. Say TypedDataSetTest.

3. Right click on the solution and click on Add-> Add New Item will show a dialog box.

Select DataSet from templates pane, give the name (Say TypedDs.xsd) and click on Open. This will add file by name TypedDs.xsd to the solution.

4. Click on the Server Explorer browse to the database and drop the table on the TypedDs.xsd file. 

If we check the xml file for the same then we can see the schema for the table.

This dataset can be used in the same manner as the normal dataset to get the data.

Leave a comment

Filed under C#

Auto-Implemented Properties

In C# 2.0 properties are declared as follows:

 private int iEmpId;
        private string strEmpName;

        public int EmpId
        {
            get { return iEmpId; }

            set { iEmpId = value; }
        }

Samething is redfined in C#3.0 using auto-implemented properties like:
public class AutoProperties
{
       public int EmpID { get; set; }
       public string EmpName { get; set; }
       public int Age { get; private set; } // read-only
}
Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

Leave a comment

Filed under C#

Temporary Tables VS Table Variables

Temporary Tables VS Table Variables

Temporary tables are like regular tables but stored in the tempdb database. These tables get dropped after they have been used. Temporary tables are of two types,

Local Temporary table – defined using a pound sign (#) and accessible only within the session that created it

Global Temporary table – defined using double pound signs (##) and visible to all users.

Table Variables is a data type that looks similar to a table but has a tighter lifetime scope (i.e within a function, stored procedure or batch that it is declared in) and should be used with small datasets.

Temporary Tables Table Variables
Created and stored in tempdb database Created in Memory (although it can write to tempdb)
They are bound to transactions i.e transaction logs are recorded. They are not bound to any transactions. So no effect of transaction rollbacks
Stored procedure containing temporary tables cannot be pre-compiled Stored procedures containing table variables can be pre-compiled
You can drop a Temporary Table You cannot manually drop a table variable
You can create indexes on them You cannot ‘explicitly’ create Indexes on them (exception is the index created while creating a Primary Key)

Leave a comment

Filed under SQL

WCF Transactions

 WCF Transactions

WCF provide the functionality of transactions based on WS specification which allow other language like JAVA to take advantage of this transaction that is the best part of WCF embracing other languages. Under transactions, every activity in the unit must either all succeed or all should fail.

This is achieved by using [TransactionFlow] attribute with different options like:

  • TransactionFlowOption.NotAllowed: This is a default option. Using this option no transaction is applied.
  • TransactionFlowOption.Allowed: This means client can use transaction but it is not compulsory.
  • TransactionFlowOption.Mandatory: This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised. 

Leave a comment

Filed under WCF

SOA with WCF

SOA principle followed by WCF

 1) Boundaries are well defined

client who is consuming the service does not need to know how the implementation of the service is done. like in case of DCOM any changes at server level the client also has to change.

  2) Services Independent

In SOA, services can be versioned and you can setup new endpoint for same service with different requirement.

eg: Service like “Search Tickets (Ticket Number) “which gives details based on Ticket Number and its exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

 3) Services share only schemas and contracts

Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments. 

4) Service compatibility is policy based

Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies. 

  Note: – Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.

1 Comment

Filed under WCF

WCF

WCF

  • WCF stands for Windows Communication Foundation.
  • WCF is advanced API (Application Programming Interface) for creating distributed applications using .NET framework.
  • It is introduced in .NET 3.0.
  • WCF API is found in System.ServiceModel namespace.
  • WCF is based on basic concepts of Service oriented architecture (SOA)

 

Endpoint

They are kind of connections exposed by WCF for communicating with either client applications or other service applications.

 

Components of WCF application

  • a WCF service
  • a WCF service host
  • a WCF service client

 

“ABC” of a WCF Service

  • Addresses:   This is location of the service in the form of an URI (Uniform resource Identifier) generally mentioned In the config file.
  • Bindings: This includes the type of network protocol  used by the Service. For Example HTTP, TCP/IP or others.
  • Contracts:  This is in fact the methods exposed by the WCF service.

 

 

What are the address formats of the WCF transport schemas? 
Address format of WCF transport schema always follow

[transport]://[machine or domain][:optional port] format.

for example:

HTTP Address Format

http://localhost:8888/
the way to read the above url is

“Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting”
When the port number is not specified, the default port is 80.

TCP Address Format

net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:

net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format
net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
 
What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

1) Basic binding

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

2) TCP binding

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
3) Peer network binding

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.
4) IPC binding

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.
5) Web Service (WS) binding

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
6) Federated WS binding

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.
7) Duplex WS binding

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.
8) MSMQ binding

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
9) MSMQ integration binding

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

Binding Class Name Transport Message Encoding Message Version Security Mode RM Tx Flow*
BasicHttpBinding HTTP Text SOAP 1.1 None X X
WSHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Disabled WS-AT
WSDualHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Enabled WS-AT
WSFederationHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Disabled WS-AT
NetTcpBinding TCP Binary SOAP 1.2 Transport Disabled OleTx
NetPeerTcpBinding P2P Binary SOAP 1.2 Transport X X
NetNamedPipesBinding Named Pipes Binary SOAP 1.2 Transport X OleTx
NetMsmqBinding MSMQ Binary SOAP 1.2 Message X X
MsmqIntegrationBinding MSMQ X** X Transport X X
CustomBinding You decide You decide You decide You decide You decide You decide

 

For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx

1 Comment

Filed under WCF

LINQ

LINQ
Using Linq ( Language Integrated Query) we can manipulate any object which is implemented by the IEnumerable<T> interface, XML, Dataset or relational database.

The core Linq assemblies are
System.Core.dll :- The core LINQ API.
System.Data.Linq.dll :- LINQ with relational databases (LINQ to SQL).
System.Data.DataSetExtensions.dll :- ADO.NET types into the LINQ programming paradigm (LINQ to DataSet).
System.Xml.Linq.dll :- LINQ with XML document data (LINQ to XML).

Linq Query Operators
from, in :- Used to start the LINQ expression.
where :- Used to filter the data.
select :- Used to select the data.
join, on, equals, into :- Performs joins based on specified key.
orderby, ascending, descending :- Allows the data to be ordered in ascending or descending order.
group, by :- Data grouped by a specified value.

Advantage of LINQ over stored procedures.
1. Debugging – It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio’s debugger to debug the queries.
2. Deployment – With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety – LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!

Query Expression
string[] Weekdays = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” };
IEnumerable<string> WeekdaysWithLength = from W in Weekdays
where W.Length> int.Parse(textBox1.Text)
orderby W
select W;

var WeekdaysWithLength = from W in Weekdays
where W.Length > int.Parse(textBox1.Text)
orderby W
select W;
IEnumerable<string> is the explicit object, & var is implicit object, which will convert to assign type by compiler.

Extension Methods
Linq provides a set of generic extension methods e.g. Aggregate<T>(), Max<T>(), Distinct<T>() etc.
eg:
string[] WeekdaysWithLength = (from W in Weekdays where W.Length > int.Parse(textBox1.Text)
orderby W descending select W).Distinct<string>();

Leave a comment

Filed under .Net, C#

XAML – Extensible Application Markup Language

Extensible Application Markup Language (XAML) is a .NET technology. It’s a markup language that can be used to help create desktop applications, web pages, and printable documents.
XAML is a declarative XML-based language that defines objects and their properties in XML.
It provides abbreviated markup syntax for specific types of elements that take advantage of the underlying Common Language Runtime (CLR) class constructors. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.
XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code like C# or VB.net.
Every event in XAML can be assigned to a codebehind handler,which is implemented in a supported .NET language. eg: Button click event
<Button
OnClick=”ButtonClickedHandler”
Name=”MyButton”
Width=”50″
Content=”Click Me!” />

a corresponding codebehind handler is declared
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}

All XAML attributes can be manipulated within code because they are simply XML representations of actual CLR class attributes.
It is also acceptable to inline code in the XAML file by specifying the <x:Code> element.
All inline code must be enclosed in the <CDATA[…]]> tag to ensure that the parser does not try to interpret the code. eg:
<x:Code>
<![CDATA
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}
]]>
</x:Code>

for application logic developers to access specific XAML elements, the elements must be named using either the Name or ID attribute which will be used to manipulate the element in the code.
Three basic rules to follow when declaring XAML elements:
1) XAML is case-sensitive. Element and attribute names must be properly cased.
2) All attribute values, regardless of data type, must be enclosed in double quotes.
3) The resulting XML must be well-formed. like end tag etc.

Elements can be declared all on one line, or attribute declarations can be split across lines; formatting is completely up to you. Because XAML is compiled into Binary Application Markup (BAML) file (This is a binary representation of XAML auto-genned by Visual Studio) before deployment, the amount of space taken up by elements in a XAML file is irrelevant. There are no advantages to using less space by declaring elements on a single line and no disadvantages to the formatting.

All XAML elements are an XML representation of CLR classes, but not all CLR classes are represented in XAML.
XAML element represents a .NET CLR class. but not all CLR classes are represented in XAML. Most of those represented are user-interface elements and are ultimately derived from System.Windows.UIElement, System.Windows.FrameworkContentElement.

XAML elements can be organized into five basic categories
1) Root elements
A page is required to have one root element. Windows and Page elements are the most common root elements.
2) Panel elements
These elements help you to lay out your user interface.  eg: StackPanel, DockPanel, Grid and Canvas.
3) Control elements
Controls are interactive and allow the user to enter data, make choices, and perform other interactive tasks.
eg: Button, CheckBox, RadioButtonList, ComboBox, MenuItem
<MenuItem Header=”First Menu Item”>
<MenuItem Header=”First Child Item” />
<MenuItem Header=”Second Child Item” />
</MenuItem>
4) Geometric elements
This kind of elements helps you to draw shapes and geometric graphics on your UI. eg: LineGeometry, EllipseGeometry, PathGeometry.
5) Document elements
use to deal with presentation of a document. eg: Bold, LineBreak and Italic, Paragraph, List, Block, Figure and Table.
Example:
<Window x:Class=”IntroductionToXAML.Window1″
xmlns=”
http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”
http://schemas.microsoft.com/winfx/2006/xaml
Title=”Introduction To XAML” Height=”200″ Width=”300″
>
<StackPanel>
<TextBox Name=”MyTextBox”
Width=”200″
Height=”30″
Margin=”40″ />
<Button Click=”ButtonClickHandler”
Width=”60″
Height=”20″>
Content=”Click Me!”
</Button>
</StackPanel>
<x:Code>
<![CDATA[
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
(“You typed ‘{0}’ in TextBox!”, MyTextBox.Text), “XAML”);
}
]]>
</x:Code>
</Window>
Benefit of XAML
1) The Run Time :- The ASPX uses the ASP.Net Run Time which is loaded in the IIS, rather Silver Light Runtime is a portion of CLR. Which we can download dowload in to the Client Machine and perform operations.
2) The XAML supports Rich User Interface, which means no need of JS and others. We can use the Straight away .NET WPF Animation Functions.
3) It also supports the Out Of Browser Support. (We can use the Server Web Application as a Client Application). Its included in Silverlight 4.0
4) In XAML you do not need to put a name as identifier for your controls unless you want to refer to them from other parts of your code.

Q: Can XAML be used to develop both Web and client-server applications?
Ans: XAML is used as part of Windows Presentation Foundation to write smart client applications that take advantage of the power of the PC and benefit from all of the power of the CLR. For Windows Presentation Foundation applications, the logic runs on the client, unlike ASP.NET, which processes on the server. ASP.NET continues to be the answer to producing powerful Web applications that take advantage of the benefits of the CLR on the server.

Leave a comment

Filed under .Net, C#

Reflection in C#

You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.
eg:
This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.
Create instance from assembly that is in your project References
The following examples create instances of DateTime class from the System assembly.
// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));
OR
Create instance from dynamically loaded assembly
All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
[C#]
namespace Test
{
public class Calculator
{
public Calculator() { … }
private double _number;
public double Number { get { … } set { … } }
public void Clear() { … }

}
}

Examples of using reflection to load the Test.dll assembly
System.Reflection.Assembly testAssembly = Assembly.LoadFile(@”c:\Test.dll”);
// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType(“Test.Calculator”);
// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);
// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty(“Number”);

Leave a comment

Filed under C#

Serialization

Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or even stored in a database or file system. This storage location can be a physical file, database or ASP.NET Cache.
In .NET it is provided by the System.Runtime.Serialization namespace.  This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream.

Types
Serialization can be of the following types:

·         Binary Serialization

·         SOAP Serialization

·         XML Serialization

·         Custom Serialization
Binary Serialization
Binary serialization is a mechanism which writes the data to the output stream. All members including private & public, no matter if they are read-only. It is used commonly in .NET’s Remoting technology.
The easiest way to make a class serializable is to mark it with the Serializable attribute.
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

//Serialize the object
Create an instance of stream and BinaryFormatter and then call Serialize method on formatter.
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = “Some String”;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

//De-serialize the object
Create an instance of stream and BinaryFormatter and then call de-Serialize method on formatter.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

// Here’s the proof.
Console.WriteLine(“n1: {0}”, obj.n1);
Console.WriteLine(“n2: {0}”, obj.n2);
Console.WriteLine(“str: {0}”, obj.str);

XML Seriallization
XML serialization converts (serializes) the public fields and properties of an object, into an XML stream to a XML Schema definition language (XSD) document.
Because XML is an open standard, the XML stream can be processed by any application. It use is the XmlSerializer for both serialization and de-serialization. XML Serialization is however, much slower compared to Binary serialization.

Public class Employee
{
[XmlAttribute(“empName”)]
public string EmpName
{
get
{
return empName;
}
set
{
empName = value;
}
}
}

//Serialize the object
Create an instance of stream and XmlSerializer and then call Serialize method on formatter.

DataContractSerializer

The System.Runtime.Serialization.DataContractSerializer is new in .Net 3.0. used by Wcf, but can be used for general serialization as well.

the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize instead of a Deserialize() method. It works with the same types of streams, so you can write to memory, files, etc. eg:

DataContractSerializer dataContractSerializer =

new DataContractSerializer(typeof(MyType));

// Serialize from an object to a stream

dataContractSerializer.WriteObject(stream, myInstanceOfMyType);

// Deserialize from a stream to an object

myInstanceOfMyType = (MyType)dataContractSerializer.ReadObject(stream);

XmlSrializer DataContractSerialize
1 Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize.
2 Can only serialize Public Properties. It can serialize properties, fields & that can be private, protected or public.
3 Slower then DataContractSerialize 10% faster then XmlSrializer
4 Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too Can understand the SerializableAttribute also and know that it needs to be serialized
5 Use only different attributes to serialize like XmlIgnoreAttribute, XmlRootAttribute, XmlAttributeAttribute, XmlElementAttribute Use only 2 attributes to serialize i.e  DataContactAttribute & DataMemberAttribute
6 use a Serialize() & Deserialize() method. use a WriteObject() & ReadObject() method.

Leave a comment

Filed under .Net, C#

Access Modifier

Access Modifier Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protectedinternal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.

Only one access modifier is allowed for a member or type, except when using the protectedinternal combination.

Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.

Members of Default accessibility Allowed declared accessibility of the member
enum public None
class private public

protected

internal

private

protected internal

interface public None
struct private public

internal

private

NB A class can not be declared as Protected.

Leave a comment

Filed under .Net, C#

Try Catch in SQL

–After the CATCH block handles the exception, control is then transferred to the first Transact-SQL statement that follows the END CATCH statement. If the END CATCH statement is the last statement in a stored procedure or trigger, control is returned to the code that invoked the stored procedure or trigger.
–A TRY block must be followed immediately by a CATCH block.
–TRY…CATCH constructs can be nested.
–Errors that have a severity of 20 or higher that cause the Database Engine to close the connection will not be handled by the TRY…CATCH block.
–Errors that have a severity of 10 or lower are considered warnings or informational messages, and are not handled by TRY…CATCH blocks.

Error Functions
TRY…CATCH uses the following error functions to capture error information:
ERROR_NUMBER() returns the error number.
ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters such as lengths, object names, or times.
ERROR_SEVERITY() returns the error severity.
ERROR_STATE() returns the error state number.
ERROR_LINE() returns the line number inside the routine that caused the error.
ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.

–The error functions will return NULL if called outside the scope of a CATCH block. Error functions can be referenced inside a stored procedure and can be used to retrieve error information when the stored procedure is executed in the CATCH block.

CREATE PROCEDURE usp_GetErrorInfo
AS
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
GO

BEGIN TRY
— Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
— Execute the error retrieval routine.
EXECUTE usp_GetErrorInfo;
END CATCH;

Leave a comment

Filed under SQL

Singleton Pattern

Only providing one user access to a resource is not the purpose of a Singleton.  The Singleton pattern allows multiple users to share a single object. Ex: if you want to share a single data connection with multiple resource, & don’t want to open multiple connections i.e. connection pooling.The Singleton pattern ensures that a class only has one instance and provides a global point of access.

public sealed class Singleton
{
private static readonly Singleton    instance = new Singleton();
private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

1) the Singleton’s constructor is set to private.This ensures that no other code in your application will be able to create an instance of this class.
2) an instance member variable is defined of the same type as the class. This instance member is used to hold the only instance of our class.
3)  The variable is static so that it is defined only once. static variables are defined at a point before their first use
4) the instance variable is readonly so that it cannot be modified – not even by any code that you may write in the class’s implementation.
5) a public Instance property is defined with only a get method that way callers can access the instance of this class without ever being able to change it. The property is also static to provide global access from anywhere in your program.

If you try to create an instance of the Singleton class using the new operator:

Singleton NewInstance = new Singleton();

Than, you will get a compiler error stating that the class cannot be created because the constructor is inaccessible due to its protection level.

Thread-Safe Singleton Code
if you are creating a multi-threaded application that needs to access a singleton across all of its threads, then you will need to create a thread-safe singleton class instead.

public sealed class MTSingleton
{
private static volatile MTSingleton    instance = null;
private static object syncRoot = new object();

// make the default constructor private, so that no can directly create it.
private MTSingleton()
{
}

// public property that can only get the single instance of this class.
public static MTSingleton Instance
{
get
{
// only create a new instance if one doesn’t already exist.
if (instance == null)
{
// use this lock to ensure that only one thread is access
// this block of code at once.
lock(syncRoot)
{
if (instance == null)
instance = new MTSingleton();
}
}
// return instance where it was just created or already existed.
return instance;
}
}
}

The instance member variable is no longer set at creation time, but in the Instance property instead.
The instance variable is declared to be volatile in order to assure that the assignment of instance complete before the instance can be accessed.
The syncRoot object is used to lock on. The lock ensures that only one thread can access the instance creation code at once.

Leave a comment

Filed under C#