Tuesday, December 21, 2010

Expand-Collapse Gridview

Well I used to display data in the expand/expand gridview

protected void gdvwplansdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

ClsBO.ClsPlanBO objclsbo = new ClsBO.ClsPlanBO();
DataSet ds = objclsbo.GetCoursePlans(Convert.ToInt64(gdvwplansdetails.DataKeys[e.Row.RowIndex].Value.ToString()));
//string DetailsQuery = "SELECT p.title,p.duration,p.price,c.thumbnail_path FROM [tbl_bt_lesson_plan] as p, [tbl_bt_course] as c where p.plan_id = c.plan_id and p.plan_id = '18'";


//Here I am grabbing the additional data and putting it into mini datagrids...
//If you wish to just use labels, or other controls, just bind the data as you
//wish, and render to html as I did.
GridView NewDg = new GridView();
NewDg.AutoGenerateColumns = false;
NewDg.CellSpacing = 0;
NewDg.CellPadding = 0;
NewDg.Width = 782;
NewDg.ShowHeader = false;
NewDg.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
NewDg.BorderColor = System.Drawing.Color.White;
if (ds.Tables[0].Rows.Count > 0)
{
TemplateField empty = new TemplateField();
empty.ItemStyle.Width = 42;
NewDg.Columns.Add(empty);
ImageField crseimage = new ImageField();
crseimage.DataImageUrlField = "imagepath";
crseimage.DataAlternateTextField = "coursetitle";
crseimage.ItemStyle.Width = 160;
crseimage.ControlStyle.Width = 45;
crseimage.ControlStyle.Height = 45;
NewDg.Columns.Add(crseimage);
BoundField title = new BoundField();
title.ItemStyle.Width = 430;
title.DataField = "coursetitle";
NewDg.Columns.Add(title);
BoundField time = new BoundField();
time.DataField = "duration";
time.ItemStyle.Width = 104;
NewDg.Columns.Add(time);
BoundField price = new BoundField();
price.DataField = "cost";
price.ItemStyle.Width = 100;
price.DataFormatString = "{0:c}";
price.NullDisplayText = "FREE";
NewDg.Columns.Add(price);
}
else
NewDg.EmptyDataText = "No Courses Found";

NewDg.DataSource = ds;
NewDg.DataBind();

System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
NewDg.RenderControl(htw);

string DivStart = "";
string FullDIV = DivStart + DivBody + DivEnd;

int LastCellPosition = e.Row.Cells.Count - 1;
int NewCellPosition = e.Row.Cells.Count - 2;

e.Row.Cells[0].ID = "CellInfo" + e.Row.RowIndex.ToString();

////Match color of div which we will expand base on row
if (e.Row.RowIndex % 2 == 0)
{
//set to regular row style
e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text + "" + FullDIV;
}
else
{
//set to alternative row style
e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text + "" + FullDIV;
}

e.Row.Cells[0].Attributes["onclick"] = "HideShowPanel('uniquename" + e.Row.RowIndex.ToString() + "'); ChangePlusMinusText('" + e.Row.Cells[0].ClientID + "'); SetExpandedDIVInfo('" + e.Row.Cells[0].ClientID + "','" + this.txtExpandedDivs.ClientID + "', 'uniquename" + e.Row.RowIndex.ToString() + "');";
e.Row.Cells[0].Attributes["onmouseover"] = "this.style.cursor='pointer'";
e.Row.Cells[0].Attributes["onmouseout"] = "this.style.cursor='pointer'";

}
}

Please refer below image for your reference

jquery Div tag Scrolling

Well..here i am displaying images in the div tags using jquery scrollable.

the below image is used to displaying the images in the horizontally using jquery horizontal slider.



the asp.net code for horizontal scrolling.

protected void dtlstimages_ItemDataBound(object sender, DataListItemEventArgs e)
{

if (e.Item.DataItem != null)
{
// Thumbview contains courses under every lessonplan, To display courses along with image
// we use the following

Localize lcimgtext = (Localize)e.Item.FindControl("lcimages");
Localize lchoriimages = (Localize)e.Item.FindControl("lchoriimages");

// To get the courses under a lessonplan we use following by passing planid
ClsBO.ClsPlanBO objclsbo = new ClsBO.ClsPlanBO();
DataSet ds = objclsbo.GetCoursePlans(Convert.ToInt64(dlst1.DataKeys[e.Item.ItemIndex]));


// Passing Gridview to get course image paths along with course titles
lcimgtext.Text = GetImages(ds);
lchoriimages.Text = GetHorizontalImages(ds);
}
}


And the methods am using above ...

