Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Feb 28, 2009

Global Variable in C# | Application Cache Vs Static Variable

Some times we need to use some variable globaly so that it may be available to application wide. For having a global variable we can use static variables as well application cache.

Example :

Application["gVar1"]="Global variable One stored here";
and this can be get anywhere in application by using string var1 = (string)Application["Var1"];

The same thing can be by using static variable also.

public static string GVar1;

These variables need to be initialized first time into Global.asax.cs application_start() method and keep alive until a IIS reset or worker process recycle not occurs.

Application_Start()
{
Application["gVar1"]="Global variable One stored here";
Gvar2= "Global Variable Two is here";
}
For using the Gvar2 we need to simply write the className.Gvar2 // Here Global.Gvar2 will do the work for us.


So the question arise as both are doing the same work which we prefer to use.
I must say It depends!!

Why I said so? Because there are reasons behind this.
In the above scenario I must say I MUST use static variable. (Please make static property rather than directly using static variable)
So what factors you must count for choosing static -
1. Application holds variable as Object.
2. While getting the value we need to caste into the objects which it stores. Of course casting need some value.

So when we need to use some primitive variables and they are not going to changes very frequent (locking issue in case of frequent changes) we should use static variable.
Application need to be used when we need to Hold some objects application wide.
(Note Its my own experience please do not take it as hard and fast rule).

Thanks

Jul 14, 2008

Storing and Retirving Data in XML format from sql server

Retrieving and storing data in XML format in Sql Server 2000.

Suppose you have 20 X 20 controls on your page. And want to send all the data to sql server then create xml for it.

Example :

Let there are A,B,C,D,E,F ……….. controls .

Then create xml for it as

Through String builder as

StringBuilder xmlData = new StringBuilder();

xmlData.Append("<Column>");

xmlData.Append("<ColumnVal ");

xmlData.Append(" A=");

xmlData.Append("'0'");

xmlData.Append(" B=");

xmlData.Append("’1’");

xmlData.Append(" C=");

xmlData.Append(" 2=");

xmlData.Append(" D=");

xmlData.Append(" 3=");

xmlData.Append(" E=");

……………………………………………………………………………………

……………………………………………………………………………………..

……………………………………………………………………………………

xmlData.Append("</Column>");

xmlData.Append("</ColumnVal ");

And at last it will created as :

<Column ColumnVal=1 A=’val_A’ B=’val_B’ C=’val_C’ D=’val_D’ E=’val_E’ F=’val_F’………………….></ Column>

<Column ColumnVal=2 A=’val_A’ B=’val_B’ C=’val_C’ D=’val_D’ E=’val_E’ F=’val_F’………………….></ Column>

<Column ColumnVal=3 A=’val_A’ B=’val_B’ C=’val_C’ D=’val_D’ E=’val_E’ F=’val_F’………………….></ Column>

<Column ColumnVal=4 A=’val_A’ B=’val_B’ C=’val_C’ D=’val_D’ E=’val_E’ F=’val_F’………………….></ Column>

………………………….

………………………….

………………………….

<Column ColumnVal=20 A=’val_A’ B=’val_B’ C=’val_C’ D=’val_D’ E=’val_E’ F=’val_F’………………….></ Column>

send this string into DataBase in as xml datatype.

And write query for inserting into datatable.

insert into YourTableName(A,B,C,D,E,F,G,H,…………………………… ColumnVal)

SELECT A,B,C,D,E,F,G,H, ColumnVal FROM OPENXML (@idoc, '/XML/ Column',1)

Retriving data from database.

It will return data in xml format.

CONVERT(xml,(select * from YourTableName where ‘yourcondition’ for xml raw,Elements,ROOT(' Column '))) as ColumnValue

Jun 27, 2008

Abstract Classs vs Virtual Methods

Abstract Class:
Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case in which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classesmust define the missing pieces.

Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.

In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has tow derived abstract classe Shape2D & Shape3D inherites the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherites from Shape2D, and another group of classes Sphere, Cylinder & Cube inherites from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw().

A class is made abstract by declaring it with Keyword abstract.

Example:
public abstract class Shape
{
//...Class implementation

public abstract void Draw(int x, int y)
{
//this method mustn't be implemented here.
//If we do implement it, the result is a Syntax Error.
}
}
public abstract class Shape2D : Shape
{
//...Class implementation
//...you do not have to implement the the method Draw(int x, int y)
}

