Tuesday, 31 December 2013

Is viewstate of the control is maintained when its visible property is false in C# ASP.NET

Yes, When we set visible ='false' for any control, the control is not rendered into the form but its state is maintained with the help of viewstate.
If we set EnableViewState = 'false' for any control it means its state will not be maintained. 

For Example :-

aspx page
<form id="myForm" runat="server">
    <div>
 
        <asp:TextBox ID="txtFirstValue" runat="server">     </asp:TextBox>
        <asp:Button ID="btnClick"
            runat="server" Text="Button" onclick="btnClick_Click />
 
        <asp:TextBox ID="txtSecondValue" runat="server" Visible="false">1</asp:TextBox>
 
    </div>
    </form>


aspx.cs page
public partial class Index : System.Web.UI.Page
{
    int number;
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        txtFirstValue.Text = txtSecondValue.Text;
        number = Convert.ToInt32(txtSecondValue.Text);
        number++; //To increment by 1
        txtSecondValue.Text = number.ToString();
    }
}

Output of this program is : 1,2,3,4,5,6 etc. It means every time viewstate is maintained even visible property is false.
If we want that viewstate should not be maintained for a control we will do something like this

<asp:textbox id="txtSecondValue" runat="server" visible="false"  EnableViewState="false">1</asp:textbox>

Now every time output will be 1 because no viewstate was maintained.


That’s it!!…..Happy Programming...

How to Create a Facebook Like Chat Panel Interface in C# ASP.NET using CSS

Create a Panel Like this :-

  <asp:Panel runat="server" ID="pnlPopUp" CssClass="chatPanel">
        <div class="chatName flip">
            Chat Person Name
  <asp:ImageButton ID="imgbtnClose" runat="server" ImageUrl="~/images/LightBox/close.png" OnClick="imgbtnClose_Click" CssClass="closeChat" ToolTip="Close" />
        </div>
        <div class="slidetogle">
            <div class="messagehistory">
                Message History will show here.
            </div>
            <div class="newmessage">
                Enter your message here...
            </div>
        </div>
    </asp:Panel>


Css Classes For this Panel :-

.messagehistory {
            background-color: #F0F9FF;
            height: 230px;
            color: Gray;
            border-bottom: 1px solid gray;
            overflow: auto;
        }


        .newmessage {
            background-color: #F0F6FF;
            height: 40px;
            color: Gray;
        }


        .chatPanel {
            width: 280px;
            max-height: 300px;
            bottom: 0px;
            right: 35%;
            position: fixed;
            z-index: 20;
            border: 1px solid gray;
            display: inline-block;
        }


        .chatName {
            width: 100%;
            border: 1px solid gray;
            height: 30px;
            text-align: center;
            background-color: rgb(37,152,196);
            font-size: medium;
            color: White;
        }


        .closeChat {
            margin-left: 30%;
            height: 60%;
            padding-top: 2px;
        }




That’s it!!…..Happy Programming...

Sunday, 29 December 2013

How to know difference between value type parameter and reference type parameter in C#

Sometimes a user search with these kind of questions :-

what are the basics differences between value type and reference type in C#
reference type vs value type in C#
value type and reference type in C#
Solution :- Definition : Value types are those which hold both data and memory on the same location. Reference types are those which has a pointer which points to the memory location. Something like this...

using System;

namespace demo
{
    class Program
    {
        public static void valueType(int number)
        {
            number++; // or number=number+1
        }

        public static void referenceType(ref int number)
        {
            number++; // or number=number+1
        }

        static void Main(string[] args)
        {
            int number;
            Console.Write("Enter any number : ");
            number = Convert.ToInt32(Console.ReadLine()); // read user input number

            Console.WriteLine("\nValue Type");
            Console.Write("\nPrevious Value : {0}", number);
            Program.valueType(number); // call static method of Program class
            Console.Write("\nCurrent Value : {0}", number);
            Console.WriteLine("\nReference Type");
            Console.Write("\nPrevious Value : {0}", number);
            Program.referenceType(ref number); // call static method of Program class
            Console.Write("\nCurrent Value : {0}", number);
            Console.ReadLine();
        }
    }
}



That’s it!!…..Happy Programming...

Saturday, 28 December 2013

Multiple Logics to Swap Two Numbers in any Programming Language

This Question is sometimes used to see the analytic ability of a person and how dynamic thinking they have. The logic is same for all programming language, so if you have the logic right then you can answer it for any particular language such as PHP, JAVA, C++, C, C# etc. 

With using a third variable :-

Logic No.1 : temp=a; a=b; b=temp;


Without using a third variable :-

Logic No.2 : a=a+b; b=a-b; a=a-b;
Logic No.3 : a=a/b; b=a*b; a=(1/a)*b;
Logic No.4 : a=a*b; b=a/b; a=a/b;
Logic No.5 : a=(a+b)-(b=a);