protected string GetImages(DataSet ds)
{

// This method will be used to get the image path, coursename of the coueses under a plan id.
// and by adding HTML tags to the retrived values make the images,coursetitle displayed under a lesson plan
// All the HTML tags along with image path,coursetitle will be added to string "imgtext"
// finally return this imgtext.

// These images are viewed when we Expand Down (uses jQuery )


string imgtext = "span start here";
if (ds.Tables[0].Rows.Count > 0)
{

// To display 4 horizontal rows we use the following

double total = 0;

total = Math.Floor(Convert.ToDouble(ds.Tables[0].Rows.Count) / 4);

for (int count = 1; count <= ds.Tables[0].Rows.Count; count++)
{

imgtext += "open image tag here width='45px' alt=" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString()
+ " title=" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString()
+ " height='45px' src=" + ds.Tables[0].Rows[count - 1]["imagepath"].ToString()
+ " close image tag and insert break here" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString() + "insert break again.";

if ((count % 4) == 0)
{
imgtext += "span close and very next start span";
}
else
{
imgtext += "break here"
";
}

}
if (total > 0)
{

imgtext += "span close here";
}
}
return imgtext;
}

one more method am using here....


public string GetHorizontalImages(DataSet ds)
{

// This method will be used to get the image path, coursename of the coueses under a plan id.
// and by adding HTML tags to the retrived values make the images,coursetitle displayed under a lesson plan
// All the HTML tags along with image path,coursetitle will be added to string "horiimges"
// finally return this horiimges.

// These images are viewed when we scroll Left / Right (uses jQuery )
string horiimges = "";

for (int count = 1; count <= ds.Tables[0].Rows.Count; count++) {

horiimges += "paragraph start here and very next start image tag here width='45px' alt=" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString()
+ " title=" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString()
+ " height='45px' src=" + ds.Tables[0].Rows[count - 1]["imagepath"].ToString()
+ " end image tag and very next place break" + ds.Tables[0].Rows[count - 1]["coursetitle"].ToString() + "close p tag";

}
return horiimges;
}


And above i have taken a datalist for displaying images to scroll.

here jquery functions to scroll both sides


$(document).ready(function() {

window.api = $("#ctl00_maincontent_dlst1_ctl00_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl00_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl01_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl01_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl02_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl02_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl03_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl03_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl04_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl04_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl05_scroller").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
window.api = $("#ctl00_maincontent_dlst1_ctl05_scroller2").scrollable({ size: 5 }).autoscroll({
autoplay: false,
api: true
});
});


I have taken page size 5 for datalist control. so that i taken 10 functions to scroll image dives for both sides.

The below image used to show images vertically using jquery slider





The jquery files we have to attach the application ..

jquery.js
jquery.min.js

and the concern javascript and css files need to develop by own. or else we can get it in google easy..

Jquery Horizontal and Vertical Scrolling(DIV)


Well here.. i used j query plugins for scrolling div tag both sides..



the below image describes the images scrolling in the div tag horizontally.

N-tier Architecture in Asp.net

Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.

Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.

This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.
[Note] tier and layer mean the same thing [End Note]

An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.

Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.

In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.

BLL and DAL
Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.

In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.

Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.

Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.

Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.

Hopefully you would have designed your application using the n-Tier approach. If this is the case, then note that you can separate the layers in the future.

Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.

Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.

WebMsgBox in C#


The below class is used to show webmessagebox dynamically


<pre class="brush:csharp">
namespace XXXXXXX
{
public class WebMsgBox
{
protected static Hashtable handlerPages = new Hashtable();
private WebMsgBox()
{
}
</pre>

// Method to show message in the messagebox
public static void Show(string Message)
{
if (!(handlerPages.Contains(HttpContext.Current.Handler)))
{
Page currentPage = (Page)HttpContext.Current.Handler;
if (!((currentPage == null)))
{
Queue messageQueue = new Queue();
messageQueue.Enqueue(Message);
handlerPages.Add(HttpContext.Current.Handler, messageQueue);
currentPage.Unload += new EventHandler(CurrentPageUnload);
}
}
else
{
Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
queue.Enqueue(Message);
}
}

// Internal private method
private static void CurrentPageUnload(object sender, EventArgs e)
{
Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
if (queue != null)
{
StringBuilder builder = new StringBuilder();
int iMsgCount = queue.Count;
builder.Append("");
handlerPages.Remove(HttpContext.Current.Handler);
HttpContext.Current.Response.Write(builder.ToString());
}
}
}

}

Sql Injection

Sql Injection

Most of Developers used to write sql queries. But the problem here is "sql injection".

What is Sql Injection

SQL Injection happens when a developer accepts user input that is directly placed into a SQL Statement.
This can allow an attacker to not only steal data from your database, but also modify and delete it.

How Sql Injection works

For example you want to check USER ID and PASSWORD from database and you write the query as follows

select userid from tablename where userid='"+txtUser.Text+"' and password='"+txtPwd "'"

This is called dynamic query building,

suppose i enter values

txtUser -- kartheek


txtPwd -- chkartheek

query becomes

select userid from tablename where userid='kartheek' and password='chkartheek'

and gives output perfectly but the problem is...

suppose an attacker want to login into ur account he enters the text into the userid as follows..

txtUser -- yy' or 'a'='a'--


txtPwd -- xxxxx

then the query becomes as follows

select userid from tablename where userid='yy' or 'a'='a'-- 'and password='kranthikumar'

