How to create the Multilanguage application in asp.net?


English

Swedish

We can create the Multilanguage application in asp.net like this

Step 1: Add the Master Page Site1.Master and Design the Menu and language Selection dropdown list like this

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="MultilanguageSample.Site1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        html {
            font-family: Tahoma;
            font-size: 14px;
            font-style: normal;
            background-color: Silver;
        }

        .Content {
            margin: auto;
            width: 700px;
            background-color: white;
            border: Solid 1px black;
        }
        .auto-style1 {
            width: 100%;
        }
    </style>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

<body>
    <form id="form1" runat="server">
        <div class="Content">
        <br />
            <table class="auto-style1">
                <tr>
                    <td style="background-color: #339966"> <a href="Default.aspx">
                <asp:Label ID="Label1" meta:resourcekey="menuItemDefault" runat="server" Text="Home"></asp:Label>
            </a></td>
                    <td style="background-color: #339966; " ><a href="Contact.aspx">
            <asp:Label ID="Label2" meta:resourcekey="menuItemContact" runat="server" Text="ContactUs"></asp:Label>
        </a></td>
                    <td style="background-color: #339966;"><asp:DropDownList ID="DropDownList_Language" runat="server" Height="20px" Width="170px"
            OnSelectedIndexChanged="DropDownList_Language_SelectedIndexChanged" AutoPostBack="true">
            <asp:ListItem Value="en-US">English</asp:ListItem>
            <asp:ListItem Value="sv-SE">Swedish</asp:ListItem>
        </asp:DropDownList></td>
                </tr>
            </table>
        <br />
        <br />

        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
        </div>
    </form>
</body>
</html>

Step 2: Write the code in code behind file like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MultilanguageSample
{
    public partial class Site1 : System.Web.UI.MasterPage
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["language"] != null && !IsPostBack)
            {
                DropDownList_Language.ClearSelection();
                DropDownList_Language.Items.FindByValue(Session["language"].ToString()).Selected = true;
            }
        }
        protected void DropDownList_Language_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (DropDownList_Language.SelectedValue)
            {
                case "en-US": this.SetMyNewCulture("en-US");
                    break;
                case "sv-SE": this.SetMyNewCulture("sv-SE");
                    break;
                default:
                    break;
            }
            Response.Redirect(Request.Path);
        }
 
        private void SetMyNewCulture(string culture)
        {
            Session["language"] = culture;
        }
    }
}

Note: Here you can also store the user language selection in cookies or Local Storage of Html 5 using JavaScript. This can be used to maintain the user preference language at page Load.

Step 3 : Create a “App_LocalResources” folder and add the resources as page wise Like Site.master .resx for English and Site1.Master.sv. resx for Swedish

Note: Keep the separate resource file for each page for better maintainability.

EnglishRes

Step 4: Add this method in global.asax file



void Application_AcquireRequestState(object sender, EventArgs e)
       {
           HttpContext context = HttpContext.Current;
           if (context.Session["language"] != null)
           {
               Thread.CurrentThread.CurrentUICulture = new CultureInfo(context.Session["language"].ToString().Trim());
               Thread.CurrentThread.CurrentCulture = new CultureInfo(context.Session["language"].ToString().Trim());
           }
       }

This is used for getting the current state of session.

Step 5: Call the resource key on label like this as a page wise.

You call also call the resource file in C# like this



protected void Page_Load(object sender, EventArgs e)
       {
          lblMsg.Text = GetLocalResourceObject("lblMsgHome.Text").ToString();
           
       }

How to use log4net in asp.net Project ?


Recently i had used log4net error handling plugin in one of my recent project. Previously i was using enterprise library for this task. But this is very flexible and essay to use in application.
We can use Log4net in our application using this few steps

Step 1: Install the Log4net plugin like this

Log4net

Step2: Inside the Configration section of Webconfig, keep this code related with log4net like this

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

  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="C:\MyLog\test.txt"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
  

Step 3: In global.aspx file, keep the code like this

protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}

Step 4: Now implement the error handling in your code like this

protected void btnClick_Click(object sender, EventArgs e)
{
log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
try
{
// This is used for generating the error in code.
int a;
a = Convert.ToInt32(txtNum.Text);
Response.Write(a);
}
catch (Exception ex)
{
logger.Error(ex.StackTrace);
}

}

Now if there will be any exception occur in application then it will create the log in C:\MyLog\test.txt

Posted in Asp.net. Tags: . Comments Off on How to use log4net in asp.net Project ?

How to Schedule Task In ASP.NET using Quartz.Net ?


Hi

Before few years ago i wrote article on this topic like this

https://chandradev819.wordpress.com/2011/04/10/how-to-create-a-job-scheduler-in-asp-net-application/

But now the same task we can do in very efficiently using Quartz.Net open source library. It is very flexible to use in asp.net and asp.net mvc application.

To learn more about Quartz.NET here is a great article on its website.
quartz-scheduler.net

Step1 : Just add the libray in your application like this image

Quarz.net

