Pages

Wednesday, 22 January 2014

How to set path and domain for a cookie?

CookieName.Path = "/Articles/";

CookieName.Domain = "www.dotnetfunda.com";

Refresh or re-load the Asp.net page automatically

<meta http-equiv="refresh" content="5000">

How to populate month name in DropDownList in ASP.NET

DropDownList code

<asp:DropDownList ID="dropDown1" runat="server"></asp:DropDownList> 



Namespace to use

using System.Globalization; 



Code behind

DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);

        for (int i = 1; i < 13; i++)

        {

            //Response.Write(info.GetAbbreviatedMonthName(i) + "<br />");

            dropDown1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));

        }

How you can organize the security section of web.config file?

<authentication mode = " [Windows/Forms/Passport/None] ">

    <forms name = " [name] " loginUrl = " [url] " >

        <credentials passwordFormat = " [Clear, SHA1, MD5] ">

            <user name = " [username] " password = " [password] " />

        </ credentials>

    </forms>

    <passport redirectUrl = "internal" />

</ authentication>


<authorization>

    <allow users = " [mention list of users separated by comma] "

              roles = " [mention list of roles separated by comma] " />

    <deny users = " [mention list of users separated by comma] "

              roles = " [mention list of roles separated by comma] " />

</ authorization>


<identity impersonate = " [true/false] " />

calculate the time taken by a web page to execute

void Application_BeginRequest(object sender, EventArgs e)

    {

        Context.Items.Add("startime", DateTime.Now);

    }

    void Application_EndRequest(object sender, EventArgs e)

    {

        //Get the start time

        DateTime dt=(DateTime)Context.Items["startime"];

         //calculate the time difference between start and end of request

        TimeSpan ts = DateTime.Now-dt;

        Response.Write("number of milleseconds for execution"+"--"+ts.TotalMilliseconds);

        

         

    }

Displaying a table information dynamically ,without using any controls

step1: connect with the database. 


using System.Data.Sqlclient;

sqlconnection conn=new sqlconnection("server=....;user id=...;password=....");


step2: Enter the table name in a textbox,and displaying the table information 

 protected void TextBox1_TextChanged(object sender, EventArgs e)

    {

     try

        {

            string s1 = TextBox1.Text;

            //passing a query to fetch the table from database,which is entered in textbox 

            string s2 = "select * from " + s1;

            SqlDataAdapter da = new SqlDataAdapter(s2, conn);

            da.Fill(ds);

            DataTable dt = new DataTable();

            dt = ds.Tables[0];

           //creating a table dynamically 

            HtmlTable table = new HtmlTable();

            HtmlTableRow tr = null;

            HtmlTableCell tc = null;



           //displaying labels for displaying coloumn names in the table 

            if (dt.Columns.Count - 1 > 0)

            {

                tr = new HtmlTableRow();

                for (int i = 0; i < dt.Columns.Count; i++)

                {

                    tc = new HtmlTableCell();

                    Label lbl = new Label();

                    lbl.Text = dt.Columns[i].ColumnName;

                    lbl.ID = "lbl" + dt.Columns[i].ColumnName;

                    tc.Height = "50px";

                    tc.Width = "150px";

                    tc.Controls.Add(lbl);

                    tr.Controls.Add(tc);

                }

                table.Controls.Add(tr);

               

               //creating textboxes for displaying records information 



                for (int j = 0; j < dt.Rows.Count; j++)

                {

                    tr = new HtmlTableRow();

                    for (int k = 0; k < dt.Columns.Count; k++)

                    {

                        tc = new HtmlTableCell();

                        TextBox txt = new TextBox();

                        txt.ID = "txt" + j + k;

                        txt.Text = dt.Rows[j][dt.Columns[k].ToString()].ToString();

                        tc.Controls.Add(txt);

                        tr.Controls.Add(tc);

                    }

                    table.Controls.Add(tr);

                }

                form1.Controls.Add(table);

            }

        }

        catch (Exception ex)

        {

            Response.Write("Please enter a valid table");

        }

    }

Asp hover Menu issue in Safari Browser

if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
    {

        Request.Browser.Adapters.Clear();

    }