see the query once here the query checks the condition " userid ='yy' or 'a'='a' " and after the " -- " will be commented

so condition works perfectly and attacker can loggin to your account.

This is what we called SQL INJECTION

How to avoid Sql injection

* Use parameterized queries (SqlCommand with SqlParameter) and put user input into parameters.

* Don't build SQL strings out of unchecked user input.

* Use stored procedures to encapsulate database operations.


SqlCommand cmd = new SqlCommand("select userid from tablename where userid=@userid and password=@password", con);



cmd.Parameters.AddWithValue("@userid", txtUserid.Text);


cmd.Parameters.AddWithValue("@password", txtPwd.Text);

This solves the sql injection.

Freetext in Sqlserver

FreeText using Full Text Indexing in sql server

Suppose we need to search for a string or for some words in a column in sql server we have one good option that is FREETEXT. by using FREETEXT we can search the data inside a column easily.
ex:
you have a column named Question, in that you want to search for "dotnet asp.net c#"
then you can use FREETEXT which searches the Question column with the "dotnet", "asp.net',"c#".

If the column has any of the 3 then the column will be selected.
For that we need to do following...

1. Create a CATALOG table in database.
CREATE FULLTEXT CATALOG CatalogName AS DEFAULT;

2. Create a Index on table for which you want to apply FULL TEXT INDEX.
(index may be primary key, unique key)
CREATE UNIQUE INDEX IndexName ON tablename(column);

3. Create a FULL TEXT INDEX on table based on the index created in (2)
CREATE FULLTEXT INDEX ON tablename(column) KEY INDEX IndexName

4.Use functions like FREETEXT, CONTAINS... for searching the database.
select * from tablename where FREETEXT(column,'search string') order by sno desc
or for Sql parameters
select * from tablename where FREETEXT(column,@string) order by sno desc

Interface in c#

Well what is actually an interface? I will start with an example from real life. We use interfaces or interface all the time. When my dad told me how to dial my first telephone number from our home phone many years ago, I was pretty pleased. When we visited my uncle in their house I could use their phone just as easy.

Imagine if someone had to teach me all over again how to use the phone. I do not need to know how the interface is implemented for a phone. I can use the buttons in the panel (the interface in this case) and know that the phone willsubscribe to the general phone interface.

Let’s see interface characteristics in the “code world”

  • An iterface defines only the properties and method signatures and not the actual implementation. I mean that in a class declaration we implement fields,properties,methods and events. In an interface we just define what properties/methods the class should have.
  • Requires that classes which implement an interface must ”honour” the property and method signatures. Basically are like contracts for classes. Classes which implement an interface must implement the methods and the properties of the interface
  • Many classes can implement a particular interface method, in their own way
  • An interface may inherit from multiple base interfaces
  • A class may implement-inherit from multiple interfaces
  • A C# class may only inherit from one class

Let’s see a simple example

1) Create a asp.net web application with C#

2) Add a new item to your project, a class file, called Human.cs.

3) Let’s define an Interface, called IHuman.

Just above this line of code

public class Human

type the following

interface IHuman
{
void Read();
void Write(object obj);
int Height { get; set; }
int Weight { get; set; }

}

here we define properties and methods that the class that subscribes to this interface must implement.

We prefix the name of the Interface with an “I”. Just a widely accepted convention…

4) Now let’s implement the class

Here we declare (sign a contract so to speak, that the Human class will Implement the IHuman Interface)

public class Human:IHuman

Right after the line above type

private int height;
private int weight;

public Human(string s)
{
MessageBox.Show(s);

}

// implement the Read method
public void Read()
{
MessageBox.Show(
“Implementing the Read Method for IHuman”);
}

// implement the Write method
public void Write(object o)
{
MessageBox.Show(
“Implementing the Write Method for IHuman”);
}
// implement the property Height
public int Height
{
get { return height; }
set { height = value; }
}

// implement the property Weight

public int Weight
{
get{ return weight; }
set{ weight = value; }
}

As i said before the class must “honour” its contract with the interface.

Before you go on try to comment this code out

public void Read()
{
MessageBox.Show(
“Implementing the Read Method for IHuman”);
}

Try to build your application. Well as you see from the error message below, someone is not honouring his contract….

Human’ does not implement interface member ‘IHuman.Read()’

5) From our Page_Load event of the defaul.aspx page we can create a new instance of the Human class

Human myperson = new Human(“fofo”);
myperson.Read();
myperson.Weight = 78;
myperson.Height = 88;
Response.Write(myperson.Weight);
Response.Write(“
”);
Response.Write(myperson.Height);

Please note that i could have a Boy class that could implement the IHuman interface.

public class Boy:IHuman

each class (boy,human) should implement the Read method of the IHuman interface. But each class was free to implement it in its own way.

We could define the IHuman interface above as an abstract class.And then had our class inheriting from our abstract class. But if changed slighlty the implementation of our abstract class then the referencing classes would fail and so our application would fail. If we work with Interfaces and we are commited to follow good practices like, never to alter the Interface implementation after they have been deployed, we will not run into such problems.