Step 2: Create one one class in appcode like AutoSave and write the code which one you want to schedule

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for AutoSave
/// </summary>
public class AutoSave:IJob
{
	
    public void Execute(IJobExecutionContext context)
    {
       // This code is used to save data in database
        using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("Insert into tblEmp(EmpName,EmpAdd) Values(@EmpName,@EmpAdd)",con))
            {
                cmd.Parameters.AddWithValue("@EmpName", "Chandradev");
                cmd.Parameters.AddWithValue("@EmpAdd", "Bangalore");
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}

Step 3: Now create on Jobscheduler class like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using Quartz.Impl;

/// <summary>
/// Summary description for JobSchedular
/// </summary>
public class JobSchedular
{

    public static void Start()
    {
        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        scheduler.Start();

        IJobDetail job = JobBuilder.Create<AutoSave>().Build();
        ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity("trigger1", "group1")
         .StartNow()
         .WithSimpleSchedule(x => x
        .WithIntervalInSeconds(5)
        .RepeatForever())
    .Build();
        scheduler.ScheduleJob(job, trigger);
    }
}

Note here i have created a simple scheduler which will fire in every 5sec . You can create you schedular on basis of your requirement. If we have trigger only one time in whole day then we can do like this


  .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();

Step 4: Add in global.asax file like this


void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterOpenAuth();
        JobSchedular.Start();
    }

I got the data in database like this.

Schedular

Posted in Asp.net. 1 Comment »

How to format Gridview rows on basis of data in asp.net ?


GridFormate
Hi

We can format asp.net gridview rows on basis of data using C# helper method like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }

    public string FormatEmpSal(object objEmpSal) 
    {
        if (objEmpSal.Equals(DBNull.Value.ToString()))
        {
            return "<span style='color: red; font-weight: bold;'>EmpSal is Blank</span>";
        }
        else
        {
            decimal Sal = Convert.ToDecimal(objEmpSal);
            if (Sal <= 0)
            {
                return "<span style='color: red; font-weight: bold;'>EmpSal is Zero</span>";
            }
            else
            {
                return Sal.ToString();
            }
        }
    }
}

In aspx bind this method like this

FormateGridCode

Posted in Asp.net. 1 Comment »

How to access user Control field in asp.net ?


UCProperty
Hi

If you are using asp.net user control in project then obviously you will get requirement to access that field in your parent page.

For example you are creating UserRegistration form as User control and going to use in so many module then you will create user control. Now you have to read all fields in your parent page then you can not read that field directly.

You can do like this

Step1: Create properties for field which one you are going to expose from your usercontrol like this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }

    public string Name 
    {
        get { return txtName.Text; }
        set { txtName.Text = value; }
    }

    public string Address   
    {
        get { return txtAddress.Text; }
        set { txtAddress.Text = value; }
    }

    public string EmailId
    {
        get { return txtEmailId.Text; }
        set { txtEmailId.Text = value; }
    }


}

Step2: Now on button click i have to read that field then i can read like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string empName = EmpRegUserControl.Name;
        string empAddress = EmpRegUserControl.Address; 
        string emailId = EmpRegUserControl.EmailId;
    }
}

How to create custom paging in Gridview using CTE ?


CustomPaging

Hi

There are so many approaches to do custom paging in Gridview for eaxmple using LINQ, using Temp table, using CTE etc.

Recently i used custom paging in gridview using CTE in store procedure. CTE is commmon table Expression. This feature come in sql server 2005 onward.

We generally use custom paging to increase the performance of application. if we will not use custom paging then every time all data will fetch from database. So performance of application will be very very slow.

We can do custom paging using CTE in very simple ways

Note: Here i have used datalist for displaying paging in footer of Gridview.

Step1: Write the store procedure using CTE like this



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Exec getEmpDetails 1,100,0

ALTER PROCEDURE getEmpDetails
      @StartIndex int,
      @PageSize int,
      @TotalCount int OutPut
as
--Select @TotalCount=count(1) from tblEmp where EmpName like '%';
Select @TotalCount=count(1) from tblEmp;

WITH EmpCTE AS
(
   select top(@startIndex+@PageSize-1) ROW_NUMBER() OVER(ORDER BY EmpId) 
   RowNumber,
   EmpId,
   EmpName,
   EmpSal
   from tblEmp 
)
select * from EmpCTE where RowNumber between @startIndex and (@startIndex+@PageSize-1)

GO

Step 2: Create the Entity of table like in Business Entity layer


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CustomPaging
{
    public class EmpBE
    {
        public int StartIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalCount { get; set; }
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public string EmpSal { get; set; }
    }
}

Step3: Write the Method for fetching data from database in Data acess layer like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.ObjectModel;


namespace CustomPaging
{
    public class EmpDAL
    {
        SqlConnection con=new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=EmpDB;Integrated Security=True");

