Friday, October 26, 2012

restrict download


The null coalescing operator: ??



This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows
string newValue = someValue ?? "default";
The first operand someValue must be a nullable type. The above code will set the value of newValue to someValueunless it's null, then it'll set it to "default".
You could also use this inline:

Console.WriteLine("The value is " + (someValue ?? "null"));


another use
return (bool)(ViewState["IsPaged"] ?? true);


If you really want to use an identifier that clashes with a keyword, you can qualify it with the @ prefix. For instance:
 class class  {...}    // illegal
 class @class {...}    // legal
The @ symbol doesn't form part of the identifier itself, so @myVariable is the same as myVariable. check out this example
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication7
{
   class Program
   {
       static void Main(string[] args)
       {
           int @int = 10;
           double @double = 10.121;
           float @float = (float)(@int + @double);
           Console.WriteLine(@float.ToString());
           Console.Read();

       }
   }
}

How to restrict download of specified file types in asp.net

In this post i will show you how to restrict your web app so that .txt (whatever file extensions you want ) files can not be downloaded. Open your web.config file and register following setting in your web.config
<system.web>
   <httpHandlers>
       <add verb="*" path="*.txt" type="System.Web.HttpForbiddenHandler" />
   </httpHandlers>
</system.web>
For more details how to register handler in web.config check out this link

Tuesday, July 24, 2012

CLR Stored Procedure


Introduction

We usually face a problem in Stored Procedures and other database objects when we need to implement some complicated logic within it. We found inefficient performance when we tried to implement complex logic & business rules in database objects. In many cases, we found C# or VB classes more powerful to implement such things. Microsoft has added a new feature to address such issues with SQL server 2005 called "CLR Stored Procedure". 

What is CLR Stored Procedure? 

Now, let us understand CLR stored procedure. CLR, as most .NET programmers know, is Common Language Runtime and Stored Procedures are routine stored procedures of database. Thus, CLR Stored Procedures are a combination of both. As we all know, Common Language Runtime is a core .NET component. The Common Language Runtime is runtime execution environment which supplies managed code with various services like cross language integration, code access security, lifetime management of object, resources management, threading, debugging & type safety, etc. So now, CLR Stored Procedures are .NET objects which run in the memory of database.
The very first usage of CLR Stored Procedures can be said is accessing system resources. Accessing system resources could also be done using Extended Stored Procedures which are again database objects like Stored Procedures, Functions, etc. Extended Stored Procedures can do most of the things which a standard executable program can do. Then, why have CLR Stored Procedures? The very first advantage of CLR Stored Procedures is that it is a managed object unlike Extended Stored Procedures, which are unmanaged objects. The common thing between them is that both run under database memory. In this way, CLR Stored Procedures give all the benefits of managed objects. The following screen explains memory allocation while executing a CLR Stored Procedure.

When Should We Use CLR Stored Procedure? 

Extended stored procedures run in the same process space as the database engine, memory leaks, bugs, etc. can affect the performance of database engine. CLR stored procedures resolve these issues as they are managed objects and run as per specifications of Common Language Runtime. CLR Stored Procedures can replace a standard stored procedure that contains complex logic and business rules. CLR Stored Procedures take benefit of .NET classes and thus make it easy to implement complex logic, calculation, intense string operations, complex iterations, data encryption, etc. that are difficult to obtain in standard stored procedures. Standard stored procedures are still best for data oriented tasks. CLR Stored Procedures not only include stored procedures but also include Functions, Triggers, etc. CLR Stored Procedures are compiled one so they give better performance.

Benefits of CLR Stored Procedures

  1. Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management, etc.
  2. CLR Stored Procedures are managed codes so ensures type safety, memory management, etc.
  3. Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism & inheritance.
  4. Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that the .NET Framework supports.
  5. CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.

Drawbacks of CLR Stored Procedures

  1. Not convenient in all contexts, for e.g. they should not be used to execute simple queries. In that case, standard stored procedures give better results.
  2. Deployment may be difficult in some scenarios.

Standard Stored Procedures vs. CLR Stored Procedures

You are the best judge when to use regular Stored Procedures and when to use CLR Stored Procedures. CLR Stored Procedures can be used in the following scenarios:
  1. When the program requires complex logic or business rules.
  2. When the flow is CPU intensive. CLR Stored Procedures give better results as they are in complied form and managed one.
  3. The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services, etc.
  4. In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.
  5. An operation requires higher data safety.
 Pass "context connection=true" as connection string in the constructor while creating new SqlConnection.

