Archive for the ‘ASP.NET’ Category

Hello All

Few days back I was struggling with a repeater problem , where I have to get a value of dropdown list on a button click event which is inside repeater. Eventually I come up with a solution through googling. What I have faced was get the value of appropriate dropdown list while clicking the button of a particular repeater’s row.

It’s being hard to describe rather that visualize :) isn’t it ! ( proposed solution should be as image bellow)

    My aspx markup is as bellow :

 <asp:Repeater runat="server" ID="rptTeamInfo" OnItemDataBound="rptTeamInfo_ItemDataBound" OnItemCommand="rptTeamInfo_ItemCommand">
               <ItemTemplate>
                <div class="side2">
                <div class="form">
                    <a href="#">delete</a><a href="#">edit /</a>
                    <ul class="p2">
                      <span class="style1">[ <%#Eval("team_name")%> ]</span> - [ <%#Eval("creation_date")%>]<br />
                      <span class="style2">[<asp:Label runat="server" Text="ADMIN bla bla bla"></asp:Label>] - [ <%#Eval("team_leader")%>]</span> - [ <%#Eval("description")%>]
                     </ul>
                </div>
                <div class="form2">
                <asp:ImageButton id="imgAddToTeam"  CommandName="select" CommandArgument='<%# Eval("team_id") %>'  ImageUrl="images/Add_to_team.png" runat="server" style="margin:10px;" align="right"></asp:ImageButton>
                <asp:DropDownList ID="ddlUserList" runat="server">

                </asp:DropDownList>

                </div>
                <div class="row1">
                        <ul class="column">
                            <p><img src="images/name.png" /> Name</p>
                        </ul>
                        <ul class="column2">
                            <p><img src="images/username.png" /> Username</p>
                        </ul>
                        <ul class="column3">
                            <p><img src="images/username.png" /> Access</p>
                        </ul>
                </div>
                <div class="row2">
                 <asp:Repeater ID="rptUserInfo"  OnItemDataBound="rptUserInfo_ItemDataBound" runat="server">
                       <ItemTemplate>
                    <asp:LinkButton id="lnkUserDelete" onclick="lnkUserDelete_Click" runat="server">delete</asp:LinkButton>
                    <ul class="column">
                        <p> <asp:Label runat="server" id="lblFirstNameIn"></asp:Label> <asp:Label runat="server" id="lblLastNameIn"></asp:Label></p>
                    </ul>
                    <ul class="column2">
                        <p> <asp:Label runat="server" id="lblUserIDIn"></asp:Label></p>
                    </ul>
                    <ul class="column3">
                        <p><asp:Label runat="server" id="lblUserTypeIn"></asp:Label></p>
                    </ul>
                        </ItemTemplate>
                 </asp:Repeater>
                </div>
            </div>
               </ItemTemplate>
               </asp:Repeater>

And my code behind file is as bellow :

using System;
using System.Web.UI.WebControls;
using ClassLibrary1.UTILITY;

namespace WebDoc
{
    public partial class ManageTeam : System.Web.UI.Page
    {
        public int CurrentTeamID { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            lblUserId.Text = BUSessionUtility.BUSessionContainer.UserName;
            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();
            rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

            rptTeamInfo.DataBind();

        }
        protected void btnLogOut_Click(object sender, EventArgs e)
        {
            BUSessionUtility.BUSessionContainer.UserName = string.Empty;
            BUSessionUtility.BUSessionContainer.UserType = string.Empty;
            Response.Redirect("~/LoginUI.aspx");
        }

        protected void rptTeamInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DropDownList ddlUserList = (DropDownList)(e.Item.FindControl("ddlUserList"));

            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();
            ddlUserList.DataSource = manageTeamDAL.GetUsersByManagerID(BUSessionUtility.BUSessionContainer.UserName);
            ddlUserList.DataTextField = "id";
            ddlUserList.DataValueField = "id";
            ddlUserList.DataBind();

            Repeater rptUserInfo = (Repeater)(e.Item.FindControl("rptUserInfo"));

            var row = e.Item.DataItem;
            rptUserInfo.DataSource = manageTeamDAL.GetUsersByAssignedTeamID(((team_info)(row)).team_id);
            rptUserInfo.DataBind();

        }

        protected void rptTeamInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                ImageButton imgAddToTeam = (ImageButton)e.CommandSource;

                DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");

                ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

                manageTeamDAL.AssignUserInTeam(int.Parse(imgAddToTeam.CommandArgument), ddlUserList.SelectedValue.ToString());

                rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

                rptTeamInfo.DataBind();
            }
        }

        protected void rptUserInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblFirstName = (Label)(e.Item.FindControl("lblFirstNameIn"));
            Label lblLastName = (Label)(e.Item.FindControl("lblLastNameIn"));
            Label lblUserID = (Label)(e.Item.FindControl("lblUserIDIn"));
            Label lblUserType = (Label)(e.Item.FindControl("lblUserTypeIn"));
            LinkButton lnkUserDelete = (LinkButton)(e.Item.FindControl("lnkUserDelete"));

            var row = e.Item.DataItem;

            lblFirstName.Text = ((user_info)(row)).f_name;
            lblLastName.Text = ((user_info)(row)).l_name;
            lblUserID.Text = ((user_info)(row)).id;
            lblUserType.Text = ((user_info)(row)).user_type;
            lnkUserDelete.CommandArgument = ((user_info)(row)).id;

        }

        protected void lnkUserDelete_Click(object sender, EventArgs e)
        {
            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

            manageTeamDAL.DeleteUserformTeam(((LinkButton)(sender)).CommandArgument);

            rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

            rptTeamInfo.DataBind();
        }

    }
}