Check Capslock is on or off

Private Sub Text_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Textbox1.KeyDown
        If e.KeyCode = Keys.CapsLock Then
            If My.Computer.Keyboard.CapsLock Then
                MsgBox("CAPS LOCK is on")
            Else
                MsgBox("CAPS LOCK is off")
            End If
        End If
    End Sub

Tuesday, 21 January 2014

Hierarchical Parent-Child Structure in LINQ

C#
public class Department
{
    public int DeptID { get; set; }
    public string DeptName { get; set; }
    public List<Employee> employee { get; set; }
}
public class Employee
{
    public int EmpID { get; set; }
    public int DeptID { get; set; }
    public string Name { get; set; }
    public int AgeInYrs { get; set; }
}
VB.NET (10.0)
Public Class Department
      Public Property DeptID() As Integer
      Public Property DeptName() As String
      Public Property employee() As List(Of Employee)
End Class
Public Class Employee
      Public Property EmpID() As Integer
      Public Property DeptID() As Integer
      Public Property Name() As String
      Public Property AgeInYrs() As Integer
End Class
Sample Data
List<Department> lists = new List<Department>()
{
    new Department()
    {
        DeptID = 1, DeptName = "Marketing", employee = new List<Employee>
        {
            new Employee() { EmpID = 9, DeptID = 1, Name = "Jack Nolas", AgeInYrs = 28 },
            new Employee() { EmpID = 5, DeptID = 1, Name = "Mark Pine" , AgeInYrs = 42 },
            new Employee() { EmpID = 3, DeptID = 1, Name = "Sandra Simte" , AgeInYrs = 38 },
            new Employee() { EmpID = 8, DeptID = 1, Name = "Larry Lo" , AgeInYrs = 31 }
        }
    },
    new Department()
    {
        DeptID = 2, DeptName = "Sales", employee = new List<Employee>
        {
            new Employee() { EmpID = 1, DeptID = 2, Name = "Sudhir Panj" , AgeInYrs = 28 },
            new Employee() { EmpID = 7, DeptID = 2, Name = "Kathy Karlo" , AgeInYrs = 43 },
            new Employee() { EmpID = 4, DeptID = 2, Name = "Dinesh Kumar" , AgeInYrs = 34 }
        }
    },
    new Department()
    {
        DeptID = 3, DeptName = "HR", employee = new List<Employee>
        {
            new Employee() { EmpID = 2, DeptID = 3, Name = "Kaff Joe" , AgeInYrs = 25 },
            new Employee() { EmpID = 6, DeptID = 3, Name = "Su Lie" , AgeInYrs = 52 },
            new Employee() { EmpID = 10, DeptID = 3, Name = "Malcolm Birt" , AgeInYrs = 41 }
        }
    }
};
Here are some common Operations on a Hierarchical Parent-Child List. Please use this Converter Tool to convert the code to VB.NET
1. List Employees in Each Department
var empInDept = lists
    .Select(emp => new
    {
        Department = emp.DeptName,
        Employee = emp.employee.Select(e => e.Name)
    });
ObjectDumper.Write(empInDept, 1);
Employee_Each_Department
2. Print the Average Age of Employees in each Department
var avgAgePerDept = lists
                .Select(emp => new
                {
                    Department = emp.DeptName,
                    AverageAge = emp.employee.Average(avg => (double)avg.AgeInYrs)
                });
ObjectDumper.Write(avgAgePerDept, 1);
Average_Age
3. List only those Employees in each Department with Age > 30
var empGt30 = lists
    .Select(emp => new
    {
        Department = emp.DeptName,
        Emp = emp.employee.Where(em => em.AgeInYrs > 30)
        .Select(e => new
        {
            EmployeeName = e.Name,
            Age = e.AgeInYrs
        })
    });
ObjectDumper.Write(empGt30, 1);
Below_30
4. Count the number of Employees in each Department
var cntEmpPerDept = lists
                .Select(emp => new
                {
                    Department = emp.DeptName,
                    NoOfEmployees = emp.employee.Count()
                });