Run the Stored Procedure:
Make sure the CLR is enabled with your SQL Server by running the following SQL.
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;GO

convert.tostring vs tostring in c#


int someValue = 4;
// You can do this
txtSomeValue.Text = someValue.ToString();
// Or this...
txtSomeValue.Text = Convert.ToString(someValue);

int x =0; 
string s=x.ToString(); 
string Str=Convert.ToString(x); 

Here We can convert the integer “x” using “x.ToString()” or “Convert.ToString()” . But only The basic difference between them is “Convert” function handles NULLS while “x.ToString()” 
does not it will throw a NULL reference exception error. So as for good programming practice using “Convert” is always safe. 

String vs. StringBuilder


Since C# strings are immutable, an existing string cannot be modified. So, if one tries to change a string either with the concatenation operator (+) or with the InsertPadLeftPadRightReplace, or SubString methods, an entirely new string is created—leaving the original string intact.
Therefore, operations which would alter strings—instead—cause additional memory to be allocated. Memory is a scarce resource. And, memory allocations are expensive in terms of memory and performance. Consequently, sometimes String class usage should be avoided.
The StringBuilder class is designed for situations when one needs to work with a single string and make an arbitrary number of iterative changes to it. Many StringBuilder class methods are the same as those of the String class. However, the string content of aStringBuilder class can be changed without the necessity of allocating additional memory. Thus, operations on the StringBuilder class will be much faster than operations on the String class in certain situations. Paradoxically, just the the opposite can be true in other situations.
The String class is optimized and quite efficient for most cases. On the other hand, if strings must be modified, then the String class can be a real resource waster. It must be appreciated that the String class is really very intelligent in its memory handling in most everyday programming situations.

Saturday, July 21, 2012

ASP.NET 2.0 Page Life Cycle


ASP.NET 2.0 Page Life Cycle - The lifetime of an ASP.NET page is filled with events. A .NET technical interview might begin with this question. A series of processing steps takes place during this page life cycle. Following tasks are performed:

* Initialization
* Instantiation of controls
* Restoration & Maintainance of State
* Running Event Handlers
* Rendering of data to the browser
The life cycle may be broken down into Stages and Events. The stages reflect the broad spectrum of tasks performed. The following stages take place

1) Page Request - This is the first stage, before the page life cycle starts. Whenever a page is requested, ASP.NET detects whether the page is to be requested, parsed and compiled or whether the page can be cached from the system.
2) Start - In this stage, properties such as Request and Response are set. Its also determined at this stage whether the request is a new request or old, and thus it sets the IsPostBackproperty in the Start stage of the page life cycle.
3) Page Initialization - Each control of the page is assigned a unique identification ID. If there are themes, they are applied. Note that during the Page Initialization stage, neither postback data is loaded, nor any viewstate data is retrieved.
4) Load - If current request is a postback, then control values are retrieved from their viewstate.
5) Validation - The validate method of the validation controls is invoked. This sets the IsValidproperty of the validation control.
6) PostBack Event Handling - Event handlers are invoked, in case the request is a postback.
7) Rendering - Viewstate for the page is saved. Then render method for each control is called. A textwriter writes the output of the rendering stage to the output stream of the page's Response property.
8) Unload - This is the last stage in the page life cycle stages. It is invoked when the page is completely rendered. Page properties like Respone and Request are unloaded.

Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.

PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To setmaster pages dynamically. Gets and Sets profile propety values.
Init - Raised after all controls are initialized, and skin properties are set.
InitComplete - This event may be used, when we need to be sure that all initialization tasks are complete.
PreLoad - If processing on a control or a page is required before the Load event.
Load - invokes the OnLoad event on the page. The same is done for each child control on the page. May set properties of controls, create database connections.
Control Events - These are the control specific events, such as button clicks, listbox item selects etc.
LoadComplete - To execute tasks that require that the complete page has been loaded.
PreRender - Some methods are called before the PreRenderEvent takes place, likeEnsureChildControls, data bound controls that have a dataSourceId set also call the DataBindmethod.
Each control of the page has a PreRender event. Developers may use the prerender event to make final changes to the controls before it is rendered to the page.
SaveStateComplete - ViewState is saved before this event occurs. However, if any changes to the viewstate of a control is made, then this is the event to be used. It cannot be used to make changes to other properties of a control.
Render - This is a stage, not an event. The page object invokes this stage on each control of the page. This actually means that the ASP.NET server control's HTML markup is sent to the browser.
Unload - This event occurs for each control. It takes care of cleanup activities like wiping the database connectivities.

Abstract_and_Static_Class


