add

Thursday, 26 September 2013

Write and read text to/from a text file in asp.net

 string path = Server.MapPath("~/");
            TextWriter tw = new StreamWriter(path+"Textsample.txt",true);
            // write a line of text to the file
            tw.WriteLine(txtresult.Text);

            // close the stream
            tw.Close();
       txtfieldname.Text = "";
       txtvalue.Text = "";
       txtresult.Text = "";
       StreamReader tr = new StreamReader(path + "Textsample.txt");
       //TextReader tr = new TextReader(path + "Textsample.txt");
       // read a line of text
       //Console.WriteLine(tr.ReadLine());
       var lineCount = File.ReadAllLines(path + "Textsample.txt").Length;
       //Response.Write(lineCount);
       for (int i = 0; i < lineCount; i++)
       {
           txtresult.Text += tr.ReadLine();
       }
       // close the stream
       tr.Close();

Thursday, 12 September 2013

multiple deletes using checkbox in asp.net

 string strID = string.Empty;

        for (int i = 0; i < gvproviders.Rows.Count; i++)
        {
            CheckBox chkDelete = (CheckBox)gvproviders.Rows[i].
                             Cells[0].FindControl("chkname");
            if (chkDelete != null)
            {
                if (chkDelete.Checked)
                {

                    Label lbldeleteid = (Label)gvproviders.Rows[i].Cells[1].FindControl("controlid");
                    if (strID != string.Empty)
                        strID += ",";
                    strID += "" + lbldeleteid.Text + "";
                    //strID  = lbldeleteid.Text;
                    //idCollection.Add(strID);
                }
            }
        }
        string s1 = "delete from tblname where PId in(" + strID + ")";
       
        con.db1.Open();
        OleDbCommand cmd = new OleDbCommand(s1, con.db1);
       
        int j = Convert.ToInt32(cmd.ExecuteNonQuery());
        con.db1.Close();

remove a session variable in asp.net

Session.Remove("sessionvariablename");

save image in a folder in asp.net and validate image

Bitmap image1;
           
            image1 = new Bitmap(fupload1.PostedFile.InputStream);

            int x = image1.Width;
            int y = image1.Height;

            string[] exe = new string[3] {".jpg",".png",".gif" };


           
            if (i < 2000)
            {
                for (int k = 0; k < exe.Length;k++)
                {
                    if (lblextension.Text == exe[k])
                    {
                        if (x <= 1024 && y <= 768)
                        {
                            filename = Path.GetFileName(fupload1.PostedFile.FileName);
                             fname=j + extension;
                            fupload1.SaveAs(Server.MapPath("Files/" +fname ));
                            break;
                        }
                    }
                 
                }
            }

Find utl path in asp.net c#

Request.Url.GetLeftPart(UriPartial.Authority) +
     VirtualPathUtility.ToAbsolute("~/");

Monday, 26 August 2013

Redirect to Another Page in Asp.net using jQuery

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<input type="button" id="btnclick" value="Redirect" />
<script type="text/javascript">
    $(function () {
        $("#btnclick").click(function () {
            var url = 'http://www.aspdotnet-suresh.com';
            $(location).attr('href', url);
        })
    });
</script>
</body>

Add blinking effect to text in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add blinking effect to text in jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        blinkeffect('#txtblnk');
    })
    function blinkeffect(selector) {
        $(selector).fadeOut('slow', function () {
            $(this).fadeIn('slow', function () {
                blinkeffect(this);
            });
        });
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="txtblnk"> <p><strong><font color="red">Welcome to Aspodtnet-Suresh.com</font></strong></p> </div>
</form>
</body>
</html>

Disable Cut, Copy and Paste Options in textbox using jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Disable Cut, Copy and Paste Options in textbox using jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        $('#txtName').bind("cut copy paste", function (e) {
            e.preventDefault();
        });
    });
   
</script>
</head>
<body>
<div>
<input type="text" id="txtName" />
</div>
</body>
</html>

Getting All Databases from a Server in Sql Server

Query:

