Wednesday, 12 June 2013

JSON with single parameter:

 

Json.aspx

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

<!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>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
<script type="text/javascript">
     function Json()  {
         var number1 = 11;
        
         $.ajax({
             url: "WebService.asmx/AddTwoNumbers",
         data:"{'x': '"+ number1+"'}",
         dataType:"json",
         type:"post",
         contentType:"application/json; charset=utf-8",
         success:function (data) {
             alert(data.d);
         },
         error: function (data) {
             alert("Error");
         }
     });
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Test" onclick="Json()" />
    
    </div>
    </form>
</body>
</html>

 

 

webservice.asmx code

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

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using
    //ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string AddTwoNumbers(int x)
    {
        int y = 11;

        int sum = x + y;
        return sum.ToString();
    }
    
}

Tuesday, 11 June 2013

JSON(Javascript Object Notation) Examples:

 

Introduction

This article i will explain what is Json and how we will perform operations on data using Json. 

 

JSON: JavaScript Object Notation.

JSON is syntax for storing and exchanging text information. Much like XML.

JSON is smaller than XML, and faster and easier to parse.

JSON is lightweight text-data interchange format

JSON is language independent

JSON is "self-describing" and easy to understand


JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

Examples:

Step 1:  Open visual studio

File->New->Web site-> select ASP.NET web Application.

After selecting new ASP.NET Application Go to solution explorer.

Right click on project in solution explorer -> Add New Item. You will get Add New Item popup window in that select Web Form and give a name to  page in Name Box then click on OK.  New web page will be added to you solution explorer.

                  Again right on Project –> Add New Item –> Select web service –> name it as JSON –> OK .  web service class add to your project.

 

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

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    
}

 

 

Note:  Uncomment

[System.Web.Script.Services.ScriptService]

 

Uncomment.bmp

 

Uncomment the above line. If That NameSpace did not exists add that above class name.

I will give 3 Examples with out using parameters , single parameters, and multiple parameters

 

1  With out using parameters.

In this example web method do not have parameters.  So no need to pass any parameters.

web methods must have.

This method called by JSON and display integer.

web method attribute at above web method, as like below.

[WebMethod]

web service class.

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    
    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
    [WebMethod]
    public int DisplayNumber()
    {
        int x = 10;
        return x;
    }
  }

JSON.aspx page Syntax

To run Query add below script in header section of web page.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
  </script>

 

Or download Jquery file and add that file to your project.

 

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

<!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>Json</title>
<%-- <script src="Jquery.js" type="text/javascript"></script>--%>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
  </script>
   
    <script type="text/jscript" >

        function Json() {
           
            var str = "srinu";

            $.ajax({
                url: 'WebService.asmx/DisplayNumber',
                data: '{}',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.d);
                },
                error: function (data) {

                    alert("Error");
                }
            });    // end $.ajax
        }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" onclick="Json()" value="button" />
    
    </div>
    </form>
</body>
</html>

Note: 

Be careful with single quotes ‘ ’  and double quotes “  ”  They must be nested. if you made any mistakes web method will not be called by this function.

And try to use HTML controls.

In above Code Snippet

URL: It is Url of web method which is going to be calling.

Data:  It is pass parameters to web method. In this Example we are not passing any parameters so data part is empty.

Run This example you will  get following output:

 

OUT PUT:

10.

 

 

 

Sunday, 7 April 2013

How to Insert table data through Gridview

Step 1: Create a table:
Create a table test
(
sno int not null identity(1,1),
sfname NvarChar(50),
slname NvarChar(50)
)
SnoFirstNameLastName
1Srinivas AmruthaMunagala
2SreenishIndian

Step 2:
GridViewExample.aspx
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" Width="800px" HorizontalAlign="Center"  
ShowFooter="true" HeaderStyle-BackColor="#8FBC8F" ID="gd"  
AutoGenerateColumns="false" OnRowCommand="inserte"   OnRowCancelingEdit="cancle"
 OnRowDeleting="delete" OnRowUpdating="update" OnRowEditing="edit" >
    <Columns>

    <asp:TemplateField>
    <EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"  
ImageUrl="~/images/imagesupdate.jpeg" ToolTip="Update" Height="20px"  
Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"  
ImageUrl="~/images/imagescancel.jpeg" ToolTip="Cancel" Height="20px"  
Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"  
ImageUrl="~/images/imagesedit.jpeg" ToolTip="Edit" Height="20px"  
Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit"  
runat="server" ImageUrl="~/images/imagesdelete.jpeg" ToolTip="Delete"
Height="20px" Width="20px" />
</ItemTemplate>

<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/images/images.jpeg"  
CommandName="insert" Width="30px" Height="30px" ToolTip="Add new User"
ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S NO"  >
    <ItemTemplate>
    <asp:Label runat="server" ID="lblsno" Text='<%#Eval("sno") %>' ></asp:Label>
    </ItemTemplate>


    </asp:TemplateField>
    <asp:TemplateField HeaderText="First Name" >
    <ItemTemplate>
    <asp:Label runat="server" ID="lblfname" Text='<%#Eval("sfname") %>' >