public class Cricle : Shape2D
{
//here we should provide an implemetation for Draw(int x, int y)
public override void Draw(int x, int y)
{
//draw the shape
}
}

Difference between an abstract method & virtual method:
Virtual method
has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

Important Notes:

(a)Any Class with abstract method or property in it must be declared abstract
(b)Attempting to instantiate an object of an abstract class retults in a compilation error

Example:
Shape m_MyShape = new Shape(); //it is Wrong to that.

But we can do that.
Shape m_MyShape = new Circle(); // True

Or
Shape m_MyShape;
/*

declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class
*/

Circle m_MyCircle = new Circle();
m_MyShape = m_MyCircle; // Also True
(d)An abstract class can have instance data and non-abstract methods -including constructors-.

Polymorphism, Method Hiding and Overriding in C#

Polymorphism

One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.

C# Example

Let's assume the following simple classes A and B for the discussions in this text. A is the base class, B is derived from A.


Inherited Methods

A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A {}

class Test
{
static void Main(string[] args)
{
A a = new A();
a.Foo(); // output --> "A::Foo()"

B b = new B();
b.Foo(); // output --> "A::Foo()"
}
}
}


The method Foo() can be overridden in classes B and C:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}


There are two problems with this code.

The output is not really what we, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual.

Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System;
namespace Polymorphism
{
class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A
{
public void Foo() {}
}

class B : A
{
public virtual new void Foo() {}
}


A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}

Important things to remember -->

1. If you are using same name in derived class it hides the base class method, and generate a compiler warning. Use new keyword to supress this warning and tells the compiler that ok i am hiding it intentional.
2. Else define the base as virtual and write override in derived class method.
3. If you dont sure whether you want to hide or override use both virtual and new in base class method definition.

Jun 26, 2008

Creating a DataTable | DataTable in C#

Creating a DataTable | DataTable in C#

DataTable aTable = new DataTable();
aTable.Columns.Add("ProductID", typeof(int));
aTable.Columns.Add("ProductName", typeof(string));
DataRow dr;
dr = aTable.NewRow();
dr[0] = 12;
dr[1] = "Lap Top";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 13;
dr[1] = "DeskTop";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 14;
dr[1] = "Server";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 15;
dr[1] = "Mac PC";
aTable.Rows.Add(dr);

You can create these rows by getting data from database also

command=new SqlCommand("select * from Product",connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
Dr=aTable.NewRow();
Dr[0] = reader.GetValue(1);
Dr[1] = reader.GetValue(2);
aTable.Rows.Add(Dr);
}

Apr 23, 2008

Writing Log to Text File with C#

Writing Text File with C#

 

Problem definition : I need to write this for logging for testing purpose. I am logging the information when a aspx file is being called,

I want to put all information like browser, os, resolution, referer page etc.

 

So here we goes

I like to add a method let it call LogToFile()

Don't forget to include #using System.IO; as we are going to use stream writer

