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.

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:

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);
}

Monday, January 10, 2011

Export Dataset to Excel

The Below code makes you more understand how can we export the Dataset values to an Excel Sheet

Initially we use the DataGridView to get the Data by Command Object. We then Create the DataSet and fil the Dataset with the Data we got from the DataGridView. Then we provide the button, By which clicking on that we can export the Data to the Excelsheet

Below code show you how to write a code for exporting

protected void Button1_Click(object sender, EventArgs e)

{

Response.Clear();

Response.Buffer = true;

Response.AddHeader("content-disposition",

"attachment;filename=GridViewExport.xls");

Response.Charset = "";

Response.ContentType = "application/vnd.ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

PrepareForExport(GridView1);

Table tb = new Table();

TableRow tr1 = new TableRow();

TableCell cell1 = new TableCell();

cell1.Controls.Add(GridView1);

tr1.Cells.Add(cell1);

TableCell cell2 = new TableCell();

cell2.Text = " ";

if (rbPreference.SelectedValue == "2")

{

tr1.Cells.Add(cell2);

tb.Rows.Add(tr1);

}

else

{

TableRow tr2 = new TableRow();

tr2.Cells.Add(cell2);

TableRow tr3 = new TableRow();

tb.Rows.Add(tr1);

tb.Rows.Add(tr2);

tb.Rows.Add(tr3);

}

tb.RenderControl(hw);



//style to format numbers to string

string style = @"";

Response.Write(style);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();

}

Thursday, January 6, 2011

Send Email in Asp.net

How to send email in Asp.net using c#. In Asp.net 2.0,email sending is very easy.In our websites we send a feedback,contact us,registration welcome,Forgot password, news letter etc. to the users mail.By using the Asp.net classes.
we can access to send the email.The Simple Mail Transfer Protocol(SMTP) server is used for deliver the mail
using the System.Net.Mail namespace.

In System.Net.Mail namespace having two sub classes MailMessage and SmptClient.

MailMessage contains the properties From,To,Subject,Body etc.

SmtpClient send the Mailmessage data to the SMTP server.

The SMTP server Store the emails in a queue.It sends the mail one after another.

The steps to send email:-
1.use the namespace.
using System.Net.Mail;
using System.Text;

2.use the MailMessage to send the mail with SMTP Connection Settings.

MailMessage mailmsg = new MailMessage("yourfromemail@yourdomain.in", "yourtoemail@domain.com");
SmtpClient smtpmail = new SmtpClient();

mailmsg.Subject = "Account information Verified";
StringBuilder bodyMsg = new StringBuilder();

bodyMsg.Append("br");
bodyMsg.Append("br");
bodyMsg.AppendFormat("Response From your domain name");
bodyMsg.Append("br");
bodyMsg.AppendFormat("sample Text Message for the Email ----- 1\n\n");
bodyMsg.Append("br");
bodyMsg.AppendFormat("sample Text Message for the Email----------- 2 !\n\n");
bodyMsg.Append("br");
bodyMsg.Append("sample Text Message for the Email --- 3");
bodyMsg.Append("br");
bodyMsg.AppendFormat("Registered Email:", "yourtoemail@domain.com");
bodyMsg.Append("br");
bodyMsg.Append("br");
bodyMsg.Append("br");
bodyMsg.Append("br");


mailmsg.Body = bodyMsg.ToString();
smtpmail.Host = "smtp.yourdomain.in";
smtpmail.Port = 587;
smtpmail.Send(mailmsg);

the mail will be send to the to address with some sample text information.

mailmsg.Subject is the subject of our mail.

mailmsg.Body contains the bodymsg string values.it attach the bodymsg with subject.

smtp.Host is your smtp server name for eg.

gmail smtp server is "smtp.gmail.com".

smtpmail.port is the port by sending the mail.

smtpmail.Send function is used to concatenate your message,subject and send the mail through the port with the smtp host address.

DataGridView binding with Databaset

Below is the sample example for binding the Dataset with the DataGridView.

string connectStr = "Server=Systemname\\SQLR2;Database=Practice_Temp;Trusted_Connection=Yes;";
SqlConnection conn = new SqlConnection(connectStr);
conn.Open();

SqlDataAdapter adap = new SqlDataAdapter("select * from Temp_Dataset", conn);
DataSet ds = new DataSet("dset");

adap.Fill(ds);//,"Tempee_Datset");
dataGridView1.DataSource = ds.Tables[0];

Sunday, January 2, 2011

C# Split Method

Here is the simple Code for split in C#

// string seperated by colons ';'
string info = "mark;smith;123 csharp drive;toronto;canada";

string[] arInfo = new string[4];

// define which character is seperating fields
char[] splitter = {';'};

arInfo = info.Split(splitter);

for(int x = 0; x < arInfo.Length; x++)
{
Response.Write(arInfo[x] + "<br>");
}


The below also does the same task but we using regulat Expression namespace

using System;
using System.Text.RegularExpressions;

class Program
{
static void Main()
{
string value = "abc\r\nffff\r\ntesting\r\nwelcome";
//
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
//
string[] lines = Regex.Split(value, "\r\n");

foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}