select name from sys.databases

Friday, 23 August 2013

Redirect User to Another Web page in jQuery






<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<input type="button" id="btnclick" value="Redirect" />
<script type="text/javascript">
    $(function () {
        $("#btnclick").click(function () {
            var url = 'http://www.aspdotnet-suresh.com';
            $(location).attr('href', url);
        })
    });
</script>
</body>
</html>

Get List of Tables in SqlServer

Introduction:

Here I will exaplain simple SQL Query to get all tables,procedure names in database or how to get list of all table names in sqlserver database or how to get list of all procedures in sql server database.

Query for retreving tables names in sqlserver :

USE Databasename

select * from sys.tables




Query for retreving stored procedures names in sqlserver :


USE Databasename

select * from sys.procedures

Save Data into Database using jQuery json in asp.net

.aspx page:



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
         $('#btnSubmit').click(function () {
             $.ajax({
                 type: 'POST',
                 contentType: "application/json; charset=utf-8",
                 url: 'insertDataThroughJsonjQuery.aspx/InsertMethod',
                 data: "{'Name':'" + document.getElementById('txtuname').value + "', 'Pwd':'" + document.getElementById('txtpwd').value + "','Email':'" + document.getElementById('txtemail').value + "'}",
                 async: false,
                 success: function (response) {
                     $('#txtuname').val('');
                     $('#txtpwd').val('');
                     $('#txtemail').val('');
                     $('#lblmsg').val('Inserted Sucessfully');
//                     alert("Record Has been Saved in Database");
                 },
                 error: function ()
                 { console.log('there is some error'); }
             });
         });
     });    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table width="100%">
    <tr>
    <td></td>
    <td></td>
    </tr>
     <tr>
    <td>
    User Name :
    </td>
    <td>
    <asp:TextBox ID="txtuname" runat="server"></asp:TextBox>
    </td>
    </tr>
     <tr>
    <td>
    Password :
    </td>
    <td>
     <asp:TextBox ID="txtpwd" runat="server"></asp:TextBox>
    </td>
    </tr>
     <tr>
    <td>
    Email :
    </td>
    <td>
     <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
    </td>
    </tr>
     <tr>
    <td>
    <asp:Label ID="lblmsg" runat="server"></asp:Label>
    </td>
    <td>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </td>
    </tr>
     <tr>
    <td></td>
    <td></td>
    </tr>
    </table>
    </div>
    </form>
</body>

</html>