Not all codes are important here and I will escape the data binding part as its not the focus of today’s topic. Now I will focus what we should do to perform our basic task.

first of all we have to do one most important  thing *** MAKE    EnableViewState="false" *** If ViewState is in true condition your are not going to handle  OnItemCommand event which will significantly react for your particular row’s activity.

 <asp:Repeater runat="server" ID="rptTeamInfo" OnItemDataBound="rptTeamInfo_ItemDataBound" OnItemCommand="rptTeamInfo_ItemCommand">

<ItemTemplate>

<asp:ImageButton id="imgAddToTeam" CommandName="select" CommandArgument=’<%# Eval("team_id") %>ImageUrl="images/Add_to_team.png" runat="server" style="margin:10px;" align="right"></asp:ImageButton>

<asp:DropDownList ID="ddlUserList" runat="server">

</asp:DropDownList>

</ItemTemplate>

</asp:Repeater>

The event handler “rptTeamInfo_ItemCommand” for the the event “OnItemCommand” is as bellow.

protected void rptTeamInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "select")
    {
        ImageButton imgAddToTeam = (ImageButton)e.CommandSource;

        DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");

        ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

        manageTeamDAL.AssignUserInTeam( int.Parse(imgAddToTeam.CommandArgument),ddlUserList.SelectedValue.ToString() );

        rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

        rptTeamInfo.DataBind();
    }
}

We are passing the “CommandName” and “CommandArgument” through our image button which will check the command name in code behind and act with the command argument parameter.

We can get our ImageButton and DropdownList is as bellow from our code behind.

ImageButton imgAddToTeam = (ImageButton)e.CommandSource;

DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");

And selet the value of dropdown as bellow.

ddlUserList.SelectedValue

In this way we can accomplish our task regarding the repeater row’s control manipulation.

Thats all for today.

BYE

Hello All

From last few months I was not working on .NET platform so haven’t get enough time to write something fruitful on .NET technology. But from last few few days I was thinking to do something with IoC . There are many DI tools to perform DI in .NET but I found Ninject useful as well as light waited and easily implementable. So lets start to make our hand dirty with the Ninject (there are many advanced level use of Ninject library but in this article I will simply show how to do DI with Ninject framework).

My project structure is as following .

In this example I’m taking 2 types of engine and 2 types of set and through Ninject DI I’ll inject one of each for a car. Fore the sake of simplicity I will place the code file accordingly and describe through code comment.

In my “DependencyInjection.Core” project I took 2 interfaces: 1.IEngine  2.ISeat

IEngine.cs is as following :

namespace DependencyInjection.Core
{
   public interface IEngine
    {
       string EngineType(string carName);
    }
}

I’m also taking 2 other classes 1.DieselEngine and 2.PetrolEngine  . Both of the classes implements IEngine interface.
DieselEngine.cs is as following :

namespace DependencyInjection.Core
{
   public  class DieselEngine : IEngine
    {
       public string EngineType(string carName)
       {
           return string.Format("This {0} runs on diesel.", carName);
       }
    }
}