protected void LogToFile()

    {

            string logFilePath = Server.MapPath("Trace.txt");

        StreamWriter sw = new StreamWriter(logFilePath, true);

        //true means if file not there then create it otherwise append to it.

        try

        {

            sw.WriteLine("Logging Time: " + DateTime.Now.ToLongDateString());

            sw.WriteLine("OS/Browser/Version : "+Request.Browser.Platform.ToString()+"/" +Request.Browser.Browser.ToString()+ “/"+Request.Browser.Version.ToString());

           

            if (Request.UrlReferrer != null)

            {

                sw.WriteLine("Referrer: "+ Request.UrlReferrer.ToString());

            }

            sw.WriteLine("User Agent: " + Request.UserAgent.ToString());

            sw.WriteLine("--------------------------------------------------------");

        }

        catch(Exception )

        {

        }

        finally

        {

            if (sw != null)

            {

                sw.Close();

            }

        } 

    }

Now call this function into pageload method of your page... you will get the trace.

You can add more properties/ information according to your needs.

Apr 22, 2008

Enable pinging - Ping worker process every ( 30 seconds)

Application Pools setting

 

Enable pinging – Ping worker process every (frequency in seconds)

This setting specifies that each worker process will be pinged every n seconds, where n is the number specified in the selection box. This process is used to determine if a worker process is running correctly, or if it has been deadlocked.

What it mean ?

Central to Health monitoring is process pinging. With process pinging, IIS periodically checks to see if worker processes are responsive. This means that the WWW Service (svchost.exe) sends a ping request at a specified interval to each worker process (w3wp.exe). If a worker process fails to respond to the ping request, either because it doesn’t have additional threads available for processing incoming requests or because it’s hung up, the WWW Service flags the worker process as unhealthy. If the worker process is in an idle but unresponsive state, the WWW Service terminates it immediately and a replacement worker process is created. Otherwise, the worker process is marked for recycling.

 

Mar 20, 2008

Proxy class generation from WSDL in .NET 2.0 and .NET3.0

Proxy class generation from WSDL in .NET 2.0

The following command creates a .wsdl file for the XML Web service located at the specified URL and creates a client proxy class in the C# language for the XML Web service.

wsdl http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

The following command creates a client proxy class in the C# language for an XML Web service located at the specified URL. The tool saves the client proxy class in the file myProxyClass.cs

wsdl /out:myProxyClass.cs http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

For more visit to:

http://msdn2.microsoft.com/en-us/library/7h3ystb6(VS.71).aspx

Proxy class generation from WSDL in .NET 3.0

Use this command to generate proxy class from a web service.

WseWsdl3 http://hostServer/WebServiceRoot/WebServiceName.asmx?WSDL /out:MyProxyClass.cs

This will generate the class MyProxyClass.cs which we can include in our solution to create an object of this and then call the appropriate method.

For more visit to :

http://msdn2.microsoft.com/en-us/library/aa529578.aspx

Mar 4, 2008

Reading URL thru HttpRequest in C#

Here is the sample code for reading Http request.

 

HttpWebRequest request = null;

   string url = “http://matespoint.blogspot.com”

   // Create web request

   request = (HttpWebRequest)WebRequest.Create(url);

   // Set value for request headers

   request.Method = "GET";

   request.ProtocolVersion = HttpVersion.Version11;

   request.AllowAutoRedirect = false;

   request.Accept = "*/*";

   request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";

   request.Headers.Add("Accept-Language", "en-us");

   request.KeepAlive = true;

 

   StreamReader responseStream = null;

   HttpWebResponse webResponse = null;

   string webResponseStream = string.Empty;

   // Get response for http web request

   webResponse = (HttpWebResponse)request.GetResponse();

   responseStream = new StreamReader(webResponse.GetResponseStream());

 

// Read web response into string

   webResponseStream = responseStream.ReadToEnd();

 

Dec 19, 2007

How to close secure connection

I have two web service suppose A and B which should be call from an application, for this I am using Proxy class and meking the call. To get access these services one need to have client certificate. Now the problem is that when I calling the services one by one A and B one in one go , A is working but B is failing. But if i call both in one go [ofcourse one by one] both A and B work.

What may be the problem??

I think it is due to once connection is opened by A used by the B so both passes while in case of individual A and B fail. If we change the order of calling now the B fails , A passes.

Sep 27, 2007

Application Instance is already running in C#

How to make sure that only one instance of application is running in C#

 

 

public static void Main(string[] args)

        {

// ----------------------------------------------------

            bool running;

            Mutex mutex = new Mutex(true, “Your application name”, out running);

 

            if (!running)

            {

                Console.WriteLine("Another instance is already running.");

                Console.WriteLine (Messages.ExitMessage);

                Console.ReadKey(false);

                return;

            }

// -----------------------------------------------------

 

 

Your all working code will go here

 

 

// -------- Don’t forget to include this

 

            GC.KeepAlive(mutex);  //1

 

            mutex.ReleaseMutex(); //2

  }

 

Note: Use only one either 1 or 2 both will works, but make sure one is present.

 

Now only one application will run at a time.

Mar 29, 2007

Sending Email thru C#

Sending email thru C#, .NET 2.0 , with attachment,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;

namespace MailConnect
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Sendbutton_Click(object sender, EventArgs e)
{
MailMessage aMessage = new MailMessage("matespoint@gmail.com", "xyz@yahoo.com");
aMessage.Subject = "This is test message";
aMessage.Body = "Body text message";

Attachment aT = new Attachment("C:\files.doc");
aMessage.Attachments.Add(aT);
aT = new Attachment("C:\files.pdf");
aMessage.Attachments.Add(aT);

SmtpClient aClient = new SmtpClient(servername, 25);
aClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
aClient.Send(aMessage);
MessageLabel.Text = "Mail has been sent successfully";
}
}
}