        public Collection<EmpBE> GetEmpsDetails(EmpBE objEmp,out int totalcount) 
        {
            con.Open();
            
            Collection<EmpBE> EmpList = new Collection<EmpBE>();
            using (SqlCommand cmd = new SqlCommand("getEmpDetails", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@StartIndex", objEmp.StartIndex);
                cmd.Parameters.AddWithValue("@PageSize", objEmp.PageSize);
                SqlParameter parTotalCount = new SqlParameter("@TotalCount", SqlDbType.Int);
                parTotalCount.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(parTotalCount);

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        EmpBE objEmp1 = new EmpBE();
                        objEmp1.EmpId = Convert.ToInt32(dr["EmpId"]);
                        objEmp1.EmpName = Convert.ToString(dr["EmpName"]);
                        objEmp1.EmpSal = Convert.ToString(dr["EmpSal"]);
                        EmpList.Add(objEmp1);
                    }
                    con.Close();
                    totalcount = Convert.ToInt32(parTotalCount.Value);
                }
            }
            return EmpList;
        }
    }
}

Step 4: Design the .aspx page like this


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="CustomPaging.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style3
        {
            width: 121px;
        }
        .style4
        {
            width: 98px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" Width="356px" ForeColor="#333333"
            AutoGenerateColumns="False">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:BoundField DataField="EmpId" HeaderText="EmpId" />
                <asp:BoundField DataField="EmpName" HeaderText="EmpName" />
                <asp:BoundField DataField="EmpSal" HeaderText="EmpSal" />
            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
        </asp:GridView>
        <asp:DataList CellPadding="2" RepeatDirection="Horizontal" runat="server" ID="dlPager"
            OnItemCommand="dlPager_ItemCommand" BackColor="LightGoldenrodYellow" Width="356px"
            BorderColor="Tan" BorderWidth="1px" ForeColor="Black">
            <AlternatingItemStyle BackColor="PaleGoldenrod" />
            <FooterStyle BackColor="Tan" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <ItemTemplate>
                <asp:LinkButton Enabled='<%#Eval("Enabled") %>' runat="server" ID="lnkPageNo" Text='<%#Eval("Text") %>'
                    CommandArgument='<%#Eval("Value") %>' CommandName="PageNo"></asp:LinkButton>
            </ItemTemplate>
            <SelectedItemStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        </asp:DataList>
        <br />
    </div>
    </form>
</body>
</html>

Step 5: write the code in Code behind file like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;

namespace CustomPaging
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        int pageSize = 3;
        int totalRowCount = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridview(1);
            }
        }

       
        /// <summary>
        /// This Method is used to generate the paging.
        /// </summary>
        /// <param name="totalRowCount">It has passed as integer.</param>
        /// <param name="pageSize">It has passed as integer.</param>
        /// <param name="currentPage">It has passed as integer.</param>

        public void generatePager(int totalRowCount, int pageSize, int currentPage)
        {
            int totalLinkInPage = 3;
            int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            int startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            int lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            List<ListItem> pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
                pageLinkContainer.Add(new ListItem("First", "1", currentPage != 1));
            for (int i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
            }

            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("Last", totalPageCount.ToString(), currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }
        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "PageNo")
            {
                BindGridview(Convert.ToInt32(e.CommandArgument));
            }
        }

        private void BindGridview(int currentPage) 
        {
            int startRowNumber = ((currentPage - 1) * pageSize) + 1;
            EmpDAL objDAL = new EmpDAL();
            EmpBE objBE = new EmpBE();
            objBE.StartIndex = startRowNumber;
            objBE.PageSize = 3;
            objBE.TotalCount = 0;
            Collection<EmpBE> objEmpList = new Collection<EmpBE>();
            objEmpList = objDAL.GetEmpsDetails(objBE,out totalRowCount);
            GridView1.DataSource = objEmpList;
            GridView1.DataBind();
            generatePager(totalRowCount, pageSize, currentPage);
        }
    }
}

How to load user control dynamically in asp.net page ?


Hi

So many time we get scenario to display some user control on some location on some condition then we can achieve this by loading the user control dynamically.

For doing this task we can do like

Step 1: Create some list of user control and keep in some folder

Step2: Keep one place Holder control in asp.net page like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicLoadingUserControl.aspx.cs" Inherits="DynamicLoadingUserControl" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>


Step 3: Now write the code behind file of aspx page for loading the user control like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class DynamicLoadingUserControl : System.Web.UI.Page
{
    // randomFolder is the Folder Name which Contains the collection of User control
    const string randomFolder = "TestUserControl";

    protected void Page_Load(object sender, EventArgs e)
    {
        string featuredProductPath = GetRandomProductPath();
        Control featuredProduct = Page.LoadControl(featuredProductPath);
        PlaceHolder1.Controls.Add(featuredProduct);
    }

    private string GetRandomProductPath()
    {
        Random rnd = new Random();
        string[] files = Directory.GetFiles(MapPath(randomFolder), "*.ascx");
        string featuredProductPath = Path.GetFileName(files[rnd.Next(files.Length)]);
        return Path.Combine(randomFolder, featuredProductPath);
    }
}