Monthly Archives: July 2010

Array vs ArrayList

In yet another round of fight, today we have contenders Array and ArrayList:

ARRAY ARRAYLIST
1. Array can store single data like Char[] vowel=new Char[]; Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2. Array is in the System namespace ArrayList is in the System.Collections namespace.
3. The capacity of an Array is fixed. ArrayList can increase and decrease size dynamically

Ex:

ArrayList list = new ArrayList();

list.Add(“One”);

list.Add(“Two”);

list.Add(“Three”);

ARRAY

ARRAYLIST

1.

Array can store single data like Char[] vowel=new Char[];

Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2.

Array is in the System namespace

ArrayList is in the System.Collections namespace.

3.

The capacity of an Array is fixed.

ArrayList can increase and decrease size dynamically

Ex:

        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");

Leave a comment

Filed under C#

Compile Code into Assemblies

To service user request thru application code, it need to be compiled to one or more assemblies.

Assembly files have extension .dll. We can write ASP.net code in many languages like C#, VB.net, J# & others but when compiled, but when compiled, it will be translated into language-independent or CPU-independent language i.e. MS Intermediate Language(MSIL). At run-time in the context of .Net framework, the MSIL gets translated into CPU-specific instructions.

 Benefits of compiling the application code to Assemblies:

Performance:- Compiled code is much faster then scripting language because it’s representation is closer to machine code & doesn’t require additional parsing.

Security:- Compiled code is difficult to the reverse engineer as it lacks the readability & high level of abstraction.

Stability:- Code is checked at compile time for syntax error, type safety, & other problems. By caching these errors at build-time we can eliminate many errors in our code.

Inter-operability:- As MSIL code support all .Net languages so if you are writing an ASP.Net web page in C# then you can use reference of assemblies written in VB.net too.

Leave a comment

Filed under .Net

Factorial

There are actually two ways to get factorial i.e. using recursion or without recursion:

With Recursion

protected int Factorial(int num)

{

              if (num == 1)

                      return num;

              return (num * Factorial(num – 1));

}

Without Recursion

protected int FactorialNoRecursion(int num)

{

             int result=1;

             if (num == 1)

                      return num;

              for (int i = 2; i <= num; i++)

                     result *= i;

             return result;

}

Leave a comment

Filed under C#

AutoCompleteExtender

AutoCompleteExtender control pulls words that start with the prefix typed into the textbox and display in a popup panel. It comes under AJAX control toolkit.

To implement the same we need to call webservice (WebMethod) thru Ajax & First thing you have to do is to add the ScriptService reference to the webserive as follows. 

