Search This Blog

Tuesday, February 11, 2014

Date format in Asp.net Examples

How to Insert Record Instead of Default Date format to dd/mm/yyyy or dd-mm-yyyy???


Default Date Format in C sharp is 

Example :- 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime d = new DateTime();
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}

Then Default Output is 1/1/0001 12:00:00 AM

So, We must to change or Give the datetime of now to d.

DateTime d = System.DateTime.Now;

The it will Give Output As Current Date and Time :- mm/dd/yyyy hh:mm:ss am/pm

Indian Standard time output is :   2/11/2014 5:30:54 PM


If i have to take universal Time then use below Function

DateTime d = System.DateTime.Now.ToUniversalTime();


output is 2/11/2014 12:00:54 PM

Convert into Short date format mm/dd/yyyy.

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            String d = System.DateTime.Now.ToShortDateString();
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}
output :- mm/dd/yyyy


Convert into Short time format hh:mm 


            String d = System.DateTime.Now.ToShortTimeString();
output :- 5:30 PM

Convert into ole automation date.
This format is Normally used with COM and VB scripting purpose of automatic scripting after some time the code will be executed. Return type of this function is float.


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            double d = System.DateTime.Now.ToOADate();
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}

output :- 41681.7406242824


If we have to print only current year then

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int d = System.DateTime.Now.Year;
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}
 output :- 2014

To print Month then use.

int d = System.DateTime.Now.Month;

Output: 2


To print Date then use

int d = System.DateTime.Now.Day;

Output : 11


Print Hour of the date
int d = System.DateTime.Now.Hour;
output : 17 instead of 5 PM


Print Hour of the date
int d = System.DateTime.Now.Minute;
output : 30

To print Millisecond

int d = System.DateTime.Now.Millisecond;
output : 534



To print only time Use Timespan

syntax of output : hours:minutes:seconds

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeSpan d = System.DateTime.Now.TimeOfDay;
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}

Output :- 17:30:01.2312332


Which kind of time is taken into the Datetime we can check weather it is Utc or local?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTimeKind d = System.DateTime.Now.ToUniversalTime().Kind;
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}

output : Utc

 DateTimeKind d = System.DateTime.Now.Kind;

output : Local

IF we have to add years in date then we can add.


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime d = System.DateTime.Now.AddYears(2);
            Console.WriteLine(d);
            Console.ReadLine();
        }
    }
}
output will print date and time of 2016.
output is 2/11/2016 12:00:54 PM


Increase Month using AddMonth(int)

DateTime d = System.DateTime.Now.AddMonths(2);

Then Month is April.

output is 4/11/2016 12:00:54 PM


Increase Date using AddDays(int)

DateTime d = System.DateTime.Now.AddDays(2);

output is 2/13/2016 12:00:54 PM




Stored Procedures in Asp.net

Stored Procedure :

                                Stored Procedure (SP) in Asp.net c# is used for writing code which will be called from the BAL file for database connectivity.
                                With the help of SP the program of three tier architecture will give faster answer to us compare to code written in the asp.net BAL.cs file.
                               Faster Execution of the query.
                               And Separation is Advantage of using SP in Asp.net C# Web Application.

