Monday, 5 May 2014

Using XMPP and Openfire server in ASP.NET C# - Part -1

Extensible Messaging and Presence Protocol (XMPP)

The Extensible Messaging and Presence Protocol (XMPP) is a protocol for streaming XML elements in order to exchange messages and presence information.
The XMPP Core uses main features like
  • XML Streams
  • TLS
  • SASL
  • <message/>, <presence/>, and <iq/> children of the stream root

The basic functionality expected of XMPP is instant messaging (IM) and presence application.

Important requirement are
  •  Exchange messages with other users
  •  Exchange presence information with other users
  •  Manage subscriptions to and from other users
  •  Manage items in a contact list (in XMPP this is called a "roster")
  •  Block communications to or from specific other users

There are many providers who had built in libraries as mentioned in XMPP Standard foundation check link http://xmpp.org/xmpp-software/libraries/ .
The example below described is based on the agsXMPP SDK developed in managed C# dedicated to .NET and Mono technologies. Since, it is dual licensed (GPL) free DLL developed by ag-software.net and they also provide support for issues.
Before moving onto example there is important requirement to implement chat i.e., Chat server installation. I am using Openfire server to fulfill the requirement. For installation follow the link http://www.igniterealtime.org/projects/openfire/documentation.jsp

     Important particulars for this implementation is
  •  JID – Jabber Id, a unique id in the openfire server for each user.
  • Roster- User’s contact is roster.

      How to login to the server?

        Add the following code after successful login from your application.
       
        AgsXMPP.XmppClientConnection objXmpp = new agsXMPP.XmppClientConnection();
        Jid jid = new Jid ("xyz@server name"); //ex: xyz@gmail.com – gmail.com is server for  google.mail
       objXmpp.Server = jid.Server;
       objXmpp.Username = jid.User;
objXmpp.Password = ******; //your password of account.
objXmpp.AutoResolveConnectServer = true;
Try
{
 objXmpp.OnLogin += loggedIn; // loggedIn is handler for successful login to server.
 objXmpp.OnAuthError += loginFailed;
 objXmpp.Open ();
}
Catch (exception ex)
{

}

The loggedin handler is shown below

Private void loggedIn (object o)
{

//lblStatus.Text = "Logged in and Active.";

}

The login failed handler is shown below

Private void loginFailed (object o, agsXMPP.Xml.Dom.Element el)
{

//lblStatus.Text = "Invalid credentials.”

}

When the loggedin handler executes it assures you that user credentials are valid and logged in.

Part 1 we discussed only on the Login part using AgsXmpp.dll.

In next part i.e., Part 2 we shall discuss upon Recieving roster list of the user using AgsXmpp.









Wednesday, 18 December 2013

Example of showing loader using jquery and closing from codebehind

Introduction 

Loader are frequently used in web-application or website. The example here shows the enabling of loader image from Jquery and closing the loader image with overlay from code-behind. 

Background 

Generally, Web developers will be using Loader image when there is some event occurred or precisely, whenever the event takes more time to execute the code we use this loader image to buy some time from the user.

Using the code 

The HTML part of the code design is 

<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" 
            onclick="ButtonSubmit_Click" /> 

In this example, on Button_click the loader image displays. 


 <div class="loading" align="center" id="modalSending">
    <img src="images/loader.gif" width="200px" />
</div> 

The mentioned div contains the loader image which displays image with overlay.


function ShowSendingProgress() {
  var modal = $('<div  />');
    modal.addClass("modal");
    modal.attr("id", "modalSending");
    $('body').append(modal);
    var loading = $("#modalSending.loading");
    loading.show();
    var top = '215px';
    var left = '560px';
    loading.css({ top: top, left: left, color: '#ffffff' });
    
} 

The above mentioned script appends the image to the body with the mentioned position. 


function StopProgress() {
 
    $("div.modal").hide();
 
    var loading = $(".loading");
    loading.hide();
} 

The above mentioned script removes the image from the body. 


System.Threading.Thread.Sleep(3000);//moving system to sleep to enable loader
ScriptManager.RegisterStartupScript(this, this.GetType(), "stop loader", 
   "StopProgress();alert('loader removed from code-behind');", true); 

In the code-behind, on button click I have added code to remove the loader on completion of the code execution.   

Using inside ajax update-panel

 This can be used inside updatepanel but need little modification in Button Click i.e. instead of calling through jquery onclick function add the function ShowSendingProgress() onclientclick because, once the page dom is created the ajax update-panel updates only the required panel. 


 <asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" OnClientClick="javascript:return ShowSendingProgress();" /> 

First Published in CodeProject - link here



Friday, 6 December 2013

SQL injection attack and prevention using stored procedure

What is SQL Injection Attack?

SQL Injection is one of the many web attack mechanisms (hacking technique) used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques.
Improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

How does SQL Database get attacked or Main Reason for SQL Injection Attack?

SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.
In general, the inline query written in the project or application is the main cause of the SQL Injection Attack.
Ex: select count (*) from [user] where usn = ’”+ txtUserName.Text +”’ and
      pwd = ’”+ txtUserPassword.Text +”’
The above mentioned query is to check (verify credentials) whether username and password matches what user entered? Generally,     used in login forms.
There are number of SQL injection techniques available and they differ from attacker to attacker; however, the functionality or malfunctioning they exploit is the same. They find out the vulnerability in SQL queries using the web URL or the error messages               generated.
Often developers use dynamic SQL statements made up of strings that are concatenated or query parameters directly specified along with input keywords.
Example
1.    Select * from MyLoginAccounts where loginname='xyz' and  loginID='123' and permission='admin'
In the above mentioned query, he/she tries to manipulate the query using sql commands this leads to SQL Injection Attack.
2.    Select * from MyLoginAccounts where loginname='arpit' or '1'='1' -- and loginID='123'
       and  permission='admin'
By passing one more parameter such as "or '1'='1'" which is always true, the user tries to capture all the records from the system. Also, to restrict the other condition to be executed from the system, attacker uses '--' to make the keywords following it look like a comment statement.
By this, attacker can login and access the confidential information from other user’s right.

Types of attacks

1.   First Order Attack :
In this attack, he/she add a sub query or a union statement to the existing SQL query to buy information illegally. Here it executes only the intended part of the query.
2.   Second Order Attack :
Here, the attacker tries to get control of persistent storage systems i.e., Attacker tries to create or delete the information, tables and even login accounts. Which can further be used to carry out dangerous attacks like retrieving the database schema.

How to avoid SQL Injection attacks

  • Developers should expose a database only via a API. And user privileges should be carefully made so that the client has no direct access to tables and views.
  • Execute privileges should be granted only to users who are authorized to perform DDL and DML operations.
  • Appropriately choose the privileges or rights such as AUTHID CURRENT_USER and AUTHID DEFINER.
  • Limit user inputs, like restrict users to specified web pages using the restricted language for input, not specifying VARCHAR        parameter when the parameter will be used as a number, and using int instead of number if you need only positive integers.
  • Developers should use SQL statement text which are compile-time-fixed.
  • All the input values should be validated before putting them under code to perform database transactions.
  • Use of Stored Procedures (in right way) reduces risk of SQL Injection Attack.   

How to avoid SQL Injection attacks using Stored Procedures
Some database programmers believe that by using stored procedures, their code are safe from SQL injection Attacks.
That is not true because, if dynamic query is used inside the stored procedures and the dynamic query is constructed by concatenating the parameters it is at high risk of attack.
The easiest way to prevent SQL injection from happening, is to use parameters and sp_executesql to execute the dynamically generated statement.
Example
1.   Create Procedure Usp_GetCountry
@Name Varchar(50)
AS
Begin
Select * from dbo.TblCountry where Name like ‘%’+@Name+’%’
End
If @Name contains any malicious string then the attacker can gain the access. For example query, look below. If input parameter from C# is
2.   India’; EXEC sp_MSforeachtable @command1 = "DROP TABLE ?" --
The above mentioned statement deletes all the tables present in the DataBase. After the “--“ (double hyphen) the sql treats all the written query as comments.
Correct method is, as mentioned before, is to use parameters and sp_executesql. The second argument of sp_executesql should be set to the name and type of the parameters to expect in string form.
Format is shown below
1.   Create Procedure Usp_GetCountry
@Name Varchar(50)
AS
Begin
DECLARE @sqlcmd NVARCHAR(MAX);
      DECLARE @params NVARCHAR(MAX);
      SET @sqlcmd = N'SELECT * FROM dbo.TblCountry WHERE Name = @Name';
      SET @params = N'@Name NVARCHAR(50)';
      EXECUTE sp_executesql @sqlcmd, @params, @Name;
      End
There are other methods, few are mentioned below which can be used to prevent SQL Injection Attack
  • Using parameterized query.
  • Using ORM tools (LINQ, LINQ to Entities)
  • Using regular expression to discard input string.
  • Encrypt sensitive data.

Wednesday, 20 November 2013

Example Of JavaScript Serializer And Json String Using WebMethod

Introduction


The tip helps in calling the server side method from client side using jquery, creating a json string in web method and displaying in the front end with the required interval.

Background  


I have used basic Jquery in my projects. In my present project, I got an idea of appending the values from server side to front end but without post-back and in certain interval of time. This is just an example, it can be changed as per the requirement.

Html part  


The example consists of a div which will be appended by the string receiving from the web method.

 <div id="Display">
 </div>

The Jquery code is shown below:



 function getajax(i) {
                $.ajax({
                    type: "POST",
                    url: "default.aspx/createjson",
                    data: "{'i':'" + i + "'}",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        var jsonostr = data.d;
                        var jsonobj = eval('(' + jsonostr + ')');
                        for (i in jsonobj) {
                            $("#Display").append
                            ("<span>City Id - " + jsonobj[i]["id"] + 
                            "</span>&nbsp;<span>City Name - " + 
                            jsonobj[i]["name"] + "</span><br/>");

                        }

                    },
                    error: function () {  inter = 1; }
                });

            }