[System.Web.Script.Services.ScriptService]:

 

 [WebService(Namespace = “http://tempuri.org/&#8221;)]

 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 [System.Web.Script.Services.ScriptService]

 public class SampleWebService : System.Web.Services.WebService

 {

      [WebMethod]

      public string[] GetName(string prefix)

      {

            List<string> names = null;

            string query = string.Empty;

            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings[“ConnectionString”]);

             query = “SELECT Name FROM Student WHERE Name = ” + prefix + “%”;

            SqlCommand com = new SqlCommand(query);

            con.Open();

            SqlDataReader dr = com.ExecuteReader();

            if (dr.HasRows)

            {

                names = new List<string>();

                while (dr.Read())

                {

                    names.Add(dr.GetString(1));

                }

            }

           

            return names.ToArray();

        }

    }

 Now at the design level, apart from specifying ScriptManager, we need to provide a <Services> tag as shown below and use Ajax AutocompleteExtender with ServicePath & ServiceMethod:

 <body>

    <form id=”form1″ runat=”server”>

        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

            <services>

                <asp:ServiceReference Path=”AutoComplete.asmx” />

            </services>

        </asp:ScriptManager>

        <div>

            <asp:TextBox ID=”txtCountry” runat=”server”></asp:TextBox>

<ajaxToolkit:AutoCompleteExtender runat=”server” ID=”autoComplete1″ TargetControlID=”txtCountry”

ServicePath=”AutoComplete.asmx” ServiceMethod=”GetCountriesList” MinimumPrefixLength=”1″

            EnableCaching=”true” />

        </div>

    </form>

</body>

 

Leave a comment

Filed under Ajax

UpdatePanel

UpdatePanel

The UpdatePanel control is a server control which used to achieve asynchronously postback of limited to regions of the page.
This process is coordinated by the ScriptManager server control.

By default, any postback control inside an UpdatePanel control causes an asynchronous postback and refreshes the panel’s content. However, you can also configure other controls on the page to refresh an UpdatePanel control. You do this by defining a trigger for the UpdatePanel control.
eg:
<form runat=”server”>
    <div>
    <asp:Button
                Text=”Refresh Panel”
                runat=”server” />
    <asp:ScriptManager
                       runat=”server” />
    <asp:UpdatePanel
                     UpdateMode=”Conditional”
                     runat=”server”>
                     <Triggers>
                       <asp:AsyncPostBackTrigger ControlID=”Button1″ />
                     </Triggers>
                     <ContentTemplate>
                     <fieldset>
                     <legend>UpdatePanel content</legend>
                     <%=DateTime.Now.ToString() %>
                     </fieldset>
                     </ContentTemplate>
    </asp:UpdatePanel>

A trigger’s control event is optional. If you do not specify an event, the trigger event is the default event of the control.

UpdateMode (Always, Conditional)
If the UpdateMode property is set to Always, the UpdatePanel control’s content is updated on every postback that originates from anywhere on the page. This includes asynchronous postbacks from controls that are inside other UpdatePanel controls, and postbacks from controls that are not inside UpdatePanel controls.

If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is updated when one of the following is true:

  • When the postback is caused by a trigger for that UpdatePanel control.
  • When you explicitly call the UpdatePanel control’s Update() method.
  • When the UpdatePanel control is nested inside another UpdatePanel control and the parent panel is updated. 

To use an UpdatePanel control in a master page, you must decide how to include the ScriptManager control. If you include the ScriptManager control on the master page, it can act as the ScriptManager control for all content pages.

UpdatePanel controls can be nested. If the parent panel is refreshed, all nested panels are refreshed also.

Leave a comment

Filed under Ajax

Abstract Class FACTS

Abstract Class FACTS

1) We can inherit abstract class from another abstract class also.

Eg:

public abstract class AbstractClass1

{
public abstract string TestMe();       

}

 It is inherited by AbstractClass2 

public abstract class AbstractClass2 : AbstractClass1

{
public abstract string DoSome();

public override string TestMe()

{

return “This is test”;

}

}

2) Abstract class can inherit Interface also.

Leave a comment

Filed under .Net, C#

GROUP BY, Where vs Having

GROUP BY is actually used to group the result-set by using aggregate functions.

Let’s say we have a table Student with columns:

Name Subject Score
Mahesh Math 80
Mahesh Eng 70
Ramesh Eng 70
Somesh Math 65
Ramesh Math 75
Somesh Eng 65
Mahesh Hindi 60
Ramesh Hindi 75

Now to get each student total marks:

SELECT Name, Sum(Score)

FROM Student

GROUP BY Name

Name Score
Mahesh 210
Ramesh 220
Somesh 130

Without GROUP BY,

SELECT Name, Sum(Score)

FROM Student

Name Score
Mahesh 560
Mahesh 560
Ramesh 560
Somesh 560
Ramesh 560
Somesh 560
Mahesh 560
Ramesh 560

WHERE vs HAVING

WHERE HAVING
WHERE is basically used to filter before the Group BY. HAVING is used to filter on GROUP BY result-set.
WHERE can’t be used with aggregate functions. Having is applied with aggregate functions only.
WHERE doesn’t need Group By. HAVING is used with Group By only.

Now for Query to get all students who have appeared in three subject exam:

SELECT Name, Count (Name)

FROM Student

GROUP BY Name

HAVING Count (Name) =3

To get all students who have scored more then 70 & appeared in three subject exam:

