How to set password for the sqlserver user by query

alter login username or userid with password='Give password inside single quote',check_policy=off

Delegate and events

Events

An event is the outcome of an action. There are two important terms with respect to events. The event source and the event receiver. The object that raises the event is called event source and the object that responds to the event is called event receiver. Did you observe a hitch in the above explanation?

O.K. my event source raises the event and my event receiver receives it, but what is the communication channel between them. Take the instance of you talking with a friend of yours over the telephone. Now you are the event source and your friend is the event receiver and the telephone cable is the communication channel. Similarly the communication channel between an event source and an event receiver is the delegate. The internals of events and their relationship to delegates would be dealt with in a later article. The explanation of events here is just to help the reader understand and visualize what exactly events are.

Delegates

Forget computers for a moment. Just think about delegates in the real world. Who are delegates? Delegates are people who represent a particular country or region or state in another country or region or state. Extend this same definition now to C#. In C#, delegates act as an intermediary between an event source and an event destination.
To be even precise delegates are similar to function pointers. They can be called as type safe function pointers. Delegates have other uses in addition to event handling. But this article would focus on describing delegates with respect to event handling. A delegate class used as an intermediary between an event source and event receiver is called an event handler.

Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.

Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.

In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.

.NET implements the concept of function pointers using delegates.

  • Delegate wraps a method. Calling delegate results in calling the method.
  • Delegate is a type of object very similar to classes.
  • Delegate gives a name to a method signature. 




Where are Delegates used?

The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.



namespace ConsoleApplication1
{
    public class MyClass
    {
      
        public  delegate void LogHandler(string message);
        public void Process(LogHandler logHandler)
        {
            if (logHandler != null)
            {
                logHandler("Process() begin");
            }

            if (logHandler != null)
            {
                logHandler("Process() end");
            }
        }
    }
    public class TestApplication
    {
        private   void Logger(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
        public void Logger2(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
        static void Logger1(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            TestApplication a = new TestApplication();
            MyClass myClass = new MyClass();
            MyClass.LogHandler myLogger = new MyClass.LogHandler(a.Logger);
            MyClass.LogHandler myLogger1 = new MyClass.LogHandler(Logger1);
            MyClass.LogHandler myLogger2 = new MyClass.LogHandler(a.Logger2);
            myClass.Process(myLogger);
            myClass.Process(myLogger1);
            myClass.Process(myLogger2);
        }
    }
}
http://www.akadia.com/services/dotnet_delegates_and_events.html


Types of Delegates

There are basically two types of delegates. Single Cast delegate and Multi Cast delegate. Let us first understand at the broader level the definition of both these delegates. 
  • A single cast delegate can call only one function.
  • A multi cast delegate is one that can be part of a linked list
  • The multi cast delegate points to the head of such a linked list. This means that when the multi cast delegate is invoked it can call all the functions that form a part of the linked list. Assume that i have several clients who would like to receive notification when a particular event occurs. Putting all of them in a multi cast delegate can help call all the clients when a particular event occurs.
  • To support a single cast delegate the base class library includes a special class type called System.Delegate
  • To support multi cast delegates the base class library includes a special class type called SystemMultiCastDelegate.


A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

In most cases, when we call a function, we specify the function to be called directly. If the class MyClass has a function named Process, we'd normally call it like this (SimpleSample.cs):
using System;

namespace NoDelegate
{
    public class MyClass
    {
        public void Process()
        {
            Console.WriteLine("Process() begin");
            Console.WriteLine("Process() end");
        }
    }

    public class Test
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.Process();
        }
    }
}
That works well in most situations. Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.

Single Cast delegate

The signature of a single cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.

public delegate Boolean  DelegateName (parm1, parm2)
 
When the compiler compiles the statement above, it internally generates a new class type. This class is called DelegateName and derives from System.Delegate. Just to make sure just check the ILDisassembler code to check that this is happening.
As an example let us create a single cast delegate named MyDelegate which would point to a function MyFunction. The code appears as below,

public delegate Boolean MyDelegate(Object sendingobj, Int32 x);

public class TestDelegateClass
{     
 Boolean MyFunction(Object sendingobj, Int32 x) 
 {           
  //Perform some processing           
  return (true);  
 }
        
 public static void main(String [] args)
 {
  //Instantiate the delegate passing the method to invoke in its constructor
  MyDelegate mdg = new MyDelegate(MyFunction);
            
  // Construct an instance of this class
  TestDelegateClass tdc = new TestDelegateClass();
               
  // The following line will call MyFunction
  Boolean f = mdg(this, 1);
       
 }
}
How does the above code work?
The System.Delegate contains a few fields. The most important of them are Target and Method.
The Target field identifies an object context. In the scenario above this would point to the TestDelegateClass being created. If the method to be invoked is a static method then this field will be null.
The Method field identifies the method to be called. This field always has some value. It is never null.
To the intelligent reader, if you observe the IL Disassembler code you would see that the constructor for MyDelegate contains two parameters. But in our case we are passing only one parameter? Any guesses on how this is done? Yeah you are right! It gets done internally by the compiler. The compiler resolves the call above to a call passing in the two parameters required. If you observe in C++ with managed extension, the object and the address of the function have to be passed explicitly. But in VB and C# we have done away with this with the compiler filling in the necessary details.
In the code sample above we saw,