This function get the data row of index passed to the code behind (Web Method) "i" is the index here and appends the row to the div with id="Display".

To get the data row at same intervals of time, I have used the set Interval function of the JavaScript. The code is shown below:


var inter = 1;
            setInterval(function () {
                getajax(inter);
                inter = inter + 1;
            }, 1000); 


Code Behind



1. I have used an XML to load the data to the DataTable. When the certain interval expires, the web method returns the 1st row from the DataTable and returns successive rows for the next same intervals .


 the Web method is used to fetch the XML data to data table, get selected row or passed index row and returns it in the form of generic-list to the client-side using JavaScriptSerializer to serialize the generic list.



[WebMethod]
    public static string createjson(string i)
    {
        DataSet cityds = new DataSet();
        cityds.ReadXml(HttpContext.Current.Server.MapPath("~/xml/cities.xml"));
        DataTable citydt = cityds.Tables[0];

        citydt = citydt.Rows.Cast<DataRow>().Skip(int.Parse(i) - 1).Take(1).CopyToDataTable();


        // citydt.AsEnumerable().Take(int.Parse(i));
        JavaScriptSerializer cityjson = new JavaScriptSerializer();
        List<loadvals> cityjsonlst = new List<loadvals>();
        loadvals cityrow;
        foreach (DataRow citydr in citydt.Rows)
        {
            cityrow = new loadvals();
            cityrow.id = citydr["id"].ToString();
            cityrow.name = citydr["name"].ToString();

            cityjsonlst.Add(cityrow);
        }
        return cityjson.Serialize(cityjsonlst);
    } 


2. A temporary class is declared to store the data in the form of the required format. The code is shown below:

private class loadvals
    {
        public string id { get; set; }
        public string name { get; set; }
    }

3.And don't forget to add the namespace System.Web.Script.Serialization;


I hope this will be helpful for the beginner.

First published in codeproject.com on 18-oct-2013 - view here
Download example here

By Nandakishorerao
Trainee software engineer In Canarys automation Pvt Ltd.
Bangalore

Example of gridview rowcommand on Button Click

Introduction


One of the most used controls in my projects is Gridview. Therefore, I thought of writing a tip which has been used in my projects frequently.  

Background  


Gridview displays the value of a data source in a table. Here, I am going to give an example of using an event called "RowCommand". The RowCommand is raised when a buttonLinkButton or ImageButton is clicked in the Gridview Control.

Html part 

 

In the HTML part , I have binded the values which have to be displayed on the page.
And in the code behind, I have used an XML to load the data to the gridview. When the button is clicked, the event verifies for the command name and command argument.
And, then, I have just alerted the name of the user in this example. Changes can be made according to the requirement.

<asp:GridView ID="gridMembersList" AutoGenerateColumns="False" GridLines="None" 
  runat="server" onrowcommand="gridMembersList_RowCommand">
        <Columns>
        <asp:TemplateField HeaderText="User Name">
        <ItemTemplate>
            <asp:Literal ID="ltrlName" runat="server" Text='<%# Eval("Name") %>'></asp:Literal>
            <asp:Literal ID="ltrlSlno" runat="server" Visible="False" Text='<%# Eval("Id") %>'></asp:Literal>
        </ItemTemplate>
        </asp:TemplateField>
        
        <asp:TemplateField HeaderText="View More">
        <ItemTemplate>
            <asp:Button ID="btnViewmore" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" CommandName="More" runat="server" Text="View More" /></ItemTemplate>
 </asp:TemplateField> </Columns></asp:GridView>  


Code Behind


1. Populating the gridview in Page_Load event from xml file "Member Details"

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string pathofxml = Server.MapPath("xml/MemberDetails.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(pathofxml);
            gridMembersList.DataSource = ds;
            gridMembersList.DataBind();
        }
    }


2. In the code behind of the GridView_RowCommand event is  fetching the name of the member and alerting the name of the clicked row. 

protected void gridMembersList_RowCommand(object sender, GridViewCommandEventArgs e)
   {
        if (e.CommandName == "More")
        {
            int index = Convert.ToInt32(e.CommandArgument.ToString());
            Literal ltrlslno = (Literal)gridMembersList.Rows[index].FindControl("ltrlSlno");
            Literal ltrlName = (Literal)gridMembersList.Rows[index].FindControl("ltrlName");
            ScriptManager.RegisterStartupScript(this, this.GetType(), 
            "Message", "alert('" + ltrlName.Text+ "');", true);
        }
    } 



First published in codeproject.com on 30-march-2013 - view here
Download example here

By Nandakishorerao
Trainee software engineer In Canarys automation Pvt Ltd.
Bangalore