ObjectDumper.Write(cntEmpPerDept, 1);
CountInEachDepartment
5. Sort and List Employees in each Department
var ordered = lists
   .Select(emp => new
   {
       Department = emp.DeptName,
       Employee = emp.employee.OrderBy(e => e.Name)
       .Select(c => new
                {
                    Name = c.Name
                })
   });
ObjectDumper.Write(ordered, 1);
SortBy

get month name from given date


public static string GetMonthName(DateTime givenDate)
        {
            var formatInfoinfo = new DateTimeFormatInfo();
            string[] monthName = formatInfoinfo.MonthNames; 
            return monthName[givenDate.Month - 1] + "" givenDate.Year;

        }

Display Month short/full name

static string GetMonthName(int monthNum, bool abbreviate)
{
if (monthNum < 1 || monthNum > 12)
throw new ArgumentOutOfRangeException(“monthNum”);
DateTime date = new DateTime(1, monthNum, 1);
if (abbreviate)
return date.ToString(“MMM”);
else
return date.ToString(“MMMM”);
}

Display month difference

private static int monthDifference(DateTime startDate, DateTime endDate)
         {
             int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
             return Math.Abs(monthsApart);
         }

Find the First and Last Days of the Month with C#

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace FirstLastDay
{
 
    /// <summary>
    /// Example of one approach to obtaining the
    /// first and last days of any given month
    /// </summary>
    public partial class frmFirstAndLast : Form
    { 
 
The constructor is shown following the namespace and class declarations; it has been modified to load an array containing a list of all of the months into a ComboBox and to set the control to display the first item in its collection upon initialization. 
   
#region Constructor
 
        /// <summary>
        /// Constructor
        /// </summary>
        public frmFirstAndLast()
        {
            InitializeComponent();
 
            // creat an array of all of the months
            string[] months = {"January", "February", "March", "April",
                "May", "June", "July",
                "August", "September", "October", "November", "December"};
 
            // populate a combobox with all of the months
            cboMonths.Items.AddRange(months);
 
            // select an item
            cboMonths.SelectedIndex = 0;
        }
 
#endregion
 
The click event handlers region follows; this section actually calls the class methods used to retrieve the first and last of the month date values and in turn displays that information to the user.  The annotation describes the code. 
    
#region Click Event Handlers
 
        /// <summary>
        /// Find and display the first and last day of the month for
        /// the supplied date
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind_Click(object sender, EventArgs e)
        {
            // set the calendar date and click the find button to report
            // the first and last day of the month for any month selected
            // in the date time picker control
            //
            // set first day
            txtFirstDay.Text =
                GetFirstDayOfMonth(dtpDate.Value).ToShortDateString();
 
            // get day of week for first day
            string[] dateParts = txtFirstDay.Text.Split('/');
            DateTime dtFirstTemp = new
                DateTime(Convert.ToInt32(dateParts[2]),
                Convert.ToInt32(dateParts[0]),
                Convert.ToInt32(dateParts[1]));
 
            // display day of week in label
            lblDowFirst1.Text = dtFirstTemp.DayOfWeek.ToString();
           
            // set last day
            txtLastDay.Text =
                GetLastDayOfMonth(dtpDate.Value).ToShortDateString();
 
            // get day of week for last day
            string[] dateParts2 = txtLastDay.Text.Split('/');
            DateTime dtLastTemp = new
                DateTime(Convert.ToInt32(dateParts2[2]),
                Convert.ToInt32(dateParts2[0]),
                Convert.ToInt32(dateParts2[1]));
 
            // display day of week in label
            lblDowLast1.Text = dtLastTemp.DayOfWeek.ToString();
        } 
 
        /// <summary>
        /// Execute the code to set the first and last day of the month
        /// by passing in only an integer representation of the month
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind2_Click(object sender, EventArgs e)
        {
            // set the calendar date and click the find button to report
            // the first and last day of the month for any month selected
            // in the date time picker control
            //
            // set first day
            txtFirstDay2.Text = GetFirstDayOfMonth(cboMonths.SelectedIndex +
                1).ToShortDateString();
 
            // get day of week for first day
            string[] dateParts = txtFirstDay2.Text.Split('/');
            DateTime dtFirstTemp = new
                DateTime(Convert.ToInt32(dateParts[2]),
                Convert.ToInt32(dateParts[0]),
                Convert.ToInt32(dateParts[1]));
 
            // display day of week in label
            lblDowFirst2.Text = dtFirstTemp.DayOfWeek.ToString();
 
            //
            // set last day
            txtLastDay2.Text = GetLastDayOfMonth(cboMonths.SelectedIndex +
                1).ToShortDateString();
 
            // get day of week for last day
            string[] dateParts2 = txtLastDay2.Text.Split('/');
            DateTime dtLastTemp = new
                DateTime(Convert.ToInt32(dateParts2[2]),
                Convert.ToInt32(dateParts2[0]),
                Convert.ToInt32(dateParts2[1]));
 
            // display day of week in label
            lblDowLast2.Text = dtLastTemp.DayOfWeek.ToString();
 
            DateTime dt = new DateTime(dtpDate.Value.Year,
                dtpDate.Value.Month, 1);
        }
  
        /// <summary>
        /// Exit the Application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
 
#endregion
 
The last region in the class contains the methods used to get the first and last days of the month.  The region provides four methods, one gets the first day of the month based upon receipt of a date, one gets the first day of the month based upon receipt of an integer value representing a month, one gets the last day of the month based upon receipt of a date, one gets the last day of the month based upon receipt of an integer value representing a month.  The annotation describes the process used in each method.
     
#region Private Methods
  
        /// <summary>
        /// Get the first day of the month for
        /// any full date submitted
        /// </summary>
        /// <param name="dtDate"></param>
        /// <returns></returns>
        private DateTime GetFirstDayOfMonth(DateTime dtDate)
        {
            // set return value to the first day of the month
            // for any date passed in to the method
 
            // create a datetime variable set to the passed in date
            DateTime dtFrom = dtDate;
 
            // remove all of the days in the month
            // except the first day and set the
            // variable to hold that date
            dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1));
 
            // return the first day of the month
            return dtFrom;
        }
        
        /// <summary>
        /// Get the first day of the month for a
        /// month passed by it's integer value
        /// </summary>
        /// <param name="iMonth"></param>
        /// <returns></returns>
        private DateTime GetFirstDayOfMonth(int iMonth)
        {
            // set return value to the last day of the month
            // for any date passed in to the method
 
            // create a datetime variable set to the passed in date
            DateTime dtFrom = new DateTime(DateTime.Now.Year, iMonth, 1);
 
            // remove all of the days in the month
            // except the first day and set the
            // variable to hold that date
            dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1));
 
            // return the first day of the month
            return dtFrom;
        }
  
        /// <summary>
        /// Get the last day of the month for any
        /// full date
        /// </summary>
        /// <param name="dtDate"></param>
        /// <returns></returns>
        private DateTime GetLastDayOfMonth(DateTime dtDate)
        {
            // set return value to the last day of the month
            // for any date passed in to the method
 
            // create a datetime variable set to the passed in date
            DateTime dtTo = dtDate;
 
            // overshoot the date by a month
            dtTo = dtTo.AddMonths(1);
 
            // remove all of the days in the next month
            // to get bumped down to the last day of the
            // previous month
            dtTo = dtTo.AddDays(-(dtTo.Day));
 
            // return the last day of the month
            return dtTo;
        }
  
        /// <summary>
        /// Get the last day of a month expressed by it's
        /// integer value
        /// </summary>
        /// <param name="iMonth"></param>
        /// <returns></returns>
        private DateTime GetLastDayOfMonth(int iMonth)
        {
 
            // set return value to the last day of the month
            // for any date passed in to the method
 
            // create a datetime variable set to the passed in date
            DateTime dtTo = new DateTime(DateTime.Now.Year, iMonth, 1);
 
            // overshoot the date by a month
            dtTo = dtTo.AddMonths(1);
 
            // remove all of the days in the next month
            // to get bumped down to the last day of the
            // previous month
            dtTo = dtTo.AddDays(-(dtTo.Day));
 
            // return the last day of the month
            return dtTo;
 
        }
 
#endregion
   }
}