That’s it!!…..Happy Programming...

Friday, 27 December 2013

How to check User Input Number is Even or Odd without using conditional statement C#


using System;

class Program
{
    public static void Main()
    {
        try
        {
            Console.WriteLine("Enter any number : ");
            int number = Convert.ToInt32(Console.ReadLine());

            int remainder = number % 2;
            int checkNumber = number / remainder;

// if remainder is not zero than this statement will execute other wise program control goes to catch block bcoz divide by zero exception would be occured
            Console.WriteLine("Number is Odd");
            Console.ReadKey();
        }

        catch (Exception ex)
        {
            Console.WriteLine("Number is even");
            Console.ReadKey();
        }
    }
}
To implement same concept in Java Click Here


That’s it!!…..Happy Programming...

How to pass values from one page to another page in C# ASP.NET?


You can use ViewState to maintain the state of controls during page postback.

For setting Viewstate :-
ViewState["myName"] = "xyz";

For retrieving Viewstate on postback:
string myName = ViewState["myName"].ToString();


You can use Cookies to save information on client side.

For setting Cookies :-

HttpCookie cName = new HttpCookie("Name");
cName.Value = txtName.Text;
Response.Cookies.Add(cName);
Response.Redirect("newPage.aspx");


You can use the Context to Transfer data to the one page to another.

For setting Context :-

Page1.aspx.cs
this.Context.Items["fName"] = "xyz";

Page2.aspx.cs
string fName = this.Context.Items["fName"].ToString();


You can use the Session Variable to preserve the common data which is required almost for every page or across the application for the specific user.

For setting Session:
Session["fName"] = "xyz";

For retrieving Session from any page :
string fName = Session["fName"].ToString();//default session timeout is 20 minutes
That’s it!!…..Happy Programming...

How to check website/url exists using javascript and C# ASP.NET

Sometimes we find questions in search engine like that:

C# - Check URL exists
C# - How can I check if a URL exists/is valid?
C# - Use httpwebrequest to check if url exist

Here is the answer of all your questions.....
Mostly the question Arise when we put our url in form fill section. But after filling the form at last we find that this is wrong url or website does not exist. so it is not much better, so we can solve this with C# simple code by clicking below link :-

http://techthoughtcircle.blogspot.in/2013/11/how-to-check-websiteurl-exists-using.html


That’s it!!…..Happy Programming...

How to Implement 3-Tier architecture in C# ASP.NET

When we create any .net application and want to seperate our logic from user interface than we all think of 3-tier architecture..Than another question raise in our mind how to implement 3 tier architecture in asp.net???

Solution :-
Start a new website project.
Design you page with 3 labels, 3 textboxes and 1 button.
Add sub-folders and class objects within the App_code folder as shown below :-



Code for the add button is something like this :-
protected void btnAdd_Click(object sender, EventArgs e)
{
    CustomerBAL customer = new CustomerBAL();
    try
    {
        if (customer .Insert(txtCustomerID.Text, txtFirstName.Text, txtLastName.Text) > 0)
        {
            lblMessageStatus.Text = "Record inserted successfully.";
        }
        else
        {
            lblMessageStatus.Text = "Record not inserted, some error occured.";
        }
    }
    catch (Exception ex)
    {
        lblMessageStatus.Text = ex.Message;
    }
    finally //Always Executable code here
    {
        customer = null;
    }
} 
Create a class with name 'CustomerBAL'.This will work as your Business layer.
Code for CustomerBAL.cs
using System;
using System.Collections.Generic;
using System.Web;

public class CustomerBAL
{
    public CustomerBAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public int Insert(string CustomerID, string FirstName, string LastName)
    {
        CustomerDAL customerDAL=new CustomerDAL();
        try
        {
            return customerDAL.Insert(CustomerID, FirstName, LastName);
        }
        catch
        {
            throw;
        }
        finally
        {
            customerDAL = null;
        }
    }
} 
Create a Class with name 'CustomerDAL'.This will work as Your Data Access Layer.
Code for CustomerDAL.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Data;

public class CustomerDAL
{
    public CustomerDAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public int Insert(string CustomerID, string FirstName, string LastName)
    {
        //declare SqlConnection and initialize it to the settings in the section of the web.config
        SqlConnection Conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
        //===============================
        //prepare the sql string
        string strSql = "insert into t_Customers(CustomerID,FirstName,LastName) ";
        strSql = strSql + "values(@CustomerID,@FirstName,@LastName)";

        //declare sql command and initalize it
        SqlCommand Command = new SqlCommand(strSql, Conn);

        //set the command type
        Command.CommandType = CommandType.Text;

        try
        {
            //define the command parameters
            Command.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.VarChar));
            Command.Parameters["@CustomerID"].Direction = ParameterDirection.Input;
            Command.Parameters["@CustomerID"].Size = 28;
            Command.Parameters["@CustomerID"].Value = CustomerID;