</asp:Label>
    </ItemTemplate>
    <EditItemTemplate>


    <asp:TextBox runat="server" ID="txtfname" Text='<%#Eval("sfname") %>'  >
</asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>

      <asp:TextBox runat="server" ID="txtftr" ></asp:TextBox>
      <asp:RequiredFieldValidator ID="rfvdesignatdfgion" runat="server"  
ControlToValidate="txtftr" Text="*" ValidationGroup="validaiton"/>

    </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Last Name" >
    <ItemTemplate>
    <asp:Label runat="server" ID="lbllastname" Text='<%#Eval("slname") %>' >
</asp:Label>
    </ItemTemplate>
    <EditItemTemplate >
    <asp:TextBox runat="server" ID="txtlastname" Text='<%#Eval("slname") %>' >
</asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
     <asp:TextBox runat="server" ID="txtinlastname"   ></asp:TextBox>
     <asp:RequiredFieldValidator ID="rfvdesignation" runat="server"  
ControlToValidate="txtinlastname" Text="*" ValidationGroup="validaiton"/>

    </FooterTemplate>
    </asp:TemplateField>

    </Columns>

    </asp:GridView>
    </div>
    </form>
</body>

Step 3:
GridViewExample.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=DOTNET19;Initial 
Catalog=srinivas;User ID=sa;Password=admin123");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            filldata();
        }
   
    }
    protected void filldata()
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from test",con);
        DataSet dt = new DataSet();
        da.Fill(dt);
        gd.DataSource = dt;
        gd.DataBind();
        con.Close();
    }
    protected void cancle(object sender, GridViewCancelEditEventArgs e)

    {
        e.Cancel = true;
        gd.EditIndex = -1;
        filldata();
    }
    protected void edit(object sender, GridViewEditEventArgs e)
    {
        gd.EditIndex = e.NewEditIndex;
        filldata();
   
    }
    protected void update(object sender, GridViewUpdateEventArgs e)
    {
        con.Open();
        GridViewRow row = gd.Rows[e.RowIndex];
        Label lblid = (Label)row.FindControl("lblsno");
        int id = Convert.ToInt32(lblid.Text);
        TextBox txtbfname = (TextBox)row.FindControl("txtfname");
        TextBox txtblname = (TextBox)row.FindControl("txtlastname");
        string fname = txtbfname.Text.ToString();
        string lname = txtblname.Text.ToString();
        update(id, fname, lname);
    }
    public void update(int id, string fname, string lastname)
    {

        SqlCommand cmm = new SqlCommand("update test set sfname='" + fname + "',
 slname='" + lastname + "' where sno="+ id +"", con);
        cmm.ExecuteNonQuery();
        con.Close();
        gd.EditIndex = -1;
        filldata();


    }
    protected void delete(object sender, GridViewDeleteEventArgs e)
    {
   
        Label lblid1 = (Label)gd.Rows[e.RowIndex].FindControl("lblsno");
        int id1 = Convert.ToInt32(lblid1.Text);
        con.Open();
        SqlCommand cmm = new SqlCommand("delete from test where sno=" + id1 +
"", con);
        cmm.ExecuteNonQuery();
        con.Close();
        filldata();
    }
    protected void inserte(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "insert")
        {
            TextBox txtfname = (TextBox)gd.FooterRow.FindControl("txtftr");
            TextBox txtlname = (TextBox)gd.FooterRow.FindControl("txtinlastname");
            con.Open();
            SqlCommand cmm = new SqlCommand("insert into test values('" +
txtfname.Text + "', '" + txtlname.Text + "')", con);
            cmm.ExecuteNonQuery();
            con.Close();
            filldata();


        }
    }
}

Monday, 18 March 2013

Definations For DML,DCL,DDL.TCL

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.
Examples: SELECT, UPDATE, INSERT statements

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.
Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.
Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.
Examples: COMMIT, ROLLBACK statements

Sunday, 17 March 2013

How To Generate Password Automatically

 In This article i will show how to generate password automatically:
 Step 1:
.ASPX
<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <br />
    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True"
        Font-Names="Arial"></asp:Label>
</div>
    </form>
</body>
</html>

.CS
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Design;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Label1.Text = CreateRandomPassword(8);
    }
    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }
   
}

Now View On browser:

Friday, 15 March 2013

Print Square Between Stars

Print Square Between The Stars:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 12, i, j;
            for (i = 1; i <= n; i++)
            {
                for (j = n; j >=i ; j--)
                {
                    Console.Write("*");
                }
                for (int k = 1; k <=i-1; k++)
                {
                    Console.Write("  "); //Two Sapces.
                }
                    for (j = n; j >= i; j--)
                    {
                        Console.Write("*");
                    }
                Console.WriteLine();
            }
            for (i = 1; i <= n; i++)
            {
                for (j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }
                for (int k = n-1; k >=i; k--)
                {
                    Console.Write("  "); // Two Spaces
                }
                for (j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.ReadLine();

        }
    }
}

Sunday, 3 March 2013

How to change user role using asp.net


For this you have to fallow below steps

Step 1:
 Make one “XML File “ which contains role types. In this i took one xml file and named it as
“chengerole.xml”.
<?xml version="1.0" encoding="utf-8" ?>
<changerole>
  <roles>
    <role>admin</role>
  </roles>
  <roles>
    <role>accountent</role>
  </roles>
  <roles>
    <role>teacher</role>
  </roles>
  <roles>
    <role>student</role>
  </roles>
  <roles>
    <role>parent</role>
  </roles>
  
</changerole>


Step 2:

Create a table as
create table userstable
(
UserName  nvarchar(50) not null,
Roletype nvarchar(50) not null
)

This table values will be added while the user registration: for understanding add some values to

this table

User NameRole
srinu.munagala33@gmail.comadmin
krishnareddy4b8@gmail.comaccountent
srinu33aryan@gmail.comteacher


Step 3:

Create one stored Procedure as
CREATE PROCEDURE rolechange 
@username nvarChar(50),
@role nvarChar(50)
    AS
    update usertable set Roletype=@role where UserName=@username

Step 4:
set the sqlconnection in webconfig file.

<connectionStrings>
    <add name="mycon" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=
|DataDirectory|\SchoolManagementSystemdatabase.mdf;Integrated 
Security=True;
User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>


Step 5:
 Create one aspx file as below

<h3>Chenge Role</h3>
    <br />
    <asp:Table runat="server" ID="tblchangerole" BorderStyle="Solid"  
Height="200px"
 Width="300px" BorderColor="Black" BorderWidth="1px" HorizontalAlign="Center" >
    <asp:TableRow runat="server" ID="row1">
    <asp:TableCell>
    UserName:
    </asp:TableCell>
    <asp:TableCell>
    <asp:DropDownList ID="DropDownList1" runat="server" Width="160px"  
AutoPostBack="true" >
    </asp:DropDownList>
    </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow runat="server" ID="row2">
    <asp:TableCell>
    Change Role:
    </asp:TableCell>
    <asp:TableCell>
    <asp:DropDownList runat="server" ID="drdprolechange" Width="160px" 
 AutoPostBack
 ="true">
    </asp:DropDownList>
    </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow runat="server" ID="row3">
    
    <asp:TableCell>
    
    </asp:TableCell>
    <asp:TableCell>
    <asp:Button ID="Button1" runat="server" Text="Change Role"  OnClick=
"Button1_Click"/>
    
    </asp:TableCell>
    </asp:TableRow>
    </asp:Table>
    
   
    
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    
Step 6:
Code Behind 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.Configuration;
using System.Xml;

namespace SchoolManagementSystem.Admin
{
    public partial class changerole : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            intiatepage();
            
            usernamebind();
            Bindrolestodropdownlist();
            Page.Header.Title = "Changerole";
            if (!IsPostBack)
            {

                if (Session["adminALoginId"] == null)
                {

                    Response.Redirect(@"~\Admin\Adminlogin.aspx");
                }

                else
                {

                    Response.ClearHeaders();

 Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, 
must-revalidate");



                }

            }
            
        }

        public void intiatepage()
        {
            
        }

        public void Bindrolestodropdownlist()
        {
            if (!IsPostBack)
            {
                XmlReader xmrd = XmlReader.Create(Server.MapPath(@"~\chengerole.
xml"));
                DataSet dt = new DataSet();
                dt.ReadXml(xmrd);
                xmrd.Close();
                drdprolechange.DataValueField = "role";
                drdprolechange.DataTextField = "role";
                drdprolechange.DataSource = dt;
                drdprolechange.DataBind();


            }

        }

        public void usernamebind()
        {
            if (!IsPostBack)
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["mycon"].ConnectionString);
                con.Open();
                SqlCommand cmm = new SqlCommand("select * from usertable", con);
                SqlDataAdapter adp = new SqlDataAdapter(cmm);
                DataSet dt = new DataSet();
                adp.Fill(dt);
                DropDownList1.DataTextField = dt.Tables[0].Columns["UserName"].
ToString();
                DropDownList1.DataValueField = dt.Tables[0].Columns["UserName"].
ToString();

                DropDownList1.DataSource = dt.Tables[0];
                
                
                DropDownList1.DataBind();
                con.Close();
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn = new SqlConnection(ConfigurationManager.
ConnectionStrings["mycon"].ConnectionString);
            cnn.Open();
            SqlCommand cmm = new SqlCommand("rolechange", cnn);
            cmm.CommandType = CommandType.StoredProcedure;
            cmm.Parameters.Add("@username", SqlDbType.NVarChar).Value = 
DropDownList1.SelectedValue.ToString();
            cmm.Parameters.Add("@role", SqlDbType.NVarChar).Value = 
drdprolechange.SelectedValue.ToString();
            cmm.ExecuteNonQuery();
            Label1.Text = "sucessfull";
            cnn.Close();
        }

       

    }
}