PetrolEngine.cs is as following :

namespace DependencyInjection.Core
{
  public class PetrolEngine : IEngine
    {
        public string EngineType(string carName)
        {
            return string.Format("This {0} runs on petrol.", carName);
        }
    }
}

Now start for another type of interface implementation ISeat . This part also is as above.
ISeat.cs is as following :

namespace DependencyInjection.Core
{
   public interface ISeat
    {
       string SeatType(string carName);
    }
}

Two other classes 1.LeatherSeat and 2.PlasticSeat  . Both of the classes implements ISeat interface.
LeatherSeat.cs is as follwong:

namespace DependencyInjection.Core
{
   public class LeatherSeat : ISeat
    {
        #region ISeat Members

        public string SeatType(string carName)
        {
          return string.Format( "This {0}'s seats are of leather.",carName);
        }

        #endregion
    }
}

PlasticSeat.cs is as following :

namespace DependencyInjection.Core
{
   public class PlasticSeat : ISeat
    {
        #region ISeat Members

        public string SeatType(string carName)
        {
            return string.Format("This {0}'s seats are of plastic.", carName);
        }

        #endregion
    }
}

In this point I’m adding reference of “Ninject.Core.dll” with my  “DependencyInjection.Core” project which I have downloaded from Ninject’s site. Now in my main class “Car” I’m going to inject one type of engine and another type of seat which I have mapped (DI mapping) through “IocMapper” class as bellow.
Car.cs is as bellow :

using Ninject.Core;

namespace DependencyInjection.Core
{
    public class Car
    {
        public IEngine CarEngine { get; set;}
        public ISeat   CarSeat   { get; set;}

        [Inject]
        public Car(IEngine engine , ISeat seat)
        {
            CarEngine   = engine;
            CarSeat     = seat;
        }

        public string GetEngineInformation(string carName)
        {
           return CarEngine.EngineType(carName);
        }

        public string GetSeatInformation(string carName)
        {
            return CarSeat.SeatType(carName);
        }
    }
}


In the above file  “ [Inject] “ attribute is place above the Car constructer to make it definable to Ninject so that Ninject can inject mapped object as described in “IocMapper” class.
I have taken another console application project named “DependencyInjection” in which I placed my “IocMapper” class.
IocMapper.cs is as following :

using Ninject.Core;

using DependencyInjection.Core;

namespace DependencyInjection
{
    public class IocMapper : StandardModule
    {
        public override void Load()
        {
            Bind<IEngine>().To<DieselEngine>();

            Bind<ISeat>().To<LeatherSeat>();
        }
    }
}


Now in program class I defined the kernel constructer and and initialize my car object.
Program.cs file is as bellow :

using System;
using Ninject.Core;
using DependencyInjection.Core;

namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new IocMapper());

            Car car = new Car(kernel.Get<IEngine>(), kernel.Get<ISeat>());

            Console.WriteLine(car.GetEngineInformation("Toyota"));

            Console.WriteLine(car.GetSeatInformation("BMW"));

            Console.ReadKey();

        }
    }
}

We can do more advance level of conditional binding with Ninject. Hope in near future I will throw a post on advance use of Ninject.

That’s all for today.
BYE

Hello All

Today I will go through logging with Log4net. Log4Net is a logging framework ( a rich library) for .NET. Log4Net is popular for its simplicity and robustness. We can write log in various way though we generally write log only in file we we can also mail log, show in console,save in datatbase as well as write in file in different ways.

First we have to download the Log4Net and add the log4net.dll in our implementation project. In the example I have take 2 projects named LogWriter and LogRunner accordingly, In one project I have implemented the logging and in another I execute that logging method.

My project structure is as image bellow :

In the LogWriter I have take two class as bellow :

LogLevel.cs: In this class I simply define a enum which basically helps to define my log level in my LogUtil class.

namespace LogWriter
{
    public enum LogLevel
    {
        DEBUG,
        ERROR,
        FATAL,
        INFO,
        WARN
    }
}

LogUtil.cs: In this class I have a static method named WriteLog which take 2 parameters one define log level and another take log message as string.

using log4net;
using log4net.Config;

namespace LogWriter
{
    public static class LogUtil
    {
        private static ILog logger = LogManager.GetLogger(typeof(LogUtil));

