Common function to dynamically fill dropdownlists and get selected text – better approach

Now this is useful only if you don’t want to use Database for storing dropdownlist’s values, otherwise i would prefer using it DB or XML.

I’ll jump directly to the code, I hope you are not a newbie 🙂

Enum for the type of dropdownlist to be filled:

public enum DDLType
{
Education = 1,
Experience,
Salary,
}

Filling dropdownlist based on enum value

public class UtilityManager
{

//place for utility functions and inner classes…

//Inner class for all the functions related to server side controls..
public class ControlsManager
{
public static DropDownList FillDropDownList(DropDownList ddl, DDLType type)
{
switch ((int)type)
{ Read the rest of this entry »

Countries Dropdownlist, Categories Dropdownlist

Countries Dropdwonlist
<asp:DropDownList id=”Country” runat=”server”>
<asp:ListItem Value=”” Selected=true>Select Country</asp:ListItem>
<asp:ListItem Value=”AF”>Afghanistan</asp:ListItem>
<asp:ListItem Value=”AL”>Albania</asp:ListItem>
<asp:ListItem Value=”DZ”>Algeria</asp:ListItem>
<asp:ListItem Value=”AS”>American Samoa</asp:ListItem>
<asp:ListItem Value=”AD”>Andorra</asp:ListItem>
<asp:ListItem Value=”AO”>Angola</asp:ListItem>
<asp:ListItem Value=”AI”>Anguilla</asp:ListItem>
<asp:ListItem Value=”AQ”>Antarctica</asp:ListItem>
<asp:ListItem Value=”AG”>Antigua And Barbuda</asp:ListItem>
<asp:ListItem Value=”AR”>Argentina</asp:ListItem>
<asp:ListItem Value=”AM”>Armenia</asp:ListItem>
<asp:ListItem Value=”AW”>Aruba</asp:ListItem>
<asp:ListItem Value=”AU”>Australia</asp:ListItem>
<asp:ListItem Value=”AT”>Austria</asp:ListItem>
<asp:ListItem Value=”AZ”>Azerbaijan</asp:ListItem>
<asp:ListItem Value=”BS”>Bahamas</asp:ListItem>
<asp:ListItem Value=”BH”>Bahrain</asp:ListItem>
<asp:ListItem Value=”BD”>Bangladesh</asp:ListItem>
<asp:ListItem Value=”BB”>Barbados</asp:ListItem> Read the rest of this entry »

Custom SessionManager, a better way of handling your session variables.

This is a custom built reusable SessionManager Class to keep track of all the used session variables in a web application. You don’t need to remember them or type them by hand every time you need to access them and with typed dataset rows, life becomes allot more easier but above all there is no need of casting where ever you access a session object, believe me, that’s the best part.

public class SessionManager
{
    //set the login status in session for the current user.
    public static void setIsLoggedIn(bool value)
    {
        //value is true when the the usser logs in
        HttpContext.Current.Session[“isLoggedIn”] = value;
        //value is false when the the usser logsout
        if (!value)
            HttpContext.Current.Session[“isLoggedIn”] = null;
    }

     //check to see if the user is logged in

    public static bool isLoggedIn()

    {

        if (HttpContext.Current.Session[“isLoggedIn”].Equals(null))

            return false;

        else

            return true;

    }   

 

    //set current employee in the sessoin

    public static void setCurrentEmployee(dsEmployees.EmployeesRow value)

    {

        HttpContext.Current.Session[“Employee”] = value;

        if (value != null)

        {

            //following variables are set separately to be used in bindable control like

            //GridView, DataList etc..

            HttpContext.Current.Session[“EmployeeId”] = value.EmployeeId;

            HttpContext.Current.Session[“Name”] = value.FirstName + ” “ +

                value.MiddleName + ” “+ value.LastName;

        }

    }

 

    //get current employee fro the session

    public static dsEmployees.EmployeesRow getCurrentEmployee()

    {

        return(dsEmployees.EmployeesRow)HttpContext.Current.Session[“Employee”];

    }

 

   

    //bonus functions – to be used on the pages where it is neccessary for the users to login

    public static void setRedirectUrl(stringredirectURL)

    {

        HttpContext.Current.Session[“redirectURL”] = redirectURL;

    }

 

    //bonus functions – once the users log in, they will be redirected back to the previously

    //stored url or redirected to the default page

    public static stringgetRedirectUrl()

    {

        if (object.Equals(HttpContext.Current.Session[“redirectURL”], null))

            return “myaccount.aspx”;

        else

            return HttpContext.Current.Session[“redirectURL”].ToString();

    }

}

Analyze one thing that setCurrentEmployee is taking the entire typed dataset’s row of the currently logged in user. This practice helps a great deal to quickly access any value from the currently logged in user’s details instead of hitting the database again and again and of course, typed datarow helps you avoid any mistakes in writing field names 🙂

Here is a sample code to set and get login sessoin variables.

protected voidLogin()

 

    {

        Page.Validate();

 

        if(!Page.IsValid)

            return;

 

        dsEmployeesTableAdapters.EmployeesTableAdapter ta = new dsEmployeesTableAdapters.EmployeesTableAdapter();

        dsEmployees.EmployeesDataTable dt = ta.Login(txtuid.Text.Trim(), txtPassword.Text.Trim());

        if(dt.Rows.Count > 0)

        {

            dsEmployees.EmployeesRow row = dt[0];

 //set current user as logged in

                EmployeeSession.setIsLoggedIn(true); 
 
                EmployeeSession.setRedirectUrl(null); 
                Response.Redirect(rediectURL); 
        }
 

 

    return;

    }

Now it is very easy to check if the user is logged in.

//check if the user is logged in

        if (!EmployeeSession.isLoggedIn())

        {

            //store current url and redirect to the login page

            stringurl = Request.Url.AbsoluteUri.ToString();

            EmployeeSession.setRedirectUrl(url);

            Response.Redirect(“login.aspx”);

        }

Accessing the data of the currently logged in user is piece of cake now. 

          //check if the user is logged in
            if (EmployeeSession.isLoggedIn())
            {
                //display the name of the user from the session object
                lblName.Text = SessionManager.getCurrentEmployee().Name;
            }

Hope it helps, if you need more on it, drop me a few lines.

Cheers –

 


2 Steps Solutions 
Re-engineering your business

Both DataSource and DataSourceID are defined on ‘GridView1’. Remove one definition. – Bind multiple datasources to a gridview control

Both DataSource and DataSourceID are defined on ‘GridView1’.  Remove one definition.

OK, so this is the message that you get most of the times when you try to bind your gridview or any other bindable controls, to multiple DataSources.

 It happens most of the times when you bind your GridView control to an ObjectDataSouce or SqlDataSource on the design surface and then you try to bind the same GridView in code behind using the manual coding and sometimes it becomes necessary to do so in the scenarios of searching and manual paging etc.

(Binding to ObjectDataSource)

 ObjectDataSource Binding

(Binding to manual DataSource)

GridView1.DataSource = null;
GridView1.DataSource = myDataTable;
GridView1.DataBind();

This is not going to solve the problem, the simples workaround is Read the rest of this entry »

C# for newbies (C# Terminology/Technical Words)

Good C# startup for those who are new to programming/c#/asp.net http://msdn.microsoft.com/en-us/library/ms173231.aspx
For programming guide have a look at http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx
access modifier
A keyword, such as private, protected, internal, or public, that restricts access to a type or type member. For more information, see Access Modifiers.

 

accessible member
A member that can be accessed by a given type. An accessible member for one type is not necessarily accessible to another type. For more information, see Access Modifiers and Friend Assemblies.
accessor
A method that sets or retrieves the value of a private Read the rest of this entry »

Object Initializers (What’s new in C#)

I love some of the new features in c#, specially the syntactic changes and enhancements are great to achieve greater productivity (I have my own reservations on the efficiency though, but that’s debatable) 🙂

Lets take a look at the new Object initializers in C#

Now you can assign values to any accessible properties (fields) of an object at its creation time. It actually avoids the necessity of invoking the constructor to do so.  lets take a look at an example with a name type before moving on to the anonymous types.

private class Student
{
    // Auto-implemented properties (We’ll discuss them in the next post of this series)
    public int Name { get; set; }
    public string RegistrationNumber { get; set; }
}

static void NewStudent()
{
    // Object initializer
    Student student = new Student{ Name = “Khan”, RegistrationNumber = 7728 };
}

Object initializers are very useful with LINQ query expressions. Query expressions use anonymous types frequently which can only be Read the rest of this entry »

Posted in ASP.NET, C#. Tags: . Leave a Comment »

var type and anonymous classes in c# 3.0

The new var type in c# 3.0 and anonymous types will help developers a great deal in extending their programming capablities and creat obejects on the fly without actually writing classes.

Existing .NET developers may have some reservations on the new var type but believe me alot of new commers from the open source world, specially PHP, would love to have this feature to get some familiarity, which otherwise is not there at all for them in .NET platform.

Anyway, for thoe who have no idea of what i am talking about here is a small code snippet to have a better understanding.

var myAnnonynomousItem = new {car=“lexus”, color=“black”, maxSpeed=4200}

Compiler generates a classes for every annonymous type automatically.

One thing has to be kept in mind here that var is definitely Read the rest of this entry »

Posted in ASP.NET, C#. Tags: . Leave a Comment »

Simple function to reset/clear all child controls in a container

Well, I thaught i wasn’t going to write any javascript this time and lets make a general function which can take any parent control and reset all the sub controls. The functoin can definitely be extended to add more parent and sub controls type but this is just a kick start 🙂

 

public static void resetAllControls(object parent)

    {

        if (parent is HtmlTable)

        {

            HtmlTable tbl = (HtmlTable)parent;

 

            foreach (HtmlTableRow row in tbl.Rows)

            { Read the rest of this entry »

Dabatase publishing with SQL SERVER 2005 Express Edition

Yeah, I was looking for the easiest way to publish my database entirely with schema plus data to my online server. Here is a handy tool to install and use with excellent GUI.

Download the database publishing wizard 1.1 here.

 

It is so easy that I guess i dont have to write any tutorial/steps to use it but yet some screenshots might be useful for newbies 🙂

Cheers –

 


2 Steps Solutions 
Re-engineering your business

70 Expert Ideas For Better CSS Coding

CSS isn’t always easy to deal with. Depending on your skills and your experience, CSS coding can sometimes become a nightmare, particularly if you aren’t sure which selectors are actually being applied to document elements. An easy way to minimize the complexity of the code is as useful as not-so-well-known CSS attributes and properties you can use to create a semantically correct markup.

http://www.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/

Here I found one of the best articles for CSS freaks to enhance their skills and abilities.

Personally i found it very useful for small fixes in my projects although i am not the designing guy 🙂

Have a good day!

Posted in CSS. Tags: , . 2 Comments »