Popular Posts

Friday, 25 July 2014

CALL WEB-SERVICE THROUGH JQUERY AND AJAX IN ASP.NET

CALL WEB-SERVICE THROUGH J QUERY AND AJAX IN ASP.NET





STEP 1:
First while creating the web services you need to uncomment the below tag in web service.

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]


STEP 2:

Include the scriptManager tag from AJAX EXTENSIONS:

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="~/Service.asmx" />      //the path to your web services
    </Services>
    </asp:ScriptManager>
   


STEP3:

create a simple html button control which will call the javascipt .


Here one textbox is also added that will call the PARAMETERIZED WEB SERICES WEB METHOD FROM JAVASCRIPT ...THAT WILL BE EXECUTED FROM BUTTON CLICK..


   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="button" onclick="storeinfo();" />
    

STEP 4:  THE JAVASCRIPT:

    <script type="text/javascript">
        function storeinfo() {
            debugger;
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
            function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    
    </script>




EXPLANATION:

    function storeinfo() {
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
    

a)The function storeinfo is called on the button click.
b)the value from textbox is recieved .
c)the Service class is used to call the WEB METHOD
Here in case mine web method is GetStoreData.
d)its has 4 parameters:
pass:  the password accuried from textbox(i.e the webmethod needs one parameter)
storeinfoSuccessCallback : function that is called on sucess on execution
storeinfoFailCallback: function that is called on error of execution
true: user context

A SIMPLE IMPLEMENTATION OF SUCCES AND ERROR FUNCTIONS:

function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    

THE COMPLETE CODE:


<%@ 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>Calling webservice via javascript and ajax</title>
    <script type="text/javascript">
        function storeinfo() {
            debugger;
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
            function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="~/Service.asmx" />      
    </Services>
    </asp:ScriptManager>
    <div>
    enter password: 
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="button" onclick="storeinfo();" />
    </div>
    </form>
</body>
</html>


AND THAT's IT...........

ENJOY...

Wednesday, 23 July 2014

GET DATA FROM SQLITE AND MYSQL DATABASES

GET DATA FROM SQLITE AND MYSQL DATABASE



Today we will see how to get data from sqlite database and mysql database .

1. DATA FROM SQLITE DATABASE.

To connect sqlite to asp.net we need to download the dll, you can down load the updated dll from the 
web site of sqlite :  http://www.sqlite.org/download.html

OR
Finisar.SQLite
- An ADO.NET Data Provider for SQLite

OR




Put the dll in your bin folder.

NOTE*: check the version of your sqlite and your framework you are using as well as the 32bit or 64 bit dll you need to download as per your application and database.


THE CODE BEHIND PAGE: 
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 Finisar.SQLite;
using System.Data.SQLite;
   using MySql.Data.MySqlClient;

public partial class _Default : System.Web.UI.Page
{
 public static string GetConnectionString()
{
  string connStr = String.Format("server={0};user id={1}; password={2};" + 
    "database=TESTDB; pooling=false", "localhost",
    "root", "youdbpassword");

  return connStr;
}
    protected void Page_Load(object sender, EventArgs e)
    {
        //connection to sqlite database

        System.Data.SQLite.SQLiteConnection cn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/sqlite/testdb.db;Version=3;New=False;Compress=True;"); 
        try
        {

                      cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("select * from emp", cn);
            DataTable dt = new DataTable();
            SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
           
        }
        catch
        {

            //display any exeptions  

        }
        finally
        {
            cn.Close();
        }  
  

    }
}





2.CONNECT TO MYSQL DATABASE:


Download the mysql from oracle site :

Install as the complete type and you will have the connector/dll required to connect to the asp.net .Or else you need to download the connector from the same above site seperate.

the connector location will be :
C:\Program Files (x86)\MySQL\Connector NET 6.8.3\Assemblies\v4.0
in your PC.

INCLUDE THE mysql.data.dll in your application and rest is done...............


            //connection to mysql database
            MySql.Data.MySqlClient.MySqlConnection mycon =
            new MySqlConnection(GetConnectionString());

            if (mycon.State != ConnectionState.Open)
                try
                {
                    mycon.Open();
                    MySqlCommand cmdmysql = new MySqlCommand("select * from empsql", mycon);
                    MySqlDataAdapter damysql = new MySqlDataAdapter(cmdmysql);
                    DataTable dtmysql = new DataTable();
                    damysql.Fill(dtmysql);
                    GridView2.DataSource = dtmysql;
                    GridView2.DataBind();

                }
                catch (MySqlException ex)
                {
                    throw (ex);
                }




Monday, 21 July 2014

Dynamic Masterpage or Adding master page at run time

DYNAMICALLY ADDING MASTER PAGES.


Conditions occurs when we have several master page and need to add on certains pahes at specific conditions.like for some user some master page and others.

so how to add master page at run time.....WHO IS THERE???

..................................................PAGE_INIT Method to rescue................................................................


The Design Page:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="TetsmasterPage.aspx.cs" Inherits="TetsmasterPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        This page loads the ,master page dynamically everytime pages loads among three 
        maser page availables....</p>
</asp:Content>




this is the sample TestMasterPage.aspx where we will add different master pages according to some conditionssss.
here i have taken a random number and adds new master page at every random number.



THREE MASTER PAGES ARE CREATED ......

site.master  :  the default master page in asp.net web application
MasterPage.master  :  Say masterpage for user and clients
MasterPage2.master : say master page for adminsitrator and testing




THE CODE BEHIND FILE:

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

public partial class TetsmasterPage : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Random r = new Random();
        int i =r.Next(3);
        if (i == 0)
        {
            Page.MasterPageFile = "~/MasterPage.master";
        }
        else if (i == 1)
        {

            Page.MasterPageFile = "~/MasterPage2.master";
        }
        else
        {
            Page.MasterPageFile = "~/Site.master";

        
        }
    }    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}