        static LogUtil()
        {
            XmlConfigurator.Configure();
        }

        public static void WriteLog(LogLevel logLevel,string log)
        {
            if (logLevel.Equals(LogLevel.DEBUG))
            {
                logger.Debug(log);
            }
            else if (logLevel.Equals(LogLevel.ERROR))
            {
                logger.Error(log);
            }
            else if (logLevel.Equals(LogLevel.FATAL))
            {
                logger.Fatal(log);
            }
            else if (logLevel.Equals(LogLevel.INFO))
            {
                logger.Info(log);
            }
            else if (logLevel.Equals(LogLevel.WARN))
            {
                logger.Warn(log);
            }             

        }
    }
}

As I am writing a  console application so my mail runner file is Program.cs which is as bellow but you can follow the same procedure in different place as per you requirement.

using System;
using LogWriter;

namespace LogRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            try {
                throw new Exception();
            }

            catch (Exception exc)
            {
                    LogUtil.WriteLog(LogLevel.DEBUG, "Debug mode logging");
                    LogUtil.WriteLog(LogLevel.ERROR, "Error mode logging");
                    LogUtil.WriteLog(LogLevel.FATAL, "Fatal mode logging");
                    LogUtil.WriteLog(LogLevel.INFO, "Info mode logging");
                    LogUtil.WriteLog(LogLevel.WARN, "Warn mode logging");

                    Console.ReadKey();
            }
        }
    }
}

Now one of the most important thing I will focus is log4net configuration. We can configure it from web.config or app.config . In my example I have configured it app.config file in my LogRunner project. In the app.config file follow the commented section.

My configuration file is as bellow , please go through the commented line to get know in detail such as log file rolling, max log file number & size, Log level etc.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <configSections>

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

    <log4net>

        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">

            <!-- Log file locaation -->
            
            <param name="File" value="C:\Users\sanzeeb\Documents\Visual Studio 2008\Projects\Solution1\LogWriter\Log\" />

            <param name="AppendToFile" value="true" />

            <!-- Maximum size of a log file -->
            <maximumFileSize value="2KB" />

            <!--Maximum number of log file -->
            <maxSizeRollBackups value="8" />

            <!--Set rolling style of log file -->
            <param name="RollingStyle" value="Composite" />

            <param name="StaticLogFileName" value="false" />

            <param name="DatePattern" value=".yyyy-MM-dd.lo\g" />

            <layout type="log4net.Layout.PatternLayout">

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

        <!-- Appender layout fix to view in console-->
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >

            <layout type="log4net.Layout.PatternLayout">

                <param name="Header" value="[Header]\r\n" />

                <param name="Footer" value="[Footer]\r\n" />

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

      
        <!-- Database appender -->

        <!--
        You need to create a table as bellow to insert log in database for MSSQL server.

        CREATE TABLE [dbo].[Log] (
        [Id] [int] IDENTITY (1, 1) NOT NULL,
        [Date] [datetime] NOT NULL,
        [Thread] [varchar] (255) NOT NULL,
        [Level] [varchar] (50) NOT NULL,
        [Logger] [varchar] (255) NOT NULL,
        [Message] [varchar] (4000) NOT NULL,
        [Exception] [varchar] (2000) NULL
        )
        -->

        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <bufferSize value="100" />
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="Data Source=SANZEEB-PC\SQLEXPRESS;Initial Catalog=AppTesterDB;Integrated Security=True" />
            <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.RawTimeStampLayout" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%thread" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%level" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%logger" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%message" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@exception" />
                <dbType value="String" />
                <size value="2000" />
                <layout type="log4net.Layout.ExceptionLayout" />
            </parameter>
        </appender>

        <root>

            <level value="DEBUG" />

            <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL
            ERROR = 2 show  log -> FATAL ERROR
            WARN =  3 show  log -> FATAL ERROR WARN
            INFO =  4 show  log -> FATAL ERROR WARN INFO
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->

            <!—To write log in file -->
            <appender-ref ref="LogFileAppender" />

            <!--To view log in console -->
            <appender-ref ref="ConsoleAppender" />
            
            <!--To write log in file batabase -->
            <appender-ref ref="AdoNetAppender" />

        </root>

    </log4net>

</configuration>

Hope this will help to improve your logging in your .NET application.

Thanks

That’s all for today.

BYE