Serving Information Simply

Sunday 14 July 2013

Properties in c#


     Properties can be get and set values. The C# language provides them as a well-situated way to make things easier syntax. They are implemented as methods in the intermediate language. They are regular access points to a class from external code. Unlike fields, properties do not indicate storage locations. Instead, properties have accessors that identify the statements to be executed when their values are read or written.

-          These are Special procedures that looks like fields but internally a method

-          It allows to put a check on values entered to some field

-          Here we Use a value keyword to input the value inside a property.

Syntax 1

<scope> <return type> <property name>
{
                set
                {
                                fieldname=value;
}             
get
{
                return fieldname;
}
}

Syntax 2

<scope> <return type> <property name>
{
                set;get;
}


Properties can of three types
1.     read/write property (set,get)
2.     read only property (get)
3.     write only property (set)

Example

Create a class Employee having fields empid,name,basic. Use properties to manage data and return Salary.
Note: Whenever we use the values, best is Property

using System;
class Employee
{
    //fields
    int empid;
    string name;
    int basic;
    public int EmpId //property
    {
        set
        {
            empid = value;
        }
        get
        {
            return empid;
        }
    }

    public string Name
    {
        set
        {
            name = value;
        }
        get
        {
            return name;
        }

    }
    public int Basic
    {
        set
        {
            if (value < 5000)
                throw new Exception("Sorry! Basic can never be lesser than 5000");
            basic = value;
        }
        get
        {
            return basic;
        }
    }
    public double Salary
    {
        get
        {
            return basic * 2.5;
        }
    }

}

class PropertyTest
{
    public static void Main()
    {
        Employee e = new Employee();
        e.EmpId = 67;
        e.Name = "Abhinav Bajpai";
        e.Basic = 8000;
        Console.WriteLine("Salary is {0}", e.Salary);
    }
}

Example : Use properties without any field name

using System;
namespace PropCheck
{
    class Employee
    {
        public int EmpId //property
        {
            set;
            get;
        }

        public string Name
        {
            set;
            get;
        }
        public int Basic
        {
            set;
            get;

        }
        public double Salary
        {
            get
            {
                return Basic * 2.5;
            }
        }

    }

    class PropertyTest
    {
        public static void Main()
        {
            Employee e = new Employee();
            e.EmpId = 67;
            e.Name = "Abhinav Bajpai";
            e.Basic = 8000;
            Console.WriteLine("Salary is {0}", e.Salary);
        }
    }
}
summary
We sharp out two customs to use properties. Properties are a influential way to put back methods and present a more perceptive way to use your objects. They are a grouping of fields and methods on a conceptual level.

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

Thank you guys... keep visiting …. :)
If you like this post then please join this site and like it’s Facebook page for getting updates and contribute into the problem solving of members of this blog. You can also post your issues on this blog's Facebook page and can get the solutions.

Saturday 4 May 2013

Magic tables in sql server


The tables "INSERTED" and "DELETED" are called magic tables of the
SQL Server. We can not see these tables in the data base. But we can access these tables from the "TRIGGER".

Magic tables are used In SQL Server 6.5, 7.0 & 2000 versions with database Triggers only.
But, In SQL Server 2005, 2008 & 2008 R2 Versions magic tables can be use with Triggers and Non-Triggers also.

when we insert or delete any record from any table in SQL server then recently inserted or deleted data from table also inserted into inserted magic table or deleted magic table with help of which we can recover data which is recently used to modify data into table either use in delete, insert or update to table.

Types of Magic tables:-

Basically there are two types of magic table in SQL server namely: inserted and deleted, update can be performed with help of these twos. Generally we cannot see these two table, we can only see it with the help Trigger's in SQL server.


Using with Triggers:

While using triggers these Inserted & Deleted tables (Called as magic tables) will be created automatically.

When we insert any record then that record will be added into this Inserted table initially, similarly while Updating a record a new entry will be inserted into Inserted table & old value will be inserted into deleted table.

In the case of deletion of a record then it will insert that record in the Deleted table.

These magic tables are used inside the Triggers for tracking the data transaction.

Using with Non-Triggers:

You can also use the Magic tables with Non-Trigger activities using OUTPUT Clause in SQL Server 2005, 2008 & 2008 R2 versions.

Following code defines  the magic table "INSERTED"




CREATE TRIGGER CreateMessage
ON EMPLOYEE
FOR INSERT
AS
   DECLARE @EMP_NAME varchar(50)
   SELECT @EMP_NAME= (SELECT EMP_NAME FROM INSERTED)
   INSERT INTO LOGTABLE(UserId,Message) values (@EMP_NAME,'Record Added')
GO

Following code Explain the magic table "DELETED"



CREATE TRIGGER CreateMessage
ON EMPLOYEE
FOR DELETE
AS
   DECLARE @EMP_NAME varchar(50)
   SELECT @EMP_NAME= (SELECT EMP_NAME FROM DELETED)
   INSERT INTO LOGTABLE(UserId,Message) values (@EMP_NAME,'Record Removed')
GO

Thank you guys... keep visiting …. :)
If you like this post then please join this site and like it’s Facebook page for getting updates and contributing into the problem solving of members of this blog. You can also post your issues on this blog's Facebook page and can get the solutions.

Sunday 14 April 2013

Caching Concept in ASP.NET


Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
Caching is extremely important for performance boosting in ASP.Net, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time.
You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources.
In short:-Caching is a feature that stores data in local memory, allowing incoming requests to be served from memory directly.

Benefits of Caching

The following are the benefits of using Caching
•         Faster page rendering
•         Minimization of database hits
•         Minimization of the consumption of server resources