Syntax of Stored Procedure
ALTER PROCEDURE Procedurename
/*Here the parameters used inside query is used and separated with semicolon.
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
 Write your query here.

RETURN



Here Example code is given for Stored Procedure.

To Select Record from the database table tbladmin(id pk,username,password,mobileno,emailid)

ALTER PROCEDURE Select1

AS
select * from tbladmin
RETURN



To Delete record according to id number,

ALTER PROCEDURE deleteadmin
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
@aid int
AS
delete from tbladmin where id=@aid
RETURN

To Update record according to id number,

ALTER PROCEDURE updateadmin
@aid int,
@user varchar(50),
@mobile decimal(10,0),
@email varchar(50)

AS
update tbladmin set username=@user,mobileno=@mobile,emailid=@email where id=@aid
RETURN


Here is the code of Asp.net Project file 

Aspx file
Aspx.cs file
DAL.cs file
BAL.cs file



The BAL.cs File code of Database Connectivity.



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

/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
    SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
public BAL()
{
//
// TODO: Add constructor logic here
//
}

    public System.Data.DataSet SelectData(System.Data.DataSet ds)
    {
        DataSet ds1 = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter("select1", con);
        da.Fill(ds1);
        return ds1;
    }

    public void Deletedata(DAL d)
    {
        SqlCommand cmd = new SqlCommand("deleteadmin", con);
        cmd.Parameters.AddWithValue("@aid",d.Id);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    public void Updatedata(DAL d1)
    {
        SqlCommand cmd = new SqlCommand("updateadmin", con);
        cmd.Parameters.AddWithValue("@user",d1.Username);
        cmd.Parameters.AddWithValue("@mobile", d1.Mobileno);
        cmd.Parameters.AddWithValue("@aid", d1.Id);
        cmd.Parameters.AddWithValue("@email", d1.Emailid);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

}



DAL.cs File Code for properties declaration.



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

/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
public DAL()
{
//
// TODO: Add constructor logic here
//
}
    int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    string username;

    public string Username
    {
        get { return username; }
        set { username = value; }
    }
    
    string emailid;

    public string Emailid
    {
        get { return emailid; }
        set { emailid = value; }
    }
    decimal mobileno;

    public decimal Mobileno
    {
        get { return mobileno; }
        set { mobileno = value; }
    }


}





Default.Aspx.cs  for coding of the events.




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

public partial class _Default : System.Web.UI.Page
{
    DAL d1 = new DAL();
    BAL b = new BAL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillgrid();
        }
    }

    private void fillgrid()
    {      
        DataSet ds = new DataSet();
        ds = b.SelectData(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        d1.Id = id;
        b.Deletedata(d1);
        fillgrid();
        lbl.ForeColor = System.Drawing.Color.Red;
        lbl.Text = "Record is deleted from the database.";
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        TextBox tu = (TextBox)GridView1.Rows[e.RowIndex].FindControl("tusername");
        TextBox tm = (TextBox)GridView1.Rows[e.RowIndex].FindControl("tmobileno");
        TextBox te = (TextBox)GridView1.Rows[e.RowIndex].FindControl("temailid");
        d1.Id = id;
        d1.Username = tu.Text;
        d1.Emailid = te.Text;
        d1.Mobileno = decimal.Parse(tm.Text);
        b.Updatedata(d1);
        GridView1.EditIndex = -1;
        fillgrid();        
        lbl.ForeColor = System.Drawing.Color.Green;
        lbl.Text = "Record is updated successfully.";
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }

}




Default.aspx code for GUI of the gridview.


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

<!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:Label ID="lbl" runat="server"></asp:Label>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="id" 
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="AdminId">
                    <ItemTemplate>
                        <asp:Label ID="ladminid" Text='<%#bind("id") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="leadminid" Text='<%#bind("id") %>' runat="server"></asp:Label>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Username">
                    <ItemTemplate>
                        <asp:Label ID="lusername" Text='<%#bind("username") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="tusername" Text='<%#bind("username") %>' runat="server"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="MobileNo">
                    <ItemTemplate>
                        <asp:Label ID="lmobileno" Text='<%#bind("mobileno") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="tmobileno" Text='<%#bind("mobileno") %>' runat="server"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emailid">
                    <ItemTemplate>
                        <asp:Label ID="lemailid" Text='<%#bind("emailid") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="temailid" Text='<%#bind("emailid") %>' runat="server"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Edit" ShowEditButton="true" />
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="true" />
            </Columns>
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
    </div>
    </form>
</body>

</html>


Web.Config file to for Connection String.



<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <appSettings>
    <add key="constr" value="Data Source=LAB2-PC3\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"/>
  </appSettings>
</configuration>


For Learn C#.Net, ASP.Net, VB.Net Visit Our Website

Friday, September 27, 2013

Add Video into Webpage



You Can Embed the video in two different ways.


1. From the Tag Video and source
2. From Website The link of Page is given into the iframe.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Video Tag to Embed it. </h1>
      <video width="450" height="300" controls>
  <source src="video.mp4" type="video/mp4">

  Your browser does not support the video tag.
</video>
    </div>
    <div>
    <h1>Concept of Iframe To Embed Directly From Other Websites Like Youtube</h1>
    <iframe width="420" height="315" src="https://www.youtube.com/embed/aFiiX2799Vo" frameborder="0" allowfullscreen></iframe>
    </div>
    </form>
</body>
</html>

For Learn C#.Net, ASP.Net, VB.Net Visit OurWebsite

Saturday, September 7, 2013

Upload/Download File - Asp.net


Click  On Choose File To Upload File .

And

Click On Link Below Download To Download File From Your Project Page.

Create One Directory Name "file" in Your Project
And Create Table That Stores the id And path of your file.

Two source code files
Coding in Aspx Design of webpage and
Code .cs file contains C# coding
Aspx code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Submit" runat="server"
            Text="Submit" onclick="Submit_Click" />
        <br />
        <br />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Download">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server"
                            CommandArgument='<%# bind("path") %>' onclick="LinkButton1_Click"
                            Text='<%# bind("path") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>






aspx.cs code 

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

using System.IO;
public partial class _Default : System.Web.UI.Page
{
 
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\WebSite1\WebSite14\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            showdata();
        }
    }

    private void showdata()
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from tblfile",con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void Submit_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fname = FileUpload1.FileName;
            string fpath = "~\\file\\"+fname;
            FileUpload1.SaveAs(Server.MapPath(fpath));
            SqlCommand cmd = new SqlCommand("insert into tblfile values('"+fpath+"')",con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }
}
For Learn C#.Net, ASP.Net, VB.Net Visit OurWebsite

Saturday, April 6, 2013

Javascript validations

Email Validation

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
var b=emailfilter.test(document.form2.mailid.value);
if(b==false)
{
alert("Please Enter a valid Mail ID");
document.form2.mailid.focus();
return false;
}

Password Validation

var a = document.form.pass.value;
if(a=="")
{
alert("Please Enter Your Password");
document.form.pass.focus();
return false;
}
if ((a.length < 6) || (a.length > 20))
{
alert("Your Password must be 6 to 20 Character");
document.form.pass.select();
return false;
}

Mobile number Validation

var a = document.form.phone.value;
if(a=="")
{
alert("please enter your mobile no");
document.form.phone.focus();
return false;
}
if(isNaN(a))
{
alert("Enter the valid Mobile Number(Like : 9999911111)");
document.form.phone.focus();
return false;
}
if((a.length < 10) || (a.length > 10))
{
alert(" Your Mobile Number must be 10 Integers");
document.form.phone.select();
return false;
}

Gender Validation

ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if (ErrorText= "") { form.submit() }
}



Tuesday, April 2, 2013

Create Menu Using Javascript


First Create Six Images.
one.jpg
two.jpg


three.jpg
four.jpg


five.jpg
six.jpg



one and two for HOME
three and four for ABOUT
five and six for CONTACT

<html>
<head><title>Html Javascript </title>
<script = "text\javascript">
function f1()
{
img1.src="two.jpg";
}
function f2()
{
img1.src="one.jpg";
}
function f3()
{
img2.src="four.jpg";
}
function f4()
{
img2.src="three.jpg";
}
function f5()
{
img3.src="six.jpg";
}
function f6()
{
img3.src="five.jpg";
}

</script>
</head>
<body>
<img src="one.jpg" height="50px" width="150px" id="img1" alt="image" onmouseover="f1();" onmouseout="f2();" />
<img src="three.jpg" height="50px" width="150px" id="img2" alt="image" onmouseover="f3();" onmouseout="f4();" />
<img src="five.jpg" height="50px" width="150px" id="img3" alt="image" onmouseover="f5();" onmouseout="f6();" />

</body>
</html>

VB.Net SQL Server Connectivity For Insert New Record

//Create connection object

Dim con1 As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\student\Local Settings\Application Data\Temporary Projects\Databaseconvb\Database1.mdf;Integrated Security=True;User Instance=True")

//Create Command Object

Dim cmd As New System.Data.SqlClient.SqlCommand

cmd.CommandType = System.Data.CommandType.Text
     
cmd.CommandText = "INSERT tbl_user VALUES('" + txt_username.Text + "','" + txt_password.Text + "','" + txt_firstname.Text + "','" + txt_lastname.Text + "','" + gender.Text + "','" + txt_mobile.Text + "','" + txt_emailid.Text + "')"

cmd.Connection = con1

        con1.Open()

        cmd.ExecuteNonQuery()

        con1.Close()

// It will perform the query of inserting new record into the table.