And THAT ALL.......


so put your logic in Pre_Init method and import the conserned master page in the aspx file.







Sunday, 20 July 2014

simple captcha in asp.net

SIMPLE OWNED CAPTCHA TO FOREPLAY BOTS...........



Here is the code for adding a simple captcha in your aspx code rather than using any third party.
use ur imagination and create your own.


THE ASPX PAGE:


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   
    <p>
        CAPTCHA :</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> + <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> =
        <asp:TextBox ID="TextBox1" runat="server" Width="40px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </p>
   
</asp:Content>




Here we have added two lables and one text box to display the number (random ) and to get the result from the user respectively..


THE CODE BEHIND PAGE:


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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Random _r = new Random();
            int n = _r.Next(10);
            Label1.Text = "0";
            Label2.Text = n.ToString();
        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        int result = Convert.ToInt32(TextBox1.Text            );
        int cal=Convert.ToInt32(Label1.Text)+Convert.ToInt32(Label2.Text);
        if (result.Equals(cal))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('CORRECT CAPTCHA LOGIN SUCCESSFULL!!')", true);

        }
        else
        {

            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('INCORRECT TRY AGAIN')", true);

        }

    }
}


AND ITS DONE ..





Friday, 11 July 2014

HOW TO UPDATE LARGE TABLES IN FASTEST WAY....... IN SQL SERVER

FASTEST WAY TO UPDATE ROWS IN A LARGE TABLES IN SQL SERVER




The key concept here will be to improve the performance of an update operation by updating the tables in smallest manner.

For E.G:

consider a table called test with contains more than 5 millions records rows. Let us also assume what we need to update,,,say there are over 3  millions rows in that column that has a negative number so we need to update all the rows (i.e upto 3 millions) containing the negative numbers to positive numbers .


NOW normal query will be(not recommended):

update test set columnname=0 where columnanme<0;


THAT IS ROWCOUNT TO RESCUE>>>>>>>>>>>>>>>>>>>


set rowcount 10000

update test set columnname=0 where columnanme<0;

while @@rowcount>0

BEGIN
set rowcount 10000

update test set columnname=0 where columnanme<0;



//
I.E
it will updates 10000 row at a time and then loop continues till @@rowcount>0.
this will ensure that table will not locked and updation is done smoothly in less time.

DELETE DUPLICATE DATA FROM SQL SERVER CONTAINING NO PRIMARY /PRIMARY KEY.

HOW TO DELETE DUPLICATE VALUES FROM SQL TABLE