Static Class :

May 11, 2011
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed and therefore cannot be inherited.
  • They cannot contain Instance Constructors (C# Programming Guide).
public static class Settings { static int i; public static string GetName() { return "MyName"; } } class Program { static void Main(string[] args) { string str=Settings.GetName(); Console.Write(str); Console.Read(); } }

Static Fields:

Static fields can be declared as follows by using the keyword static. class MyClass { public static int x; public static int y = 20; }
When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

For example

class MyClass { public static int x = 20; public static int y; public static int z = 25; public MyClass(int i) { x = i; y = i; z = i; } } class MyClient { public static void Main() { Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z); MyClass mc = new MyClass(25); Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z); } }

Static Method:

Static methods can be declared using Static keyword befor method name. The static methods can by accessed directly from the class. Static methods are normally faster to invoke on the call stack than instance methods
class MyClass { private static int x = 20; private static int y = 40; public static void Method() { Console.WriteLine("{0},{1}", x, y); } } class MyClient { public static void Main() { MyClass.Method(); } }

Abstract Class :

An abstract class is the one that is not used to create objects. An abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a design concept in program development and provides a base upon which other classes are built. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on it's own, it must be inherited. Like interfaces, abstract classes can specify members that must be implemented in inheriting classes. Unlike interfaces, a class can inherit only one abstract class. Abstract classes can only specify members that should be implemented by all inheriting classes.
Important :
  • An abstract class cannot be a sealed class or static.
  • Declarations of abstract methods are only allowed in abstract classes.
  • An abstract method cannot be private.
  • The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
public abstract class ABstractClass { static int i; public int GetValue(int first,int second) { return first + second; } } class Program : ABstractClass { static void Main(string[] args) { // Program sd = new Program (); // This will give error as you can not create instance of Static class Program cc = new Program(); int value = cc.GetValue(10, 20); Console.Write("Total : " + value.ToString()); Console.Read(); } }

Abstract method:

An abstract method is a method without any method body. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon. When a class inherits from an abstract class, the derived class must implement all the abstract methods declared in the base class. But by declaring the derived class also abstract, we can avoid the implementation of all or certain abstract methods. This is what is known as partial implementation of an abstract class
public abstract class Shape { public abstract void Paint(Graphics g, Rectangle r); } public class Ellipse : Shape { public override void Paint(Graphics g, Rectangle r) { g.DrawEllipse(r); } } public class Box : Shape { public override void Paint(Graphics g, Rectangle r) { g.DrawRect(r); } } http://thecodekey.com/C_VB_Codes/Abstract_and_Static_Class.aspx

Friday, July 20, 2012

SQL Server Index Basics


One of the most important routes to high performance in a SQL Server database is the index. Indexes speed up the querying process by providing swift access to rows in the data tables, similarly to the way a book’s index helps you find information quickly within that book. In this article, I provide an overview of SQL Server indexes and explain how they’re defined within a database and how they can make the querying process faster. Most of this information applies to indexes in both SQL Server 2005 and 2008; the basic structure has changed little from one version to the next. In fact, much of the information also applies to SQL Server 2000. This does not mean there haven’t been changes. New functionality has been added with each successive version; however, the underlying structures have remained relatively the same. So for the sake of brevity, I stick with 2005 and 2008 and point out where there are differences in those two versions.

Index Structures

Indexes are created on columns in tables or views. The index provides a fast way to look up data based on the values within those columns. For example, if you create an index on the primary key and then search for a row of data based on one of the primary key values, SQL Server first finds that value in the index, and then uses the index to quickly locate the entire row of data. Without the index, a table scan would have to be performed in order to locate the row, which can have a significant effect on performance.
You can create indexes on most columns in a table or a view. The exceptions are primarily those columns configured with large object (LOB) data types, such as imagetext, and varchar(max). You can also create indexes on XML columns, but those indexes are slightly different from the basic index and are beyond the scope of this article. Instead, I'll focus on those indexes that are implemented most commonly in a SQL Server database.
An index is made up of a set of pages (index nodes) that are organized in a B-tree structure. This structure is hierarchical in nature, with the root node at the top of the hierarchy and the leaf nodes at the bottom, as shown in Figure 1.
Figure 1: B-tree structure of a SQL Server index
When a query is issued against an indexed column, the query engine starts at the root node and navigates down through the intermediate nodes, with each layer of the intermediate level more granular than the one above. The query engine continues down through the index nodes until it reaches the leaf node. For example, if you’re searching for the value 123 in an indexed column, the query engine would first look in the root level to determine which page to reference in the top intermediate level. In this example, the first page points the values 1-100, and the second page, the values 101-200, so the query engine would go to the second page on that level. The query engine would then determine that it must go to the third page at the next intermediate level. From there, the query engine would navigate to the leaf node for value 123. The leaf node will contain either the entire row of data or a pointer to that row, depending on whether the index is clustered or nonclustered.

Clustered Indexes

A clustered index stores the actual data rows at the leaf level of the index. Returning to the example above, that would mean that the entire row of data associated with the primary key value of 123 would be stored in that leaf node. An important characteristic of the clustered index is that the indexed values are sorted in either ascending or descending order. As a result, there can be only one clustered index on a table or view. In addition, data in a table is sorted only if a clustered index has been defined on a table.
Note: A table that has a clustered index is referred to as a clustered table. A table that has no clustered index is referred to as a heap.

Nonclustered Indexes

Unlike a clustered indexed, the leaf nodes of a nonclustered index contain only the values from the indexed columns and row locators that point to the actual data rows, rather than contain the data rows themselves. This means that the query engine must take an additional step in order to locate the actual data.
A row locator’s structure depends on whether it points to a clustered table or to a heap. If referencing a clustered table, the row locator points to the clustered index, using the value from the clustered index to navigate to the correct data row. If referencing a heap, the row locator points to the actual data row.
Nonclustered indexes cannot be sorted like clustered indexes; however, you can create more than one nonclustered index per table or view. SQL Server 2005 supports up to 249 nonclustered indexes, and SQL Server 2008 support up to 999. This certainly doesn’t mean you should create that many indexes. Indexes can both help and hinder performance, as I explain later in the article.
In addition to being able to create multiple nonclustered indexes on a table or view, you can also add included columns to your index. This means that you can store at the leaf level not only the values from the indexed column, but also the values from non-indexed columns. This strategy allows you to get around some of the limitations on indexes. For example, you can include non-indexed columns in order to exceed the size limit of indexed columns (900 bytes in most cases).

Index Types

In addition to an index being clustered or nonclustered, it can be configured in other ways:
  • Composite index: An index that contains more than one column. In both SQL Server 2005 and 2008, you can include up to 16 columns in an index, as long as the index doesn’t exceed the 900-byte limit. Both clustered and nonclustered indexes can be composite indexes.
  • Unique Index: An index that ensures the uniqueness of each value in the indexed column. If the index is a composite, the uniqueness is enforced across the columns as a whole, not on the individual columns. For example, if you were to create an index on the FirstName and LastName columns in a table, the names together must be unique, but the individual names can be duplicated.
A unique index is automatically created when you define a primary key or unique constraint:
    • Primary key: When you define a primary key constraint on one or more columns, SQL Server automatically creates a unique, clustered index if a clustered index does not already exist on the table or view. However, you can override the default behavior and define a unique, nonclustered index on the primary key.
    • Unique: When you define a unique constraint, SQL Server automatically creates a unique, nonclustered index. You can specify that a unique clustered index be created if a clustered index does not already exist on the table.
  • Covering index: A type of index that includes all the columns that are needed to process a particular query. For example, your query might retrieve the FirstName and LastName columns from a table, based on a value in the ContactID column. You can create a covering index that includes all three columns.

Index Design

As beneficial as indexes can be, they must be designed carefully. Because they can take up significant disk space, you don’t want to implement more indexes than necessary. In addition, indexes are automatically updated when the data rows themselves are updated, which can lead to additional overhead and can affect performance. As a result, index design should take into account a number of considerations.

Database

As mentioned above, indexes can enhance performance because they can provide a quick way for the query engine to find data. However, you must also take into account whether and how much you’re going to be inserting, updating, and deleting data. When you modify data, the indexes must also be modified to reflect the changed data, which can significantly affect performance. You should consider the following guidelines when planning your indexing strategy:
  • For tables that are heavily updated, use as few columns as possible in the index, and don’t over-index the tables.
  • If a table contains a lot of data but data modifications are low, use as many indexes as necessary to improve query performance. However, use indexes judiciously on small tables because the query engine might take longer to navigate the index than to perform a table scan.
  • For clustered indexes, try to keep the length of the indexed columns as short as possible. Ideally, try to implement your clustered indexes on unique columns that do not permit null values. This is why the primary key is often used for the table’s clustered index, although query considerations should also be taken into account when determining which columns should participate in the clustered index.
  • The uniqueness of values in a column affects index performance. In general, the more duplicate values you have in a column, the more poorly the index performs. On the other hand, the more unique each value, the better the performance. When possible, implement unique indexes.
  • For composite indexes, take into consideration the order of the columns in the index definition. Columns that will be used in comparison expressions in the WHERE clause (such as WHERE FirstName = 'Charlie') should be listed first. Subsequent columns should be listed based on the uniqueness of their values, with the most unique listed first.
  • You can also index computed columns if they meet certain requirements. For example, the expression used to generate the values must be deterministic (which means it always returns the same result for a specified set of inputs). For more details about indexing computed columns, see the topic “Creating Indexes on Computed Columns” in SQL Server Books Online.

Queries

Another consideration when setting up indexes is how the database will be queried. As mentioned above, you must take into account the frequency of data modifications. In addition, you should consider the following guidelines:
  • Try to insert or modify as many rows as possible in a single statement, rather than using multiple queries.
  • Create nonclustered indexes on columns used frequently in your statement’s predicates and join conditions.
  • Consider indexing columns used in exact-match queries.

Index Basics

In this article, I’ve tried to give you a basic overview of indexing in SQL Server and provide some of the guidelines that should be considered when implementing indexes. This by no means is a complete picture of SQL Server indexing. The design and implementation of indexes are an important component of any SQL Server database design, not only in terms of what should be indexed, but where those indexes should be stored, how they should be partitioned, how data will be queried, and other important considerations. In addition, there are index types that I have not discussed, such as XML indexes as well as the filtered and spatial indexes supported in SQL Server 2008. This article, then, should be seen as a starting point, a way to familiarize yourself with the fundamental concepts of indexing. In the meantime, be sure to check out SQL Server Books Online for more information about the indexes described here as well as the other types of indexes.

Monday, March 5, 2012

ASP.NET 2.0 Page Life Cycle


ASP.NET 2.0 Page Life Cycle - The lifetime of an ASP.NET page is filled with events. A .NET technical interview might begin with this question. A series of processing steps takes place during this page life cycle. Following tasks are performed:

* Initialization
* Instantiation of controls
* Restoration & Maintainance of State
* Running Event Handlers
* Rendering of data to the browser
The life cycle may be broken down into Stages and Events. The stages reflect the broad spectrum of tasks performed. The following stages take place

1) Page Request - This is the first stage, before the page life cycle starts. Whenever a page is requested, ASP.NET detects whether the page is to be requested, parsed and compiled or whether the page can be cached from the system.
2) Start - In this stage, properties such as Request and Response are set. Its also determined at this stage whether the request is a new request or old, and thus it sets the IsPostBackproperty in the Start stage of the page life cycle.
3) Page Initialization - Each control of the page is assigned a unique identification ID. If there are themes, they are applied. Note that during the Page Initialization stage, neither postback data is loaded, nor any viewstate data is retrieved.
4) Load - If current request is a postback, then control values are retrieved from their viewstate.
5) Validation - The validate method of the validation controls is invoked. This sets the IsValidproperty of the validation control.
6) PostBack Event Handling - Event handlers are invoked, in case the request is a postback.
7) Rendering - Viewstate for the page is saved. Then render method for each control is called. A textwriter writes the output of the rendering stage to the output stream of the page's Response property.
8) Unload - This is the last stage in the page life cycle stages. It is invoked when the page is completely rendered. Page properties like Respone and Request are unloaded.

Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.

PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To setmaster pages dynamically. Gets and Sets profile propety values.
Init - Raised after all controls are initialized, and skin properties are set.
InitComplete - This event may be used, when we need to be sure that all initialization tasks are complete.
PreLoad - If processing on a control or a page is required before the Load event.
Load - invokes the OnLoad event on the page. The same is done for each child control on the page. May set properties of controls, create database connections.
Control Events - These are the control specific events, such as button clicks, listbox item selects etc.
LoadComplete - To execute tasks that require that the complete page has been loaded.
PreRender - Some methods are called before the PreRenderEvent takes place, likeEnsureChildControls, data bound controls that have a dataSourceId set also call the DataBindmethod.
Each control of the page has a PreRender event. Developers may use the prerender event to make final changes to the controls before it is rendered to the page.
SaveStateComplete - ViewState is saved before this event occurs. However, if any changes to the viewstate of a control is made, then this is the event to be used. It cannot be used to make changes to other properties of a control.
Render - This is a stage, not an event. The page object invokes this stage on each control of the page. This actually means that the ASP.NET server control's HTML markup is sent to the browser.
Unload - This event occurs for each control. It takes care of cleanup activities like wiping the database connectivities.