Boolean f = mdg(this, 1);
When the compiler comes across this line, this is what happens,
  1. The compiler identifies that mdg is a delegate object.
  2. The delegate object has the target and method fields as described above.
  3. The compiler generates code that calls the Invoke method of the System.Delegate derived class i.e MyDelegate.
  4. The Invoke method internally uses the MethodInfo type identified by the delegate's Method field and calls the MethoidInfo's invoke method.
  5. The MethodInfo's invoke method is passed the delegates Target field which identifies the method and an array of variants which contains the parameters to the method to be called. In our case, the array of variants would be an Object and an Int32 value.
The above discussion would have made you clear about what happens internally when a method gets called through a Single Cast delegate.

Multi Cast delegate

The signature of a mutli cast delegate is shown below. The letters in italics can be replaced with your own names and parameters.

public delegate void DelegateName (parm1, parm2)
 
Whatever has been explained with respect to Single cast delegate holds good even in the context of a Multi Cast Delegate. There is a small addition here. Since a multi cast delegate represents a linked list, there is an additional field called prev which refers to another Multi Cast Delegate. This is how the linked list is maintained.
The return type if you have observed has changed from Boolean to void. Have you guessed the reason as to why it happens? The reason is that since several multi cast delegates get called consecutively we cannot wait to get the return value from each of these methods being called.
The code shown in the example for single cast delegate will work in the case of multi cast delegate too. The only difference is that the delegate signature needs to be changed, the method signature needs to be changed to return void instead of Boolean.
The power of multi cast delegates come in when you combine delegates to form a linked list. The Combine method is available in the System.Delegate class as a static method. The function signature as follows.

public static Delegate Combine(Delegate a, Delegate b);
 
What the above method does is that it combines the two delegates a and b and makes b's prev field point to a. It returns the head of the linked list. This in turn has to be type casted to our delegate type.
Similar to the Combine method we have a remove method which removes a delegate from the linked list and gives you the modifies smaller linked list with a pointer to the head. The signature of the remove method is as follows,
Collapse
public static Delegate Remove(Delegate source, Delegate value);
Here's a small sample that illustrates the use of a multi cast delegate,

using System;

class MCD1
{
    public void dispMCD1(string s)
    {
        Console.WriteLine("MCD1");
    }
}

class MCD2
{

    public void dispMCD2(string s)
    {
        Console.WriteLine("MCD2");
    }
}

 

public delegate void OnMsgArrived(string s);

class TestMultiCastUsingDelegates
{
    public static void Main(string [] args)
    {
        MCD1 mcd1=new MCD1();
        MCD2 mcd2=new MCD2();
        // Create a delegate to point to dispMCD1 of mcd1 object
        OnMsgArrived oma=new OnMsgArrived(mcd1.dispMCD1);

        // Create a delegate to point to dispMCD2 of mcd2 object
        OnMsgArrived omb=new OnMsgArrived(mcd2.dispMCD2);
 
        OnMsgArrived omc;
        // Combine the two created delegates. Now omc would point to the head of a linked list
        // of delegates
        omc=(OnMsgArrived)Delegate.Combine(oma,omb);
 
        Delegate [] omd;
         // Obtain the array of delegate references by invoking GetInvocationList()
        omd=omc.GetInvocationList();
 
         OnMsgArrived ome;
        // Now navigate through the array and call each delegate which in turn would call each of the
        // methods
        for(int i=0;i<omd.Length;i++)
        {
            // Now call each of the delegates
            ome=(OnMsgArrived)omd[i];
            ome("string");
        }
    }
}
The examples in this article would revolve around Multi Cast Delegates. It is essential that you have understood the basics of single cast and multi cast delegates before you proceed further.

Problem Scenario

The code below shows an example of adding a button to a Form. The button is associated with an event handler that handles whatever happens when the button is pressed. When the form is displayed and the button is pressed a message box showing "Button Clicked" will appear.
Compilation directions: Compile using
Collapse
csc /r:System.DLL;System.WinForms.DLL;Microsoft.Win32.Interop.DLL FormTest.cs
Collapse
/*
Creating a form and adding a button to it and associating the button with an event handler
*/
using System;
using System.WinForms;
public class FormTest : Form
{
    //Create a button
    private Button button1 = new Button();
    public static void Main (string [] args)
    {
        //Run the application
        Application.Run(new FormTest());
    }
    
    public FormTest()
    {
        //Set up the Form
        this.Text = "Hello WinForms World";
        //Set up the button
        button1.Text = "Click Me!";
        //Register the event handler
        button1.AddOnClick(new System.EventHandler(buttonClicked));
        //Add the controls to the form
        this.Controls.Add(button1);
    }
 