.aspx.cs page

 [WebMethod]
    public static string InsertMethod(string Name, string Pwd, string Email)
    {
        SqlConnection con = new SqlConnection("connection string");
        string s = "insert Query";
        SqlCommand cmd = new SqlCommand(s, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
            return "True";

       
    }

Wednesday, 21 August 2013

jQuey json Dataset

.aspx Page Code:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    table.gridtable
    {
        font-family: verdana,arial,sans-serif;
        font-size: 11px;
        color: #333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }
    table.gridtable th
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }
    table.gridtable td
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }
</style>
    <script src="jQuery/jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
    // calling jquery functions once document is ready
    $(document).ready(function () {
        // retreving data on button click
        $("#btnLoad").click(LoadDataThroughAjaxCall);
        //loading screen functionality - this part is additional - start
        $("#divTable").ajaxStart(OnAjaxStart);
        $("#divTable").ajaxError(OnAjaxError);
        $("#divTable").ajaxSuccess(OnAjaxSuccess);
        $("#divTable").ajaxStop(OnAjaxStop);
        $("#divTable").ajaxComplete(OnAjaxComplete);
        //loading screen functionality - this part is additional - end
    });
    // ajax call
    function LoadDataThroughAjaxCall() {
        $.ajax({
            type: "POST",
            url: "JqueryJsonDataSet.aspx/GetShipDetails",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: OnFailure,
            error: OnError
        });
        // this avoids page refresh on button click
        return false;
    }
    // on sucess get the xml
    function OnSuccess(response) {
        //debugger;
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Table");
        showOnATable(customers);
    }
    // show data on a table
    function showOnATable(customers) {
        //debugger;
        var headers = [];
        var rows = [];
        // header section
        headers.push("<tr>");
        headers.push("<td><b>   ApperField Names</b></td>");
        headers.push("<td><b> ApperField Names</b></td>");
        headers.push("<td><b> ApperField Names</b></td>");
        headers.push("<td><b> ApperField Names</b></td>");
        headers.push("</tr>");
        // rows section
        $.each(customers, function () {
            var customer = $(this);
            rows.push("<tr>");
            rows.push("<td>" + $(this).find(" databaseField Names").text() + "</td>");
            rows.push("<td>" + $(this).find(" databaseField Names").text() + "</td>");
            rows.push("<td>" + $(this).find(" databaseField Names").text() + "</td>");
            rows.push("<td>" + $(this).find(" databaseField Names").text() + "</td>");
            rows.push("</tr>");
        });
        var top = "<table class='gridtable'>";
        var bottom = "</table>";
        var table = top + headers.join("") + rows.join("") + bottom;
        $("#divTable").empty();
        $("#divTable").html(table);
    }
    // loading screen functionality functions - this part is additional - start
    function OnAjaxStart() {
        //debugger;
        //alert('Starting...');
        $("#divLoading").css("display", "block");
    }
    function OnFailure(response) {
        //debugger;
        alert('Failure!!!' + '<br/>' + response.reponseText);
    }
    function OnError(response) {
        //debugger;
        var errorText = response.responseText;
        alert('Error!!!' + '\n\n' + errorText);
    }
    function OnAjaxError() {
        //debugger;
        alert('Error!!!');
    }
    function OnAjaxSuccess() {
        //debugger;
        //alert('Sucess!!!');
        $("#divLoading").css("display", "none");
    }
    function OnAjaxStop() {
        //debugger;
        //alert('Stop!!!');
        $("#divLoading").css("display", "none");
    }
    function OnAjaxComplete() {
        //debugger;
        //alert('Completed!!!');
        $("#divLoading").css("display", "none");
    }
    // loading screen functionality functions - this part is additional - end
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnLoad" runat="server" Text="Load Data" />
    </div>
    <br />
    <div id="divTable">
    </div>
    <%--Loading screen section - start--%>
    <div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
        text-align: left;">
        <span>
            <img src='Images/Loading.jpg' alt="Image not found." /></span>
        <br />
        <span style="text-align: left; padding-left: 8px;">Loading ...</span>
    </div>
    <%--Loading screen section - end--%>
    </form>
</body>

</html>


.cs Page Code:

First and foe most thing is add the following dll's to page


[System.Web.Services.WebMethod]
        public static string GetShipDetails()
        {
            string query = "select query";
            SqlCommand cmd = new SqlCommand(query);
            return GetData(cmd).GetXml();
        }
        private static DataSet GetData(SqlCommand cmd)
        {
            string connString = "connectionstring";
            using (SqlConnection con = new SqlConnection(connString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds;
                    }
                }
            }

        }

Monday, 12 August 2013