SELECT Name, Count(Name)

FROM Student

Where Score>70

GROUP BY Name

HAVING Count(Name)=3

 References:

http://www.programmerinterview.com/index.php/database-sql/having-vs-where-clause/

Leave a comment

Filed under SQL

Protected: Amex work

This content is password protected. To view it please enter your password below:

Comments Off on Protected: Amex work

Filed under Work

User Control Bubble Event

A better idea is to publish an event in the user control to allow any interested parties to handle the event.

This technique is commonly referred to as “event bubbling”.

Here is an exmple:

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”UserControlDemo.ascx.cs” Inherits=”WellnGood.UserControlDemo” %>
<asp:Button ID=”btn1″ runat=”server” Text=”Bubble to Page”
onclick=”btn1_Click” />

public partial class WebUserControl : System.Web.UI.UserControl

{

public event EventHandler buttonClick;

protected void Button1_Click(object sender, EventArgs e)
{
buttonClick(sender, e);
}

}

Then you can subscribe the event buttonClick at webpage to display the different information .

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”BubbleEvent.aspx.cs” Inherits=”WellnGood.BubbleEvent” %>

<%@ Register Src=”~/UserControlDemo.ascx” TagName=”UserControlDemo” TagPrefix=”ucDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<ucDemo:UserControlDemo ID=”ucDemo1″ runat=”server” />
</div>
</form>
</body>
</html>

public partial class BubbleEvent: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

ucDemo1.buttonClick+=new EventHandler(ucDemo1_buttonClick);

}

protected void ucDemo1_buttonClick(object sender, EventArgs e)
{
Response.Write(“I am User control bubble event on Page”);
}

}

Leave a comment

Filed under .Net

Factory Pattern

Factory Pattern is a creational patter. It provide encapsulation by hiding the complex components and their dependencies from the client.
Why do we need?
1. A class can’t anticipate the class of object it must create.
2. Client don’t need to use lot of new keywords.
3. Classes delegate responsibility to one of several helper subclasses.
4. If you want to develop a data layer that supports many types of database products, it should not be tightly coupled with a particular database product or ADO.NET data provider.

Ex: we will be creating an Employee objects. As with good OO design we will start with an interface.

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}

Now Concrete Classes: we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource

public Class CTechnology : IEmployee
{
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}

public class CHumanResource : IEmployee
{
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Now Client section: there are two buttons “IT EMployee” & “HR Employee” and two labels lblDept & lblEdu.

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnITEmployee_Click(object sender, EventArgs e)
{
IEmployee emp = EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.IT);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

protected void btnHREmployee_Click(object sender, EventArgs e)
{
IEmployee emp =               EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.HR);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}Now we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource
public Class CTechnology : IEmployee
{
public CTechnology()
{

}
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}
public class CHumanResource : IEmployee
{
public CHumanResource()
{

}
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now our factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Leave a comment

Filed under .Net

How GC Works

How GC works

The GC maintains lists of managed objects arranged in “generations.” A generation is a measure of the relative lifetime of the objects in memory. The generation number indicates to which generation an object belongs. Recently created objects are stored in lower generations compared to those created earlier in the application’s life cycle. Longer-lived objects get promoted to higher generations.

Because applications tend to create many short-lived objects compared to relatively few long-lived objects, the GC runs much more frequently to clean up objects in the lower generations than in the higher ones.

Finalization is the process, by which the GC allows objects to clean up any unmanaged resources that they’re holding,

Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class.

~Test

{

//Necessary cleanup code

}

Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running.

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

Finalize Dispose
The execution order of finalize is non-deterministic. It’s execution is deterministic by using call to Dispose() method.
It doesn’t use any interface. It uses IDisposable interface and then override it’s Dispose() method.
you cannot  override the Finalize method, as it is generated implicitly destructor. Dispose is not depended on destructor.
You can suppress Finalize() by using GC.SuppressFinalize(this) You can’t suppress Dispose() as it is not called implicitly.

Leave a comment

Filed under .Net