            Command.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.VarChar));
            Command.Parameters["@FirstName"].Direction = ParameterDirection.Input;
            Command.Parameters["@FirstName"].Size = 28;
            Command.Parameters["@FirstName"].Value = FirstName;

            Command.Parameters.Add(new SqlParameter("@LastName", SqlDbType.VarChar));
            Command.Parameters["@LastName"].Direction = ParameterDirection.Input;
            Command.Parameters["@LastName"].Size = 28;
            Command.Parameters["@LastName"].Value = LastName;

            //open the database connection
            Conn.Open();
            //execute the command
            return Command.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }
        finally //Connection will end here
        {
            Command.Dispose();
            Conn.Dispose();
        }
    }
}
Set the connection string on the web.config file.
Run the Project.



That’s it!!…..Happy Programming...

Thursday, 26 December 2013

Convert Current Date into Words format by Creating a Class in C# ASP.NET

Some times we face the problem if we want to convert the date format in to words then we have many options to do this task, i will give the answer using C# Class. 

Solution :-
For example : we get the date in c# with code (DateTime.Today) and convert it in words.
First Create a Class with Name class  'DateInWords' and Code Like this :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DateInWords
{
    static int firstTime = 0;
    static readonly string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    static readonly string[] firsts = new string[] { "", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth" };
    static readonly string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    static readonly string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    static readonly string[] thousandsGroups = { "", " Thousand", " Million", " Billion" };

    private static string FriendlyInteger(int n, string leftDigits, int thousands)
    {
        if (n == 0)
        {
            return leftDigits;
        }
        else
        {
            string friendlyInt = leftDigits;
            if (friendlyInt.Length > 0)
                friendlyInt += " ";

            if (n < 10 & firstTime == 0)
            {
                friendlyInt += firsts[n];
            }
            else if (n < 10 & firstTime != 0)
            {
                friendlyInt += ones[n];
            }
            else if (n < 20)
                friendlyInt += teens[n - 10];
            else if (n < 100)
                friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
            else if (n < 1000)
                friendlyInt += FriendlyInteger(n % 100, (firsts[n / 100] + " Hundred"), 0);
            else
                friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands + 1), 0);

            firstTime = firstTime + 1;
            return friendlyInt + thousandsGroups[thousands];
        }
    }

    public static string DateToWritten(DateTime date)
    {
        firstTime = 0;
        return string.Format("{0} {1} {2}", IntegerToWritten(date.Day), date.ToString("MMMM"), IntegerToWritten(date.Year));
    }

    public static string IntegerToWritten(int n)
    {
        if (n == 0)
            return "Zero";
        else if (n < 0)
            return "Negative " + IntegerToWritten(-n);

        return FriendlyInteger(n, "", 0);
    }
}
and this class will return the date format in word .. So firstly we must pass the parameter in this class with any date format given in standards ... Example :
var outputDate = DateInWords.DateToWritten(DateTime.Today);// Current date is passing in DateToWritten function of 'DateInWords' static class.
        dateLabel.Text = outputDate;
the output will display in 'dateLabel'





That’s it!!…..Happy Programming...

Keep me logged in functionality in C# ASP.NET

Sometimes a user logs in to your website, comes back tomorrow and.... has to log in again. To avoid this problem i am providing option to keep you from having to enter your user name and password every time someone return. If someone check the 'Keep me logged in' box, a small cookie will create on your computer that will let us know who you are next time you login again.

Solution:-

First you have to create Cookie on login button click as follows :

protected void btnLogin_Click(object sender, System.EventArgs e)
{
    string Username = txtUsername.Text;
    string Password = txtPassword.Text;

//Create Cookie and Store the Login Detail in it, if check box is marked like this :-
if ((CheckBox1.Checked == true)) { HttpCookie createCookie = new HttpCookie("LoginDetail"); createCookie.Values("Username") = txtUsername.Text.Trim(); createCookie.Values("Password") = txtPassword.Text.Trim(); createCookie.Expires = System.DateTime.Now.AddDays(1); Response.Cookies.Add(createCookie); } Response.Redirect("Page Name");//Page Name on which you want to transfer your current page } Then you have check if cookie exists (is remember me marked), if yes fill the details like this on Page Load Event :- protected void Page_Load(object sender, System.EventArgs e) { if ((Response.Cookies("LoginDetail") != null)) { string uname = Response.Cookies("LoginDetail").Values("Username").ToString(); string pass = Response.Cookies("LoginDetail").Values("Password").ToString(); Response.Redirect("Page Name");//Page Name on which you want to transfer your current page } }


That’s it!!…..Happy Programming...