    //The event handling method
    private void buttonClicked(object sender, EventArgs evArgs)
    {
        MessageBox.Show("Button clicked");
    }
}
The topic of our discussion would be the routing of calls between the time when the click event is raised and the time when the method displaying "Button clicked" is displayed.

Restore Database from backup file .

Create the database with the specific name->Right click on the database->Task->Restore->Database->It will open a new window->chose from device radio button->Go for browse the back up file ->add the back file physically present in the system->ok->Then go to the left side panel's Options->check the ckeck bok Overwrite the existing database->then browse the ldf and mdf file where to saved -> Then ok->Ok

Export DataSet to CSV Sheet

public   void ExportExel(DataTable data, string fileName)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();
         //   context.Response.Charset = System.Text.UTF8Encoding.UTF8.EncodingName.ToString();
         //   context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");

            context.Response.ContentType = "text/csv";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
            //rite column header names
            for (int i = 0; i < data.Columns.Count; i++)
            {
                if (i > 0)
                {
                    context.Response.Write(",");
                }
                context.Response.Write(data.Columns[i].ColumnName);
            }
            context.Response.Write(Environment.NewLine);
            //Write data
            foreach (DataRow row in data.Rows)
            {
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    if (i > 0)
                    {
                        context.Response.Write(",");
                    }
                    context.Response.Write(row.ItemArray[i].ToString());
                }
                context.Response.Write(Environment.NewLine);
            }
            context.Response.End();
        }
//  return datatable
   private DataTable Test_db_table()
      {
     DataTable ConData = new DataTable();
    con.Open();
    SqlCommand com1 = new SqlCommand("select * from employee", con);
    SqlDataAdapter da1 = new SqlDataAdapter(com1);
   da1.Fill(ConData);
    return ConData;
 }


//  -- execute function
protected void Button1_Click(object sender, EventArgs e)
    {
ExportExe(Test_db_table(),"filename");


     }

Export excel sheet data from dataset in ASP.NET

Environment :
                
    • ASP.NET 1.1v
    • Visual C#
    • SQL Server2000
    • MS Excel2003
    • Microsoft Visual Studio2003
1. Create one webapplication using visual studio.
2. Just put the button text as “Exports to Excel” in webform1.aspx.
excel
3.  Use the following namespaces for this application
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
4. In button(Exports to Excel) click event
 SqlConnection conn = new SqlConnection("server=chsridhar;database=NAACP;uid=sa;pwd=mavin");
        SqlCommand cmd = new SqlCommand("select * from Branches", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable ds = new DataTable();            try
            {
            da.Fill(ds);
            }
            catch(Exception ex)
               {
                System.Diagnostics.Trace.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                conn.Close();            }
           ExcelUtility.DataSetToExcel.Convert(ds, Response);
        }            }
5. Create required class name as  “DataSetToExcel”
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;namespace ExcelUtility
{
    /// <summary>
    /// Summary description for DataSetToExcel.
    /// </summary>
    public class DataSetToExcel
    {
        public DataSetToExcel()
        {
            //
            // TODO: Add constructor logic here
            //
        }    }
}
6. In DataSetToExcel class create the method  name as called “Convert”
Convert method used for transfering dataset data to excel sheet and this method have requires two parameters are ‘dataset’ and ‘Httpresponse’.
public static void Convert(DataTable ds, HttpContext Response)
        {
            Response.Response.Clear();
            Response.Response.Charset = "";
            Response.Response.ContentType = "application/vnd.ms-excel";
            Response.Response.AddHeader("Content-Disposition", "attachment;filename=\\xxx.xls");
            System.IO.StringWriter  stringWrite=new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter  htmlWrite=new System.Web.UI.HtmlTextWriter(stringWrite) ;
            System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
            dg.DataSource=ds;
            dg.DataBind();
            dg.RenderControl(htmlWrite);
            Response.Response.Write(stringWrite.ToString());
            Response.Response.End();
        }