Their are severals ways this can be achieved .below are the discussed two ways:


Table structure:
username varchar2
password varchar2


--using CTE COMMON TABLE EXPRESSION and row_number function


WITH CTE AS(
   SELECT username, Password,
       RN = ROW_NUMBER()OVER(PARTITION BY username ORDER BY username)
   FROM dbo.users
)
DELETE FROM CTE WHERE RN > 1







--using auto id column


ALTER TABLE dbo.users ADD AUTOID INT IDENTITY(1,1)

select username,count(username) as counts from users group by username
having count(username)>1


delete from users where AUTOID  not in (select min(AUTOID) from users group by username)


Thus simply done..

Wednesday, 26 February 2014

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT


DESIGN PAGE:


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

<!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 id="Head1" runat="server">
    <title></title>
    <style type="text/css">
    .fileUpload{
    width:255px;    
    font-size:11px;
    color:#000000;
    border:solid;
    border-width:1px;
    border-color:#7f9db9;    
    height:17px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
    <div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="SHOW FILES" 
            onclick="Button2_Click" />
        &nbsp;&nbsp;&nbsp;&nbsp;
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

        </div>
        <div id="download" runat="server">
        
      <p>  ALL AVAILABEL FILES :<br /></p>
      <br />
        
        </div>
    </div>
    <script language="javascript" type="text/javascript">
        function AddMoreImages() {
            if (!document.getElementById && !document.createElement)
                return false;
            var fileUploadarea = document.getElementById("fileUploadarea");
            if (!fileUploadarea)
                return false;
            var newLine = document.createElement("br");
            fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
            newFile.setAttribute("class", "fileUpload");

            if (!AddMoreImages.lastAssignedId)
                AddMoreImages.lastAssignedId = 100;
            newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
            newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
            fileUploadarea.appendChild(div);
            AddMoreImages.lastAssignedId++;
        }
   
    </script>
    </form>
</body>
</html>




Here we are adding asp control upload dynamically (up to max 6 optionally) on btnAddMoreFiles button click and call the java script  function AddMoreImages .

Button2 Is used to list all the files been upoaded successfully . 



CODE BEHIND PAGE:

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.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Threading;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
       }
  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Label1.Text = "";
            HttpFileCollection hfc = Request.Files;
            
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string type = hpf.FileName.Split(".".ToCharArray())[1].ToString();
                    if (type == "doc" || type == "docx" || type == "DOC" || type == "DOCX")
                    {
                        if (hpf.ContentLength > 0 && hpf.ContentLength < 5242880)
                        {
                            hpf.SaveAs(Server.MapPath("~/uploads/") + System.IO.Path.GetFileName(hpf.FileName));
                            Label1.Text += "<br/>file "+ hpf.FileName+" uploaded successfully...<br/>";

                        }
                        else
                        {

                            Label1.Text += "FILE of size more than 5 mb ("+hpf.FileName+") are not allowed<br />";
                        }
                    }
                    else
                    {

                        Label1.Text += "only docs file are allowed"+hpf.FileName+" NOT UPLOADED";
      
                    
                    }
                   
                }
           
               
        }
        catch (Exception)
        {
            
            throw;
        } 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/uploads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            HyperLink HL = new HyperLink();
            HL.ID = "HyperLink" + i++;
            HL.Text = fi.Name;
            HL.NavigateUrl = "Download.aspx?file=" + fi.Name;
            download.Controls.Add(HL);
            download.Controls.Add(new LiteralControl("<br/>"));
        }
    }
    }



HERE I have made a restriction that only doc files will be uploaded and of size less than 5 mb.
it depends upon you what are the conditions.
 
On button2_Click the files been uploaded are shown in hyperlink and on clicking the hyper link the file are been downloaded.


BELOW IS THE CODE FOR DOWNLOAD FILE:


using System.IO;
using System.Threading;

public partial class Download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = Request["file"].ToString();
        fileDownload(filename, Server.MapPath("~/uploads/" + filename));
    }
    private void fileDownload(string fileName, string fileUrl)
    {
        Page.Response.Clear();
        bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
        if (!success)
            Response.Write("Downloading Error!");
        Page.Response.End();

    }
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }