Quick View for finding the help for Dotnet
Monday, February 3, 2014
Remove spaces between two string
In PHP we have so many functions which are related to strings. The below examples explains how to remove the spaces between string.
1. str_replace
2. preg_replace.
str_replace:
This replaces the empty spaces. this can be used partially.
Example:
$string = str_replace(' ', '', $string);
preg_replace:
This will replace the nth spaces and removes the white spaces within all the string.
Example:
$string = preg_replace('/\s+/', '', $string);
Wednesday, February 23, 2011
C# custom control and user contorl
* What are user controls?
* What are custom controls?
* What are the basic differences between user controls and custom controls?
I'll also introduce a few of the advanced topics that concern custom controls, such as state management and the rendering of custom controls.
Back to the top
What are user controls?
User controls are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms page works. For more details about the Web Forms programming model, visit the following Microsoft Developer Network (MSDN) Web sites:
Introduction to Web Forms pages
http://msdn2.microsoft.com/en-us/library/65tcbxz3(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/65tcbxz3(vs.71).aspx)
Web Forms code model
http://msdn2.microsoft.com/en-us/library/015103yb(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/015103yb(vs.71).aspx)
How to create a user control
The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the <?html>, <?body>, and <?form> elements since a Web Forms page hosts the user control. To create a user control, follow these steps:
1. Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
script language="C#" runat="server"
public void button1_Click(object sender, EventArgs e)
{
label1.Text = "Hello World!!!";
}
<?/script>
2. Create a user interface for the user control.
<?asp:Label id="label1" runat="server"/>
<?br><?br>
<?asp:button id="button1" text="Hit" OnClick="button1_Click" runat="server" />
How to use a user control in a Web Forms page
1. Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft Visual Studio 2005, or any text editor.
2. Declare the @ Register directive. For example, use the following code.
<?%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
Note Assume that the user control and the Web Forms page are in the same location.
3. To use the user control in the Web Forms page, use the following code after the @ Register directive.
<?html>
<?body>
<?form runat="server">
<?UC:TestControl id="Test1" runat="server"/>
<?/form>
<?/body>
<?/html>
How to create an instance of a user control programmatically in the code behind file of a Web Forms page
The previous example instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:
1. Create a new Web Forms page in Visual Studio.
2. Navigate to the code behind file generated for this Web Forms page.
3. In the Page_Load event of the Page class, write the following code.
// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");
// Add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.
For more information, visit the following Web sites:
Adding controls to a Web Forms page programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/kyt0fzt1(vs.71).aspx)
Control execution lifecycle
http://msdn2.microsoft.com/en-us/library/aa719775(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/aa719775(vs.71).aspx)
Dynamic Web controls, postbacks, and view state, by Scott Mitchell
http://aspnet.4guysfromrolla.com/articles/092904-1.aspx (http://aspnet.4guysfromrolla.com/articles/092904-1.aspx)
How a user control is processed
When a page with a user control is requested, the following occurs:
* The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that derives from the System.Web.UI.UserControl class.
* The parser then dynamically compiles the class into an assembly.
* If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the file is precompiled by the designer itself.
* Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.
Back to the top
What are custom controls?
Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.
How to choose the base class for your custom control
To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:
* You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, <?meta> and <?head> are examples of nonvisual rendering.
* You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.
If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.
In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.
How to create and use a simple custom control that extends from System.Web.UI.Control using Visual Studio
1. Start Visual Studio.
2. Create a class library project, and give it a name, for example, CustomServerControlsLib.
3. Add a source file to the project, for example, SimpleServerControl.cs.
4. Include the reference of the System.Web namespace in the references section.
5. Check whether the following namespaces are included in the SimpleServerControl.cs file.
System
System.Collections
System.ComponentModel
System.Data
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls
6. Inherit the SimpleServerControls class with the Control base class.
public class SimpleServerControl : Control
7. Override the Render method to write the output to the output stream.
protected override void Render(HtmlTextWriter writer)
{
writer.Write("Hello World from custom control");
}
Note The HtmlTextWriter class has the functionality of writing HTML to a text stream. The Write method of the HtmlTextWriter class outputs the specified text to the HTTP response stream and is the same as the Response.Write method.
8. Compile the class library project. It will generate the DLL output.
9. Open an existing or create a new ASP.NET Web application project.
10. Add a Web Forms page where the custom control can be used.
11. Add a reference to the class library in the references section of the ASP.NET project.
12. Register the custom control on the Web Forms page.
<?%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>
13. To instantiate or use the custom control on the Web Forms page, add the following line of code in the <?form> tags.
<?form id="Form1" method="post" runat="server">
<?CC:SimpleServerControl id="ctlSimpleControl" runat="server">
<?/CC:SimpleServerControl >
<?/form>
Note In this code, SimpleServerControl is the control class name inside the class library.
14. Run the Web Forms page, and you will see the output from the custom control.
If you are not using Visual Studio, you need to perform the following steps:
1. Open any text editor.
2. Create a file named SimpleServerControl.cs, and write the code as given in steps 1 through 14.
3. In the PATH variable, add the following path:
c:\windows (winnt)\Microsoft.Net\Framework\v1.1.4322
4. Start a command prompt, and go to the location where SimpleServerControl.cs is present.
5. Run the following command:
csc /t:library /out: CustomServerControlsLib. SimpleServerControl.dll /r:System.dll /r:System.Web.dll SimpleServerControl.cs
For more information about the C# compiler (csc.exe), visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/1700bbwd(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/1700bbwd(vs.71).aspx)
6. To run the custom control on the Web Forms page, do the following:
1. Create a directory under the wwwroot folder.
2. Start Microsoft Internet Information Services (IIS) Manager, and mark the new directory as the virtual root directory.
3. Create a Bin folder under the new directory.
4. Copy the custom control DLL into the Bin folder.
5. Place the sample Web Forms page that you created in the previous steps inside the new directory.
6. Run the sample page from IIS Manager.
Now that you have built a simple custom control, let's look at how to expose properties and apply design-time attributes on that custom control.
How to expose properties on the custom control
I will build on the previous example and introduce one or more properties that can be configured while using the custom control on the Web Forms page.
The following example shows how to define a property that will display a message from the control a certain number of times, as specified in the property of the control:
1. Open SimpleServerControl.cs in a text editor.
2. Add a property in the SimpleServerControl class.
public class SimpleServerControl : Control
{
private int noOfTimes;
public int NoOfTimes
{
get { return this.noOfTimes; }
set { this.noOfTimes = value; }
}
protected override void Render (HtmlTextWriter writer)
{
for (int i=0; i<? NoOfTimes; i++)
{
write.Write("Hello World.."+"<?BR>");
}
}
}
3. Compile the custom control.
4. To use the custom control on the Web Forms page, add the new property to the control declaration.
<?CC:SimpleServerControl id="ctlSimpleControl" NoOfTimes="5" runat="server"><?/CC:SimpleServerControl>
5. Running the page will display the message "Hello world" from the custom control as many times as specified in the property of the control.
How to apply design-time attributes on the custom control
Why design-time attributes are needed
The custom control that you built in the previous example works as expected. However, if you want to use that control in Visual Studio, you may want the NoOfTimes property to be automatically highlighted in the Properties window whenever the custom control is selected at design time.
To make this happen, you need to provide the metadata information to Visual Studio, which you can do by using a feature in Visual Studio called attributes. Attributes can define a class, a method, a property, or a field. When Visual Studio loads the custom control's class, it checks for any attributes defined at the class, method, property, or field level and changes the behavior of the custom control at design time accordingly.
To find more information about attributes, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/Aa288059(VS.71).aspx (http://msdn2.microsoft.com/en-us/library/Aa288059(VS.71).aspx)
Let's build a sample that uses commonly used attributes:
1. Open SimpleServerControl.cs in a text editor.
2. Introduce some basic attributes at the class level, for example, DefaultProperty, ToolboxData, and TagPrefixAttrbute. We'll build our sample on these three attributes.
[
// Specify the default property for the control.
DefaultProperty("DefaultProperty"),
// Specify the tag that is written to the aspx page when the
// control is dragged from the Toolbox to the Design view.
// However this tag is optional since the designer automatically
// generates the default tag if it is not specified.
ToolboxData("<{0}:ControlWithAttributes runat=\"server\">" +
"{0}:ControlWithAttributes>")
]
public class ControlWithAttributes : Control
{
private string _defaultProperty;
public string DefaultProperty
{
get { return "This is a default property value"; }
set { this._defaultProperty = value; }
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("Default Property --> <?B>" +
DefaultProperty + "<?/B>");
}
}
3. There is one more tag called TagPrefixAttrbute. It is an assembly-level attribute that provides a prefix to a tag when you drag the control from the Toolbox to the designer. Otherwise, the designer generates a prefix such as "cc1" by default. TagPrefixAttrbute is not directly applied to the control class. To apply TagPrefixAttrbute, open AssemblyInfo.cs, include the following line of code, and then rebuild the project.
[assembly:TagPrefix("ServerControlsLib ", "MyControl")]
Note If you want to build the source using the command line, you need to create the AssemblyInfo.cs file, place the file in the directory that contains all the source files, and run the following command to build the control:
> csc /t:library /out: ServerControlsLib.dll /r:System.dll /r :System.Web.dll *.cs
Source taken from http://support.microsoft.com/kb/893667
* What are custom controls?
* What are the basic differences between user controls and custom controls?
I'll also introduce a few of the advanced topics that concern custom controls, such as state management and the rendering of custom controls.
Back to the top
What are user controls?
User controls are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms page works. For more details about the Web Forms programming model, visit the following Microsoft Developer Network (MSDN) Web sites:
Introduction to Web Forms pages
http://msdn2.microsoft.com/en-us/library/65tcbxz3(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/65tcbxz3(vs.71).aspx)
Web Forms code model
http://msdn2.microsoft.com/en-us/library/015103yb(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/015103yb(vs.71).aspx)
How to create a user control
The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the <?html>, <?body>, and <?form> elements since a Web Forms page hosts the user control. To create a user control, follow these steps:
1. Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
script language="C#" runat="server"
public void button1_Click(object sender, EventArgs e)
{
label1.Text = "Hello World!!!";
}
<?/script>
2. Create a user interface for the user control.
<?asp:Label id="label1" runat="server"/>
<?br><?br>
<?asp:button id="button1" text="Hit" OnClick="button1_Click" runat="server" />
How to use a user control in a Web Forms page
1. Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft Visual Studio 2005, or any text editor.
2. Declare the @ Register directive. For example, use the following code.
<?%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
Note Assume that the user control and the Web Forms page are in the same location.
3. To use the user control in the Web Forms page, use the following code after the @ Register directive.
<?html>
<?body>
<?form runat="server">
<?UC:TestControl id="Test1" runat="server"/>
<?/form>
<?/body>
<?/html>
How to create an instance of a user control programmatically in the code behind file of a Web Forms page
The previous example instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:
1. Create a new Web Forms page in Visual Studio.
2. Navigate to the code behind file generated for this Web Forms page.
3. In the Page_Load event of the Page class, write the following code.
// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");
// Add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.
For more information, visit the following Web sites:
Adding controls to a Web Forms page programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/kyt0fzt1(vs.71).aspx)
Control execution lifecycle
http://msdn2.microsoft.com/en-us/library/aa719775(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/aa719775(vs.71).aspx)
Dynamic Web controls, postbacks, and view state, by Scott Mitchell
http://aspnet.4guysfromrolla.com/articles/092904-1.aspx (http://aspnet.4guysfromrolla.com/articles/092904-1.aspx)
How a user control is processed
When a page with a user control is requested, the following occurs:
* The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that derives from the System.Web.UI.UserControl class.
* The parser then dynamically compiles the class into an assembly.
* If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the file is precompiled by the designer itself.
* Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.
Back to the top
What are custom controls?
Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.
How to choose the base class for your custom control
To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:
* You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, <?meta> and <?head> are examples of nonvisual rendering.
* You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.
If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.
In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.
How to create and use a simple custom control that extends from System.Web.UI.Control using Visual Studio
1. Start Visual Studio.
2. Create a class library project, and give it a name, for example, CustomServerControlsLib.
3. Add a source file to the project, for example, SimpleServerControl.cs.
4. Include the reference of the System.Web namespace in the references section.
5. Check whether the following namespaces are included in the SimpleServerControl.cs file.
System
System.Collections
System.ComponentModel
System.Data
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls
6. Inherit the SimpleServerControls class with the Control base class.
public class SimpleServerControl : Control
7. Override the Render method to write the output to the output stream.
protected override void Render(HtmlTextWriter writer)
{
writer.Write("Hello World from custom control");
}
Note The HtmlTextWriter class has the functionality of writing HTML to a text stream. The Write method of the HtmlTextWriter class outputs the specified text to the HTTP response stream and is the same as the Response.Write method.
8. Compile the class library project. It will generate the DLL output.
9. Open an existing or create a new ASP.NET Web application project.
10. Add a Web Forms page where the custom control can be used.
11. Add a reference to the class library in the references section of the ASP.NET project.
12. Register the custom control on the Web Forms page.
<?%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>
13. To instantiate or use the custom control on the Web Forms page, add the following line of code in the <?form> tags.
<?form id="Form1" method="post" runat="server">
<?CC:SimpleServerControl id="ctlSimpleControl" runat="server">
<?/CC:SimpleServerControl >
<?/form>
Note In this code, SimpleServerControl is the control class name inside the class library.
14. Run the Web Forms page, and you will see the output from the custom control.
If you are not using Visual Studio, you need to perform the following steps:
1. Open any text editor.
2. Create a file named SimpleServerControl.cs, and write the code as given in steps 1 through 14.
3. In the PATH variable, add the following path:
c:\windows (winnt)\Microsoft.Net\Framework\v1.1.4322
4. Start a command prompt, and go to the location where SimpleServerControl.cs is present.
5. Run the following command:
csc /t:library /out: CustomServerControlsLib. SimpleServerControl.dll /r:System.dll /r:System.Web.dll SimpleServerControl.cs
For more information about the C# compiler (csc.exe), visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/1700bbwd(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/1700bbwd(vs.71).aspx)
6. To run the custom control on the Web Forms page, do the following:
1. Create a directory under the wwwroot folder.
2. Start Microsoft Internet Information Services (IIS) Manager, and mark the new directory as the virtual root directory.
3. Create a Bin folder under the new directory.
4. Copy the custom control DLL into the Bin folder.
5. Place the sample Web Forms page that you created in the previous steps inside the new directory.
6. Run the sample page from IIS Manager.
Now that you have built a simple custom control, let's look at how to expose properties and apply design-time attributes on that custom control.
How to expose properties on the custom control
I will build on the previous example and introduce one or more properties that can be configured while using the custom control on the Web Forms page.
The following example shows how to define a property that will display a message from the control a certain number of times, as specified in the property of the control:
1. Open SimpleServerControl.cs in a text editor.
2. Add a property in the SimpleServerControl class.
public class SimpleServerControl : Control
{
private int noOfTimes;
public int NoOfTimes
{
get { return this.noOfTimes; }
set { this.noOfTimes = value; }
}
protected override void Render (HtmlTextWriter writer)
{
for (int i=0; i<? NoOfTimes; i++)
{
write.Write("Hello World.."+"<?BR>");
}
}
}
3. Compile the custom control.
4. To use the custom control on the Web Forms page, add the new property to the control declaration.
<?CC:SimpleServerControl id="ctlSimpleControl" NoOfTimes="5" runat="server"><?/CC:SimpleServerControl>
5. Running the page will display the message "Hello world" from the custom control as many times as specified in the property of the control.
How to apply design-time attributes on the custom control
Why design-time attributes are needed
The custom control that you built in the previous example works as expected. However, if you want to use that control in Visual Studio, you may want the NoOfTimes property to be automatically highlighted in the Properties window whenever the custom control is selected at design time.
To make this happen, you need to provide the metadata information to Visual Studio, which you can do by using a feature in Visual Studio called attributes. Attributes can define a class, a method, a property, or a field. When Visual Studio loads the custom control's class, it checks for any attributes defined at the class, method, property, or field level and changes the behavior of the custom control at design time accordingly.
To find more information about attributes, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/Aa288059(VS.71).aspx (http://msdn2.microsoft.com/en-us/library/Aa288059(VS.71).aspx)
Let's build a sample that uses commonly used attributes:
1. Open SimpleServerControl.cs in a text editor.
2. Introduce some basic attributes at the class level, for example, DefaultProperty, ToolboxData, and TagPrefixAttrbute. We'll build our sample on these three attributes.
[
// Specify the default property for the control.
DefaultProperty("DefaultProperty"),
// Specify the tag that is written to the aspx page when the
// control is dragged from the Toolbox to the Design view.
// However this tag is optional since the designer automatically
// generates the default tag if it is not specified.
ToolboxData("<{0}:ControlWithAttributes runat=\"server\">" +
"{0}:ControlWithAttributes>")
]
public class ControlWithAttributes : Control
{
private string _defaultProperty;
public string DefaultProperty
{
get { return "This is a default property value"; }
set { this._defaultProperty = value; }
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("Default Property --> <?B>" +
DefaultProperty + "<?/B>");
}
}
3. There is one more tag called TagPrefixAttrbute. It is an assembly-level attribute that provides a prefix to a tag when you drag the control from the Toolbox to the designer. Otherwise, the designer generates a prefix such as "cc1" by default. TagPrefixAttrbute is not directly applied to the control class. To apply TagPrefixAttrbute, open AssemblyInfo.cs, include the following line of code, and then rebuild the project.
[assembly:TagPrefix("ServerControlsLib ", "MyControl")]
Note If you want to build the source using the command line, you need to create the AssemblyInfo.cs file, place the file in the directory that contains all the source files, and run the following command to build the control:
> csc /t:library /out: ServerControlsLib.dll /r:System.dll /r :System.Web.dll *.cs
Source taken from http://support.microsoft.com/kb/893667
Difference Between Truncate and Delete
There are many differences between the two.
DELETE is a logged operation on a per row basis. This means
that the deletion of each row gets logged and physically deleted.
You can DELETE any row that will not violate a constraint, while leaving the foreign key or any other contraint in place.
TRUNCATE is also a logged operation, but in a different way.
TRUNCATE logs the deallocation of the data pages in which the data
exists. The deallocation of data pages means that your data
rows still actually exist in the data pages, but the
extents have been marked as empty for reuse. This is what
makes TRUNCATE a faster operation to perform over DELETE.
You cannot TRUNCATE a table that has any foreign key
constraints. You will have to remove the contraints, TRUNCATE the
table, and reapply the contraints.
TRUNCATE will reset any identity columns to the default seed
value. This means if you have a table with an identity column and
you have 264 rows with a seed value of 1, your last record will have
the value 264 (assuming you started with value 1) in its identity
columns. After TRUNCATEing your table, when you insert a new
record into the empty table, the identity column will have a value of
1. DELETE will not do this. In the same scenario, if you
DELETEd your rows, when inserting a new row into the empty table, the
identity column will have a value of 265.
DELETE is a logged operation on a per row basis. This means
that the deletion of each row gets logged and physically deleted.
You can DELETE any row that will not violate a constraint, while leaving the foreign key or any other contraint in place.
TRUNCATE is also a logged operation, but in a different way.
TRUNCATE logs the deallocation of the data pages in which the data
exists. The deallocation of data pages means that your data
rows still actually exist in the data pages, but the
extents have been marked as empty for reuse. This is what
makes TRUNCATE a faster operation to perform over DELETE.
You cannot TRUNCATE a table that has any foreign key
constraints. You will have to remove the contraints, TRUNCATE the
table, and reapply the contraints.
TRUNCATE will reset any identity columns to the default seed
value. This means if you have a table with an identity column and
you have 264 rows with a seed value of 1, your last record will have
the value 264 (assuming you started with value 1) in its identity
columns. After TRUNCATEing your table, when you insert a new
record into the empty table, the identity column will have a value of
1. DELETE will not do this. In the same scenario, if you
DELETEd your rows, when inserting a new row into the empty table, the
identity column will have a value of 265.
Wednesday, January 19, 2011
C# OOPS Concepts
OOPS Concept mainly covers Inheritance, Abstraction, Polymorphism.
Inheritance is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects.a parent class can inherit its behavior and state to children classes. This concept was developed to manage generalization and specialization in OOP and is represented by a is-a relationship.
The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. Thus inheritance provides a mechanism for class level re-usability.
When using Inheritance we use the Access Keywords
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
NOTE
# A static member cannot be marked as override, virtual, or abstract. So following is an error:
public static virtual void GetID()
# You can't call static methods of base class from derived class using base keyword.
#Virtual or abstract members cannot be private.
Inheritance makes code elegant and less repetitive
Sealed class
A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed.
Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use". An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.
Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.
Virtual keyword
The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
Override keyword
Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.
Difference between Interface and Abstract Class
* Interfaces are closely related to abstract classes that have all members abstract.
* For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods.
* For an interface, all the methods must be abstract
* Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class
* In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once.
* An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
* Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
* Class members that implement the interface members must be publicly accessible.
Inheritance is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects.a parent class can inherit its behavior and state to children classes. This concept was developed to manage generalization and specialization in OOP and is represented by a is-a relationship.
The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. Thus inheritance provides a mechanism for class level re-usability.
When using Inheritance we use the Access Keywords
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
NOTE
# A static member cannot be marked as override, virtual, or abstract. So following is an error:
public static virtual void GetID()
# You can't call static methods of base class from derived class using base keyword.
#Virtual or abstract members cannot be private.
Inheritance makes code elegant and less repetitive
Sealed class
A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed.
Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use". An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.
Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.
Virtual keyword
The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
Override keyword
Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.
Difference between Interface and Abstract Class
* Interfaces are closely related to abstract classes that have all members abstract.
* For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods.
* For an interface, all the methods must be abstract
* Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class
* In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once.
* An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
* Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
* Class members that implement the interface members must be publicly accessible.
Thursday, January 13, 2011
Nunit Test Example
When you are working with the Nunit Testing, we need to have Nunit installed in our machine.below example demonstrated how to write a Nunit test case.
First open the microsoft visual studio and select the New project and select the Class library. Change the name of the Class name to your respected name.Click OK.
before writing a code always use a namespace which is a good way of writing a code.
The below code is written in the C# language
The First Class library :
using System;
namespace MyApp
{
public class MyMath
{
public int Add(int i, int j)
{
return i + j;
}
}
}
Compile the code and make sure where you have saved the files.
Now create an another class library with the same above process we have done.The code inside the class library should contain as below code. Before you proceed you need to add the previous class library DLL as a reference and Add the Nunit Test DLL as a reference as you have done for Class library.
The Unit Test Reference is mandatory and the Previous class DLL(first class library you have created, whose methods you want to use), After adding the refereces add the code as below.
Second Class Library which contains Nunit reference
using System;
using NUnit.Framework;
using MyAppTest;
using MyApp;
namespace MyAppTest
{
[TestFixture]
public class Class1
{
[Test]
public void MyAddTest()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 8,"Both are wrong");
}
[Test]
public void MyAddTest2()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 5, "Both are correct");
}
[Test]
public void MyAddTest3()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 6, "Both are wrong");
}
}
}
After you are compiling this code. open the Nunit Editor. Click on New project and add the Compiled DLL for that and click ok. After this Click on RUN, You will have a window which will show the Expected Results and the Actual Results.
Assertions are the way to test for fail-pass test. NUnit framework support following assertions:
Assert()
AssertEquals()
AssertNotNull()
AssertNotNull()
AssertNull()
AssertSame()
Fail()
Below is the attached image:
First open the microsoft visual studio and select the New project and select the Class library. Change the name of the Class name to your respected name.Click OK.
before writing a code always use a namespace which is a good way of writing a code.
The below code is written in the C# language
The First Class library :
using System;
namespace MyApp
{
public class MyMath
{
public int Add(int i, int j)
{
return i + j;
}
}
}
Compile the code and make sure where you have saved the files.
Now create an another class library with the same above process we have done.The code inside the class library should contain as below code. Before you proceed you need to add the previous class library DLL as a reference and Add the Nunit Test DLL as a reference as you have done for Class library.
The Unit Test Reference is mandatory and the Previous class DLL(first class library you have created, whose methods you want to use), After adding the refereces add the code as below.
Second Class Library which contains Nunit reference
using System;
using NUnit.Framework;
using MyAppTest;
using MyApp;
namespace MyAppTest
{
[TestFixture]
public class Class1
{
[Test]
public void MyAddTest()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 8,"Both are wrong");
}
[Test]
public void MyAddTest2()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 5, "Both are correct");
}
[Test]
public void MyAddTest3()
{
MyMath m = new MyMath();
Assert.AreSame(m.Add(2, 3), 6, "Both are wrong");
}
}
}
After you are compiling this code. open the Nunit Editor. Click on New project and add the Compiled DLL for that and click ok. After this Click on RUN, You will have a window which will show the Expected Results and the Actual Results.
Assertions are the way to test for fail-pass test. NUnit framework support following assertions:
Assert()
AssertEquals()
AssertNotNull()
AssertNotNull()
AssertNull()
AssertSame()
Fail()
Below is the attached image:
Tuesday, January 11, 2011
Nunit Testing In Dotnet
NUnit is a Nunit-testing framework for all .Net languages.You can download it from http://www.nunit.org. The NUnit framework is developed from ground up to make use of .NET framework functionalities. It uses an Attribute based programming model. It loads test assemblies in separate application domain hence we can test an application without restarting the NUnit test tools. The NUnit further watches a file/assembly change events and reload it as soon as they are changed. With these features in hand a developer can perform develop and test cycles sides by side.
we should understand what NUnit Framework is not:
* It is not Automated GUI tester.
* It is not a scripting language, all test are written in .NET supported language e.g. C#, VC, VB.NET, J# etc.
* It is not a benchmark tool.
* Passing the entire unit test suite does not mean software is production ready.
The Main Concepts in the Unit testing is:
1. Text Fixtures.
2. Test Cases.
Test Fixtures:
A Test fixture is used to group and run multiple tests that test a logical collection of functionality. Programmatically, a test fixture corresponds to a class that in turn contains unit tests as methods of the class. A Test Fixture class must have either a public default constructor or no constructor, which implicitly creates a public default constructor. Identify a class as a test fixture by decorating it with the [TestFixture] attribute.
Example Declaration of a Texture:
using System;
using NUnit.Framework;
namespace example.namespace
{
[TestFixture]
public class ExampleTestFixture
{
[Test]
public void TestExample()
{
// Your test here
}
[Test]
public void TestExample2()
{
// Your second test here
}
// etc...
}
}
Test Cases:
Test is the lowest building block of unit testing and tests a single piece of software functionality. Programmatically, a test corresponds to a method in the unit test code. You identify a test by decorating a method with the [Test] attribute.
Each test case will consist of three parts. The first part sets up the test by instantiating "Tester" objects that know how to parse ASP.NET. The second part loads the page from the web server, and the third part performs the test by using and making assertions about the testers.
Example Declaration of a Test Case:
[Test]
public void TestExample()
{
// First, instantiate "Tester" objects:
LabelTester label = new LabelTester("textLabel");
LinkButtonTester link = new LinkButtonTester("linkButton");
// Second, visit the page being tested:
Browser.GetPage("http://localhost/example.aspx");
// Third, use tester objects to test the page:
Assert.AreEqual("Not clicked.", label.Text);
link.Click();
Assert.AreEqual("Clicked once.", label.Text);
link.Click();
Assert.AreEqual("Clicked twice.", label.Text);
}
we should understand what NUnit Framework is not:
* It is not Automated GUI tester.
* It is not a scripting language, all test are written in .NET supported language e.g. C#, VC, VB.NET, J# etc.
* It is not a benchmark tool.
* Passing the entire unit test suite does not mean software is production ready.
The Main Concepts in the Unit testing is:
1. Text Fixtures.
2. Test Cases.
Test Fixtures:
A Test fixture is used to group and run multiple tests that test a logical collection of functionality. Programmatically, a test fixture corresponds to a class that in turn contains unit tests as methods of the class. A Test Fixture class must have either a public default constructor or no constructor, which implicitly creates a public default constructor. Identify a class as a test fixture by decorating it with the [TestFixture] attribute.
Example Declaration of a Texture:
using System;
using NUnit.Framework;
namespace example.namespace
{
[TestFixture]
public class ExampleTestFixture
{
[Test]
public void TestExample()
{
// Your test here
}
[Test]
public void TestExample2()
{
// Your second test here
}
// etc...
}
}
Test Cases:
Test is the lowest building block of unit testing and tests a single piece of software functionality. Programmatically, a test corresponds to a method in the unit test code. You identify a test by decorating a method with the [Test] attribute.
Each test case will consist of three parts. The first part sets up the test by instantiating "Tester" objects that know how to parse ASP.NET. The second part loads the page from the web server, and the third part performs the test by using and making assertions about the testers.
Example Declaration of a Test Case:
[Test]
public void TestExample()
{
// First, instantiate "Tester" objects:
LabelTester label = new LabelTester("textLabel");
LinkButtonTester link = new LinkButtonTester("linkButton");
// Second, visit the page being tested:
Browser.GetPage("http://localhost/example.aspx");
// Third, use tester objects to test the page:
Assert.AreEqual("Not clicked.", label.Text);
link.Click();
Assert.AreEqual("Clicked once.", label.Text);
link.Click();
Assert.AreEqual("Clicked twice.", label.Text);
}
Subscribe to:
Posts (Atom)