Now the class with convert method.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;namespace ExcelUtility
{
    /// <summary>
    /// Summary description for DataSetToExcel.
    /// </summary>
    public class DataSetToExcel
    {
        public DataSetToExcel()
        {
            //
            // TODO: Add constructor logic here
            //
        }      
public static void Convert(DataTable ds, HttpContext Response)
        {
            Response.Response.Clear();
            Response.Response.Charset = "";
            Response.Response.ContentType = "application/vnd.ms-excel";
            Response.Response.AddHeader("Content-Disposition", "attachment;filename=\\xxx.xls");
            System.IO.StringWriter  stringWrite=new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter  htmlWrite=new System.Web.UI.HtmlTextWriter(stringWrite) ;
            System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
            dg.DataSource=ds;
            dg.DataBind();
            dg.RenderControl(htmlWrite);
            Response.Response.Write(stringWrite.ToString());
            Response.Response.End();
        }
}
after builded the solution run the project. Click the exports to excel button, new ‘file download dialog box’ will appear in front of the screen.
FileDisplay
If you click open, the excel sheet embed with browser.
EmbedExcel
Otherwise you can save excel sheet file to your local system using click the save button.

http://balanagaraj.wordpress.com/2007/12/07/export-excel-sheet-data-from-dataset-in-aspnet/

Alert in the codebehind

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
       protected void Page_Load(object sender, EventArgs e)
    {
        Page.RegisterStartupScript("startup", "<script>alert('Nothing selected to perform selected operation.');</script>");
        if (!IsPostBack)
        {
         }
      }

Create a store procedure to copy the structure of one table to another temporary table

Create PROCEDURE xyz
as
select * into #employee1 from employee where 1=2
select * from #employee1

exec xyz

Here employee original Table
#employee1 temporary table

OUTPUT ONLY BE THE STRUCTURE OF THE EMPLOYEE TABLE

What is encapsulation and why is encapsulation important

Imagine that we both work for the same project and first you wrote the code for a class, and then I used your class in my program. Later on, you didn't like the way the class behaved, because some of its instance variables were being set (by me from my code) to values you hadn't anticipated. Their code brought out errors in your code. (Relax, I wont do that, dont worry.) Since, it is a Java program, so you should be able just to ship out a newer version of the class, which I could replace in my programs without changing any of my own code.

You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability. Just because Java supports OO concepts, it cannot write code for you. Can it?? For example, imagine if you made your class with public instance variables, and those other programmers were setting the instance variables directly, as the following code demonstrates:

public class BadExample {
public int size;
public int weight;
...
}
public class AnotherBadExample {
public static void main (String [] args) {
BadExample b = new BadExample ();
b.size = -5; // Legal but bad!!
}
}
Now go back the scenario we spoke about a paragraph ago. BadExample is your class and AnotherBadExample is my code. I have modified one of your variables in a way that it helps my code logic but that totally alters the way your class works. Now you are in trouble. How are you going to change your class in such a way that no one can alter your values directly (like what i have done in my code)? Your only choice is to write a method say setSize(int newVal) inside your class and then change the access modifier of the variable size to say, private. This will ensure that you handle instances when someone is trying to set a value to the size variable that you dont want and at the same time ensure that no one can access the size variable directly and mess with your code.

But, unfortunately, by doing that, you have broken my code. If I try to compile my AnotherBadExample class, i will get errors because the size variable is no longer visible for me.

How can we address this situation now? The best way is: not write such code where public variables are available for anyone and everyone to modify.


The ability to make changes in your code without breaking the code of all others who use your code is a key benefit of encapsulation. You should always hide implementation details. To elaborate, you must always have your variables as private and then have a set of public methods that others can use to access your variables. Since the methods are public anyone can access them, but since they are in your class you can ensure that the code works the way that is best for you. So in a situation that you want to alter your code, all you have to do is modify your methods. No one gets hurt because i am just using your method names in my code and the code inside your method doesnt bother me much.

If you want maintainability, flexibility, and extensibility (and I guess, you do), your design must include encapsulation. How do you do that?
• Keep instance variables protected (with an access modifier, mostly private).
• Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.
• For the methods, use the JavaBeans naming convention of set and get.

We call the access methods getters and setters although some prefer the fancier terms accessors and mutators. (Personally, I will be using the terms getters and setters) Regardless of what you want to call them, they're methods that other programmers must go through in order to access your instance variables. They look simple, and you've probably been using them forever if you have been writing java code:

public class GoodExample {
// protect the instance variable only an instance of your class can access it
private int size;
// Provide public getters and setters
public int getSize() {
return size;
}
public void setSize(int newSize) {
size = newSize;
}
}

You are now probably mumbling, what benefit is it to have methods that do nothing and just set or get values. I would rather have a public variable. If you did that go to the first paragraph under Encapsulation and re-read the whole thing. And if you did not do that but are asking me, where is the validation code that we are supposed to have in the setSize() method to ensure no one modifies it to invalid values, my friend this is just an example class. I leave you to ponder about how the implementation needs to be. Atleast you wont end up on the receiving side of unexpected shocks because of someone like me coding along with you or worse !!!

Knowing When to Use Override and New Keywords (C# Programming Guide)


Knowing When to Use Override and New Keywords (C# Programming Guide)

First we declare three classes: a base class called Car, and two classes that derive from it, ConvertibleCar and Minivan. The base class contains a single method, DescribeCar, which sends a description of the car to the console. The derived class methods also include a method called DescribeCar, which displays their unique properties. These methods also call the base class DescribeCar method to demonstrate how they have inherited the properties of the Car class.
In order to highlight the difference, the ConvertibleCar class is defined with the new keyword, while the Minivan class is defined with override.
class Car
{
    public virtual void DescribeCar()
    {
        System.Console.WriteLine("Four wheels and an engine.");
    }
}
 
// Define the derived classes
class ConvertibleCar : Car
{
    public new virtual void DescribeCar()
    {
        base.DescribeCar();
        System.Console.WriteLine("A roof that opens up.");
    }
}
 
class Minivan : Car
{
    public override void DescribeCar()
    {
        base.DescribeCar();
        System.Console.WriteLine("Carries seven people.");
    }
}

We can now write some code that declares instances of these classes, and calls their methods so that the objects can describe themselves:

public static void TestCars1()
{
    Car car1 = new Car();
    car1.DescribeCar();
    System.Console.WriteLine("----------");
 
    ConvertibleCar car2 = new ConvertibleCar();
    car2.DescribeCar();
    System.Console.WriteLine("----------");
 
    Minivan car3 = new Minivan();
    car3.DescribeCar();
    System.Console.WriteLine("----------");
}
As you might expect, the output looks like this:
Four wheels and an engine.
----------
Four wheels and an engine.
A roof that opens up.
----------
Four wheels and an engine.
Carries seven people.
----------
However, in this next section of code, we declare an array of objects derived from the Car base class. This array can store Car, ConvertibleCar, and Minivan objects. The array is declared like this:
public static void TestCars2()
{
    Car[] cars = new Car[3];
    cars[0] = new Car();
    cars[1] = new ConvertibleCar();
    cars[2] = new Minivan();
}
 
foreach (Car vehicle in cars)
{
    System.Console.WriteLine("Car object: " + vehicle.GetType());
    vehicle.DescribeCar();
    System.Console.WriteLine("----------");
}

The output from this loop is as follows:
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
Notice how the ConvertibleCar description is not what you might expect. As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead. The Minivan object correctly calls the overridden method, producing the results we expected.
If you want to enforce a rule that all classes derived from Car must implement the DescribeCar method, you should create a new base class that defines the method DescribeCar as abstract. An abstract method does not contain any code, only the method signature. Any classes derived from this base class must provide an implementation of DescribeCar

What's the benefit i get if i use Method Overriding ?


What's the benefit i get if i use Method Overriding ?


The derived class or sub class can have its own business logic in it..

Say for example, considering a real time example..


Let us say we have a class where some features of bank transactions are 
defined..

Now, we want to write our own bank transactions using already existing
 methods defined in the class but extending its behaviiour and with some 
modifications...

this is the sitaution where we inherit the class and overrride the 
methods which are required to suit our business requirement...


method overriding will be used to redefine the base class methods 
functionality in child classes... so base class and child clas 
method have different functioality.... It will work differently 
depends on the object used to call that one...

In some situations we want to have a class that has types(specially methods) that can possibly be modified in the derived class. In such situation we declare the method in the base class as virtual and precede the same method in the derived class with 'override' keyword
Consider the following code in which situation is that, a base class method Area() returns square of a parameter and suppose we want to extend this method in the derived class sothat this square may just be multiplied by a constant pi(3.142) so that it can return area of a circle:

What's the benefit i get if i use Method Overriding ?


What's the benefit i get if i use Method Overriding ?


The derived class or sub class can have its own business logic in it..

Say for example, considering a real time example..


Let us say we have a class where some features of bank transactions are
 defined..

Now, we want to write our own bank transactions using already existing
 methods defined in the class but extending its behaviiour and with some
 modifications...

this is the sitaution where we inherit the class and overrride the
 methods which are required to suit our business requirement...


method overriding will be used to redefine the base class methods 
functionality in child classes... so base class and child clas method 
have different functioality.... It will work differently depends on the
 object used to call that one...

In some situations we want to have a class that has types(specially methods) that can possibly be modified in the derived class. In such situation we declare the method in the base class as virtual and precede the same method in the derived class with 'override' keyword
Consider the following code in which situation is that, a base class method Area() returns square of a parameter and suppose we want to extend this method in the derived class sothat this square may just be multiplied by a constant pi(3.142) so that it can return area of a circle:

How override works


I'm learning about the virtual table in association with virtual methods. I got most of the logic and understanding down (I believe) for when you use 'override' and no 'override' or no 'new' modifier. What I'm trying to figure out now is what happens when you do use modifier 'new' on a derived class method inherited from the base class?

My understanding for the override mechanism with the following code:

class Base
{
public virtual void Method( )
{
}
}

class Derived : Base
{
public override void Method( )
{
}
}


...is that the vtable will replace the Base.Method() address by making the slot in the array of pointers (where Base.Method resides) point to the new override method declared in the Derived class. Correct?

My understanding for when you do not 'override' or 'new' the base method in the derived class is this: The vtable will not change where the Base.Method address resides in the the slot in the array of pointers, of the vtable, so, we'll be using the same base method. Yes?

Now to my main question: what happens when you do use the 'new' modifier on the derived method? How will the vtable look?


vtable, is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding).
Suppose a program contains several classes in an inheritance hierarchy: a superclass, Cat, and two subclasses, HouseCat and Lion. Class Cat defines a virtual function named speak, so its subclasses may provide an appropriate implementation (i.e., either meow or roar).
When the program calls the speak method on a Cat pointer (which can point to a Cat class, or any subclass of Cat), the run-time environment must be able to determine which implementation to call, depending on the actual type of object that is pointed to.

Why we can't create the object of abstract class ?

Why we can't create the object of abstract class ?
Virtual PureVirtualFunction()=0;
 This indicates compiler to reserve a slot for Function in VTABLE but  don’t put an address in that 
particular slot.  If only one function  in a class is declared as pure virtual, the VTABLE is incomplete.
If the VTABLE for a class is incomplete, compiler cannot safely create an object of a pure abstract 
class, so you get an error message from the  compiler if you try to make an object of a pure abstract 
class. Thus, the   compiler ensures the purity of the abstract class, and you don’t have to
 worry about misusing it.
  
2  The exact reason is .
 The function address of the pure virtual function is not put into VTABLE of the abstract class ,
 hence VTABLE of the abstract is incomplete. So when the user tries to create an instance of the 
abstract class the compliler  will throw an error.

 The reason behind this is , the abstract class contains abstract methods which cant do any job.
 Calling such function is meaningless. So it is not allowed to  instantiate abstract class

abstract class is an incomplete class,because if it have any method which  is abstract then it will be
 an abstract class, and abstract method have  not any implementation,thats why we can not create 
any object of  the abstract calss,we can not use the sealed keyword with abstract calss

A Simple Real time Example do Child Can Exsist Without Parent? ans is No, Hence we Define an Abstarct Class(Parent) and now the Controvercy is wheater Parent is alive or not? Child have aquried the Properties of 
Parent even though if he is alive or not? to Define an Abstract class keep in mind that parent is not 
alive that means instance can not be created but can be inherited .....Hence we can not create instance 
of  abstract class
 
abstract class contain one or more pure vertual function ,this types of  class contain only the declaration of method ,it do not have defination of any method,when we define any abstract class object it not allocate 
the memory to any object , and when any object of class will created it  first initialise memory for
 class and then methods. and look for the defination for that, for that point of view when we 
createobject of any abstract class method defination will not present  and memory cannot be allow to 
object. any by the compiler it cause the error.
 

Abstraction


ABSTRACTION

Abstraction is used to create a common set of methods that might have different specific implementations by subclasses. Abstract class cannot be instantiated and consists of abstract methods without any implementations. Classes inheriting from abstract class must implement all the methods in abstract class.
Public abstract class Shape
{
     Private float _area;
     Public Float Area
     {
          Get{return _area;}
          Set{_area=value;}
     }
     Public abstract void CalculateArea();
  
     Class Rect:Shape
     {
           Private float _height;
           Private float _width;
           Public Rect(float height, float width)
           {
                   _height = height;
                   _width = width;
           }
           Public Float Height
           {
                 Get{return _height}
                 Set{_height=value;}
           }
           Public Float Width
           {
                  Get{return _width}
                  Set{_width=value;}
           }
           Public override void CalculateArea()
           {
                  This.Area=_height*_width;
      }
}

WHY use encapsulation

Encapsulation is basically data hiding. If you don't want your variables and methods to be exposed to outside world, you use encapsulation by using the access specifier for the variables and function.


public class WeightPerson
{
private int weight;
private int size;
}

now, to enforce encapsulation, you provide accessor methods to force calling code to use them instead of directly access the instance variable.

Maintainability and flexibility is the key here. Without encapsulation, we can have a calling code
public class BadOoExample
{
public static void main(String[]args){
PersonWeight wt= new PersonWeight();
wt.size=-5;}
}
Size is set negative here which is legal but not desirable.
Using accessor methods can avoid such problems.

Benefits of Encapsulation

  • In Encapsulation fields of a class can be read-only or can be write-only
  • A class can have control over in its fields
  • A class can change data type of its fields anytime but users of this class do not need to change any code

Encapsulation

Encapsulation is process of keeping data and methods together inside objects.

  • Encapsulation is one of the fundamental principles of object-oriented programming.
  • Encapsulation is a process of hiding all the internal details of an object from the outside world
  • Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
  • Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class
  • Encapsulation gives us maintainability, flexibility and extensibility to our code.
  • Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class. 
  • Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods
  • Encapsulation gives you the ability to validate the values before the object user change or obtain the value
  • Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.
  •  

HOW TO ENCRYPT AND DECRYPT A STRING IN C#

string EncryptedString= Encrypt("STRING VALUE");
------------------------------------------

public string Encrypt(string Data)
{
 SHA1Managed shaM = new SHA1Managed();
 Convert.ToBase64String(shaM.ComputeHash(System.Text.Encoding.ASCII.GetBytes(Data)));
 byte[] eNC_data = System.Text.ASCIIEncoding.ASCII.GetBytes(Data);
 string eNC_str = Convert.ToBase64String(eNC_data);
 return eNC_str;
}

string  DecryptedString= Decrypt("Encryptedsrting");
------------------------------------------------------------------------------------------------
string original_string=Decrypt(eNC_str);

private string Decrypt(string Data)
{
 byte[] dEC_data = Convert.FromBase64String(Data);
 string dEC_Str = System.Text.ASCIIEncoding.ASCII.GetString(dEC_data);
 return dEC_Str;
}

CLICKING ON BUTTONCOLUMN OF THE GRIDVIEW

 <asp:ButtonColumn DataTextField="LogID" SortExpression="LogID" HeaderText="LogID"
    CommandName="edit"></asp:ButtonColumn>

CommandName="edit"->THIS WILL FIRE TO THE GRIDVIEW EDITCOMMAND EVENT

OPENING A WINDOW FROM THE CODE BEHIND USING JAVASCRIPT


Response.Write("<script language='javascript'>window.open('" & urllink & "', '_new')</script>")

FIND DATA BETWEEN TWO DATES INCLUDING THE GIVEN DATE

select * from TABLE  where username=@cuser and  convert(datetime,dateaccessed,105) BETWEEN convert(datetime,@frmdate,105) AND dateadd(day,1,convert(datetime,@todate,105))

dateaccessed->DATABASE FIELD HAVING VARCHAR DATATYPE CONTAINS DATA OF DATETIME FORMAT

@frmdate-> FROM DATE HAVING VARCHAR DATATYPE
@todate->TODATE HAVING VARCHAR DATATYPE

dateadd()  FUNCTION ADD A DATE TO THE GIVEN DATE

CALLING A JAVASCRIPT FUNCTION FROM THE ASPX CLICK

<input id="btn1" type="button" class="btn" value="" onclick="return btn_click()" title="Search Patients" />

 <script type="text/javascript" language="javascript">

function btn_click()
{
        if($get("search_q_Header").value=='')
        {
            alert('Please enter value to Search');
            $get("search_q_Header").focus();
            return false;
        }

}

</script>

OPENING THE PAGE IN ANOTHER BROWSER USING JAVA SCRIPT

 FROM JAVASCRIPT
-----------------

function Openwindow(id)
        {
       
        a1=window.open("desktopModules/DocuInfo.aspx?&itemid="+id,"MyWindow", 'left=300,top=200,width=500,height=230,scrollbars=yes,toolbar=0,resizable=0');
        a1.focus();
        }

FROM ASPX
---------------

<a href='#'>
<img alt="open" id="tes" style="border: 0" name="test" src="images/images1.jpg" onclick="javascript:Openwindow('<%# DataBinder.Eval(Container.DataItem,"ItemId") %>');"           height="10" width="10" align="middle"></a>


<a href='#'>-># ONLY SHOW THE LINK WHEN MOUSE OVER.ON CLICK IN IT NOTHING WILL HAPPEN

JAVA SCRIPT IN CODE BEHIND

Dim jscript As String = Nothing
            jscript += "<script>"
            jscript += "window.open('GetLogDetails.aspx','_blank')"
            jscript += "</script>"

            RegisterClientScriptBlock("submission", jscript)->THIS WILL OPEN THE SPECIFIED PAGE

SPECIAL CHARACTER IN HTML

Four character entity references deserve special mention since they are frequently used to escape special characters:

  • "&lt;" represents the < sign.
  • "&gt;" represents the > sign.
  • "&amp;" represents the & sign.
  • "&quot; represents the " mark.

HOW TO CHANGE THE BACKGROUND COLOR OF A LINK BUTTON ON MOUSE OVER

style type="text/css">
    .customhover a
    {
                background-color: Transparent;
    }
    .customhover a:hover
    {
        background-color: #CCFFFF;
        color:Black;
          border:solid 1px black;
       
    }
   </style>

<td>
   <div class="customhover">
    <asp:LinkButton runat="server" ID="lnkBtnKitDefinition" Font-Size="11px" Font-Underline="False"
                                                                                    Font-Bold="false" Font-Names="Verdana" Text="Kit Definitions"></asp:LinkButton>
</div>
 </td>

HOW TO CHANGE THE IMAGE SOURCE OF AN IMAGE BUTTON ON MOUSE OVER

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

imgBtn_Rename.Attributes.Add("onmouseover", "this.src='images/icons/rename2.gif';")
imgBtn_Rename.Attributes.Add("onmouseout", "this.src='images/icons/rename.gif';")

  End Sub

<asp:ImageButton ID="imgBtn_Rename" runat="server" ImageUrl="~/images/icons/rename2.gif"
                    AlternateText="Rename" Height="20px"></asp:ImageButton>

HOW TO CALL A JAVASCRIPT FUNCTION FROM CODE BEHIND

   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

imgBtnViewAll.Attributes.Add("onclick", "return filesSelected('View');")

End Sub

<asp:ImageButton ID="imgBtnViewAll" runat="server" ImageUrl="~/images/docimages/move3.jpg"
                    AlternateText="Move To" Height="20px"></asp:ImageButton>

HERE WHEN IMAGE BUTTON WILL BE CLICKED THE  filesSelected METHOD PRESENT IN THE JAVA SCRIPT WILL BE CALLED WITH A STRING PARAMETER.

JAVA SCRIPT IN CODE BEHIND

Dim jscript As String = Nothing
            jscript += "<script>"
            jscript += "window.open('GetLogDetails.aspx','_blank')"
            jscript += "</script>"
            RegisterClientScriptBlock("submission", jscript)

SETTING THE DATAKEY VALUE OF A GRIDVIEW

DataKeyNames="Id,empname"

BINDING DATA IN A LITERAL CONTROL PRESENT INSIDE THE ITEM TEMPLATE OF GRIDVIEW

<asp:TemplateField Visible="false">
 <ItemTemplate>
  <asp:Literal runat="server" ID="ltlFileNameUrl" Text='<%#Eval("FileNameUrl") %>'></asp:Literal>
   </ItemTemplate>
   </asp:TemplateField>

FIND THE NO OF DAY IN A PARTICULAR MONTH OF A PARTICULAR YEAR

Dim iNumDays As Integer
            iNumDays =Date.DaysInMonth(YEAR, MONTH)

Authentication And Authorisation

Authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user's identity.
Authorization is the process of allowing an authenticated user access to resources. Authentication is always precedes to Authorization
It can be difficult for a new developer to know just where to start. In this article, we review the settings in ASP.net and Internet Information Services (IIS) that control authentication and authorization in ASP.net applications. 
An ASP.net application has two separate authentication layers. That is because ASP.net is not a standalone product. Rather it is a layer on top of IIS. All requests flow through IIS before they are handed to ASP.net. As a result, IIS can decide to deny access without the ASP.net process even knowing that someone requested a particular page. Here is an overview of the steps in the joint IIS and ASP.net authentication process.


  • IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.

  • Next IIS performs its own user authentication if it configured to do so. By default IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per - application basis with in IIS.

  • If the request is passed to ASP.net with an authenticated user, ASP.net checks to see whether impersonation is enabled. If impersonation is enabled, ASP.net acts as though it were the authenticated user. If not ASP.net acts with its own configured account.

  • Finally the identity from step 3 is used to request resources from the operating system. If ASP.net authentication can obtain all the necessary resources it grants the users request otherwise it is denied. Resources can include much more than just the ASP.net page itself you can also use .Net's code access security features to extend this authorization step to disk files, Registry keys and other resources.

  •  

  • As you can see several security authorities interact when the user requests and ASP.net page. If things are not behaving the way you think they should, it can be helpful to review this list and make sure you have considered all the factors involved
    Authentication providers Assuming IIS passes a request to ASP.net, what happens next? The answer depends on the configuration of ASP.net itself. The ASP.net architecture includes the concept of and authentication provider a piece of code whose job is to verify credentials and decide whether a particular request should be considered authenticated. Out of the box ASP.net gives you a choice of three different authentication providers.
    Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:
    <authentication mode="windows">authentication mode="passport">
    <
    authentication mode="forms">











    Windows authentication and IIS
    If you select windows authentication for your ASP.NET application, you also have to configure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods:
    Anonymous, basic digest, and windows integrated
    If you select anonymous authentication, IIS doesn't perform any authentication, Any one is allowed to access the ASP.NET application.
    If you select basic authentication, users must provide a windows username and password to connect. How ever this information is sent over the network in clear text, which makes basic authentication very much insecure over the internet.
    If you select digest authentication, users must still provide a windows user name and password to connect. However the password is hashed before it is sent across the network. Digest authentication requires that all users be running Internet Explorer 5 or later and that windows accounts to stored in active directory.
    If you select windows integrated authentication, passwords never cross the network. Users must still have a username and password, but the application uses either the Kerberos or challenge/response protocols authenticate the user. Windows-integrated authentication requires that all users be running internet explorer 3.01 or later Kerberos is a network authentication protocol. It is designed to provide strong authentication for client/server applications by using secret-key cryptography. Kerberos is a solution to network security problems. It provides the tools of authentication and strong cryptography over the network to help to secure information in systems across entire enterprise

    Passport authentication
    Passport authentication lets you to use Microsoft's passport service to authenticate users of your application. If your users have signed up with passport, and you configure the authentication mode of the application to the passport authentication, all authentication duties are offloaded to the passport servers.
    Passport uses an encrypted cookie mechanism to indicate authenticated users. If users have already signed into passport when they visit your site, they'll be considered authenticated by ASP.NET. Otherwise they'll be redirected to the passport servers to log in. When they are successfully log in, they'll be redirected back to your site
    To use passport authentication you have to download the Passport Software Development Kit (SDK) and install it on your server. The SDK can be found at http://msdn.microdoft.com/library/default.asp?url=/downloads/list/websrvpass.aps. It includes full details of implementing passport authentication in your own applications.
    Forms authentication Forms authentication provides you with a way to handle authentication using your own custom logic with in an ASP.NET application. The following applies if you choose forms authentication.
     


    1. When a user requests a page for the application, ASP.NET checks for the presence of a special session cookie. If the cookie is present, ASP.NET assumes the user is authenticated and processes the request.
    2. If the cookie isn't present, ASP.NET redirects the user to a web form you provide
    3. You can carry out whatever authentication, checks you like in your form. When the user is authenticated, you indicate this to ASP.NET by setting a property, which creates the special cookie to handle subsequent requests.