Binding the data into Gridview in asp.net C#


 private void getdata()
    {
        string _SelectedValues = string.Empty;
        string s = "select query'";
        SqlDataAdapter da = new SqlDataAdapter(s, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        grdstore.DataSource = ds;
        grdstore.DataBind();
        if (grdstore.Rows.Count > 0)
        {
            for (int p = 0; p < grdstore.Rows.Count; p++)
            {
                CheckBox chkselect = (CheckBox)grdstore.Rows[p].Cells[0].FindControl("chkboxlst");
                chkselect.Checked = true;
          
                //chkselect.CheckedChanged += new EventHandler(chkboxlst_CheckedChanged);
                for (int i = 0; i < grdstore.Rows.Count; i++)
                {
                    CheckBox chkbox = (CheckBox)grdstore.Rows[i].Cells[0].FindControl("chkboxlst");
                    if (chkbox.Checked)
                    {
                        Label lblid = (Label)grdstore.Rows[i].Cells[1].FindControl("lbl");
                        if (_SelectedValues != string.Empty)
                            _SelectedValues += ",";
                        _SelectedValues += "" + lblid.Text + "";

                    }
                }

            }

apply Gridview Column alignment to Right


Fist of all we are loading the data into griview you can write the following code in gridview Row DataBound event

 protected void grdstore_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            gvctrl.Columns[3].ItemStyle.HorizontalAlign = HorizontalAlign.Right;
            //gvctrl.Columns[2].ItemStyle.HorizontalAlign = HorizontalAlign.Right;
            gvctrl.Columns[4].ItemStyle.HorizontalAlign = HorizontalAlign.Right;
            //gvctrl.Columns[2].ItemStyle.Width = 150;
        }
    }

Monday, 29 July 2013

Delete Multiple Records From Gridview and also asking Permission to whether the record is delete or not

First Add this script to header tag on .aspx page:

  <script type="text/javascript" language="javascript">
        function DeleteConfirmation() {
            if (confirm("Are you sure, you want to delete selected records ?") == true)
                return true;
            else
                return false;
        }
    </script>


and call this function on button like this:

OnClientClick="return DeleteConfirmation()"

First Get the records from database attache to gridview

write the following code on button click event:

 string strID = string.Empty;

        for (int i = 0; i < gvsample.Rows.Count; i++)
        {
            CheckBox chkDelete = (CheckBox)gvsample.Rows[i].
                             Cells[0].FindControl("chkSelect");
            if (chkDelete != null)
            {
                if (chkDelete.Checked)
                {

                    Label lbldeleteid = (Label)gvsample.Rows[i].Cells[1].FindControl("lblid");
                    if (strID != string.Empty)
                        strID += ",";
                    strID += "" + lbldeleteid.Text + "";
                    //strID  = lbldeleteid.Text;
                    //idCollection.Add(strID);
                }
            }
        }
        string s1 = "delete from store where id in("+strID+")";
        //sb += sb.AppendFormat("{0}='{1}'; ", s1, item);
        con.Open();
        SqlCommand cmd = new SqlCommand(s1, con);
        //cmd.ExecuteNonQuery();
        int j = Convert.ToInt32(cmd.ExecuteNonQuery());
        con.Close();
        if (j > 0)
        {
            lblsample.Text = j+"Record(s) Deleted Sucessfully";
        }
        else
        {
        }
        getdata();

Sending E-Mail With Attachment

 MailMessage mail = new MailMessage();
         mail.To.Add("To mail id");
     
        mail.From = new MailAddress("From mail id");
        mail.Subject = "mail";
        mail.Body = "find the attached file";
        mail.IsBodyHtml = true;

      //Attach file using FileUpload Control and put the file in memory stream

        mail.Attachments.Add(new Attachment("Attached document file path"));
     
      SmtpClient smtp = new SmtpClient();
       smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
       smtp.Credentials = new System.Net.NetworkCredential
           ("u r email id", "password");
       //Or your Smtp Email ID and Password
       smtp.EnableSsl = true;
       smtp.Send(mail);

Tuesday, 23 July 2013

check only one checkbox among multiple check boxes in gridview

add the below script in your html head section

<script type="text/javascript">
        function CheckOne(obj) {
            var grid = obj.parentNode.parentNode.parentNode;
            var inputs = grid.getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == "checkbox") {
                    if (obj.checked && inputs[i] != obj && inputs[i].checked) {
                        inputs[i].checked = false;
                    }
                }
            }
        }
    </script>


call the above function in your checkbox like:

 <asp:CheckBox ID="chkinner" runat="server" AutoPostBack="true" onclick="CheckOne(this);"
                                                                                OnCheckedChanged="chkinner_CheckedChanged" />

display gmap on a asp.net page

First Download Gmap.dll file add it to solution

Add the following page directive:

<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>


and then add the following code which position you display the gmap

 <cc1:GMap ID="GMap1" runat="server" Height="365px" Width="700px" />

u can edit height and width