Types of Caching:-

Caching in ASP.NET can be of the following types
•         Page Output Caching
•         Page Fragment Caching
•         Data Caching

Page Output Caching:

 Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.

Syntax of output caching

At design time:-

<%@ OutputCache Duration="no of seconds"  Location="Any | Client | Server | None" VaryByParam="parameter" %>

Programmetically:-

Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["EmployeeID"]= true;

Page Fragment Caching:

This type of caching is used with user controls in asp.net.

Syntax of fragment caching

 <%@ OutputCache  Duration="15"  VaryByParam="*" %>  
This directive is placed at the top of any User Control (.ascx file).
 Data Caching
 Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled.
 Example:-1

x=new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb");
x.Open();
y = new OleDbDataAdapter("select * from emp", x)
  ds = new DataSet();
  y.Fill(ds, "emp");
  Cache.Insert("abc", ds);
  ds =(DataSet) Cache["abc"];
  GridView1.DataSource = ds.Tables["emp"];
  GridView1.DataBind();

Example-2

OleDbConnection x;
 OleDbDataAdapter y;
 DataSet z;
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataSet z = new DataSet();
        Cache.Remove("abc"); 
        z=(DataSet)Cache["abc"];
        if(z != null)
        {
            GridView1.DataSource =z.Tables["emp"];
            GridView1.DataBind();
        }
        else
        {
            //z.Dispose();
            x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger");
            x.Open();
            y = new OleDbDataAdapter("select * from emp", x);
             z = new DataSet();
            y.Fill(z, "emp");
            Cache.Insert("abc", z);
            GridView1.DataSource = Cache["abc"];
            GridView1.DataBind();
            x.Close();
        }
    }

Cache Expirations
 Time Based Expiration
 This is used to specify a specific period of time for which the page would remain in the cache. The following statement specifies
such expiration for a page in the code behind of a file using C#.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
Cache.Insert("userInfo", ds, null, DateTime.Now.AddMinutes(2),
NoSlidingExpiration, CacheItemPriority.High,
CacheItemPriorityDecay.Slow, onRemove);
 The Cache Class
 The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Cache class contains the following properties and methods.
 Properties
•         Count
•         Item
 Methods
 •         Add
•         Equals
•         Get
•         GetEnumerator
•         GetHashCode
•         GetType
•         Insert
•         Remove (Overloaded)
•         ToString
-------------------------------------------------------------------------------------
 Thank you guys... keep visiting ….:)
If you like this post then please join this site and like it’s Facebook page for getting updates and contributing into the problem solving of members of this blog.you can also post your issues on this blog's Facebook page and can get the solutions.



Wednesday 13 March 2013

Reflection in C#


It is a powerful  way of collecting and manipulate information present in
Application’s assemblies and its metadata. Metadata contain all the Type
Information used by the application.

What is Reflection?

Reflection is the ability to find out information about objects, the
application details (assemblies), its metadata at run-time.

How to use Reflection in our applications?

Namespace :- System.Reflection
The Type class Base for all reflection.

Classes:-

Assembly Class: Assembly Class can be used to get the information and
Manipulate the assembly.

Module Class: Module Class is used for the reflection of the module.
This class is used to get information about parent assembly, classes in the module, all the global methods available in the classes.

ConstructorInfo Class:It is used for the reflection of a constructor, and used to fetch the information about constructor also constructor can be invoked.
Constructor information like name, parameters, access modifiers, and various implementation details (such as abstract or virtual) can be obtained.

MethodInfo Class : It is used to obtain information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details  (such as abstract or virtual) of a any method inside the class, module,  assembly. GetMethods or GetMethod method of a Type are used to on the to obtain the information.

fieldInfo Class
EventInfo Class
PropertyInfo Class
ParameterInfo Class

eg:-private void Form1_Load(object sender, EventArgs e)
        {
            int i = 42;

            System.Type type = i.GetType();
            MessageBox.Show(type.ToString());
            MethodInfo[] t= type.GetMethods();
            MessageBox.Show(t[0].ToString()); 
 
  Assembly x=Assembly.LoadFrom(@"C:\Documents and Settings\abhinav\My Documents\Visual Studio
2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe");

  MessageBox.Show(x.FullName);
  MessageBox.Show(x.CodeBase);
   MessageBox.Show(x.EntryPoint.Name.ToString());
    MessageBox.Show(x.FullName.ToString());

  Type[] t = x.GetTypes();
   foreach (Type y in t)
          {
              MessageBox.Show(y.ToString());
          }
        Module[] p = x.GetModules();
          foreach (Module z in p)
          {
   MessageBox.Show(z.ToString());
          }

          Type gt = typeof(System.String);
          // Constructors.
          ConstructorInfo[] t9 = gt.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
          foreach (MemberInfo memberInformationDetails in t9)
          {
              MessageBox.Show(memberInformationDetails.ToString());
          } 
        }

================

WindowsFormsApplication1.Form1 x = new WindowsFormsApplication1.Form1();
            Type t=x.GetType();
            MessageBox.Show(t.Assembly.FullName.ToString());
            MessageBox.Show(t.BaseType.Name.ToString());
            MethodInfo[] y=t.GetMethods();
            foreach (MethodInfo MI in y)
            {
                MessageBox.Show(MI.ToString());  
            }
            ConstructorInfo[] p1 = t.GetConstructors();
            foreach (ConstructorInfo CI in p1)
            {
                MessageBox.Show(ppp.ToString());
            }
---------------------------------------------------------------------------------------
 Thank you guys... keep visiting ….:)
If you like this post then please join this site and like it’s Facebook page for getting updates.