Wednesday, 31 December 2014

Audio recording in Windows Phone 8 and playing using Media Element

Audio recording in Windows Phone 8 and playing using Media Element

In my present project had required audio recording for windows phone 8 . I was happy to find many samples and examples in google.

But the main problem was I have to store this audio to my DataBase in binary format.I had a ready WCF service to post the data to Database. I was able to get the buffer but the buffer was not in the format to play in media element.

It was very tough task to convert the byte array to .wav format in windows phone 8 . Because the problem was headers missing in the byte array to convert it to valid .wav format.

But it was not able to play . But after many search i found out the audio library for windows phone 8 in codeplex i.e., Coding4Fun.

A beautiful library for getting custom controls in windows phone 8.

Here , I found out that it has audio recorder and returns the data in byte array format of .wav Atlast I find out the required dll.

Shall we start a sample application

  1. Create application ->select windows phone 8 Template - > Sample-Audio

2. Add user control name it as FinalRecorder.xaml (Shows my frustration)

3. Add buttons to Record,Play,Stop,Clear (as per your requirement)

4. Add Media element to play the audio.

 <MediaElement x:Name="MediaElementPlayAudio" MediaEnded="MediaElementPlayAudio_MediaEnded" MediaFailed="MediaElementPlayAudio_MediaFailed"


5. Onclick of Record
  _recorder.Start(); - microphone is activated and started to record.

6. Onclick of Stop
_recorder.Stop(); - microphone is stopped and de-activated .
And Creating audio stream to store the recorded buffer into IsolatedStorageFileStream

7. on click of Play
setting source of media element the audio stream.

Please find the sample application here 

" Happy New Year " Let's Welcome 2015 by thanking 2014 for the beautiful experiences to be in touch with this Blog. Thanks for all the viewers. 

-----------------------------------------Happy Coding -------------------------------------

Tuesday, 16 December 2014

PDF creation using Sharp-PDF C#

Simple example for creating PDF file using Sharp-PDF


I came across a new library for developing PDF in C# named as SharpPDF . It is open source .net dll . Find the URL here .

You will find many tutorials on the net. But, I thought of sharing what I know (not completely).

Hoping for ?

A generic class to create pdf with different generic objects and mail it as attachment.



Lets get on

There are many objects that is supported by SharpPDF . Below are just a glimpse of objects supported in SharpPDF and used here in the post are
  • Text Object
  • Image Object
  • Table Object

The main class is pdfDocument for preparing document.

Here we can add text or background image(Logo) using PdfDocument document .

PdfTable is the table object as specified above . Where , we use maximum of these objects
in PDF generation.

I have created a class PDFGenerate which has some properties included . And there is a Method CreatePDF with generic List (List<T> ) as input.

It will create PDF and save to the folder PDF in application.

Please find the guide related to the sharp pdf in below mentioned URL

If there are any changes required and any guidance are accepted happily.

Friday, 28 November 2014

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

Hi check out my new blog post here on retrieving roster from openfire server in

Roster in XMPP

Roster are the contacts of  user (contact list).

Roster Handlers in AgsXmpp

Let us discuss, the handlers other than the mentioned in part -1 i.e., (loggedin, loginfailed) are mentioned below

·         OnRosterItem

·         OnRosterEnd

·         OnRosterStart

Let us recap part -1 ( ) login part (we need here that code snippet for initializing the above mentioned handlers)

AgsXMPP.XmppClientConnection objXmpp = new agsXMPP.XmppClientConnection ();

Jid jid = new Jid ("xyz@server name"); //ex: –abc is server name

objXmpp.Server = jid.Server;

objXmpp.Username = jid.User;

objXmpp.Password = ******; //your password of account.

objXmpp.AutoResolveConnectServer = true;



 objXmpp.OnLogin += loggedIn; // loggedIn is handler for successful login to server.

 objXmpp.OnAuthError += loginFailed;

objXmpp. OnRosterStart+= new ObjectHandler(objXmpp_OnRosterStart);

objXmpp.OnRosterItem+=new AgsXMPP.XmppClientConnection.RosterHandler(objXmpp_OnRosterItem);

objXmpp. OnRosterEnd+= new ObjectHandler(objXmpp _OnRosterEnd);

objXmpp.Open ();


Catch (exception ex)

{ }

OnRosterStart handler is shown below

 private  void objXmpp_OnRosterStart(object sender)



Onrosterstart handler is executed after the login is successful,  implies initiate any method or variable (ex. DataTable or Generic list to store the contacts ) to handle the Roster List item which is next event.

The OnRosterItem handler is shown below

private void objXmpp_OnRosterItem(object sender, RosterItem rosterItem)



    // rosterItem.Subscription


In the above mentioned handler, we can read every roster information (contact list) after successful OnRosterStart .

We can get below mentioned properties from RosterItem

·         Subscription (SubscriptionType enum )

·         JId

SubscriptionType is an enum with values

·         None – (not yet subscribed)

·         To – (sender subscribed waiting for your approval)

·         From – (receiver not accepted your subscription)

·         Both – (Both receiver and sender accepted the request)

In this event, you can bind the contacts to the required type as explained in onrosterstart.

Add New Roster
We can add new roster to the contacts list by using RosterManager in OnRoserItem

private void addNewRoster(Jid contactJid)


    objXmpp.RosterManager.AddRosterItem(contactJid); // Add new

    objXmpp.RosterManager.UpdateRosterItem(contactJid, "nickname"); //update

    objXmpp.RosterManager.RemoveRosterItem(contactJid); // remove


Approve Subscription
We can approve subscription according to the above mentioned subscription type

private void subcribeRoster(Jid contactJid)




OnRosterEnd handler is shown below

private void objXmpp_OnRosterEnd(object sender)


This handler assures that all Roster all delivered.

(Note: - We cannot use any controls in these handlers to display or update values. Since, these handlers are asynchronous.)

In Part 1 we discussed about Login and Login failed handler.

In Part 2 we discussed about Roster Handlers

And , In Part 3 we shall discuss about sending and Receiving Messages using AgsXmpp.

Firsted posted on

Please, do post feedback.

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 .
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 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

     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: – is server for  google.mail
       objXmpp.Server = jid.Server;
       objXmpp.Username = jid.User;
objXmpp.Password = ******; //your password of account.
objXmpp.AutoResolveConnectServer = true;
 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


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. 


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" />

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

function ShowSendingProgress() {
  var modal = $('<div  />');
    modal.attr("id", "modalSending");
    var loading = $("#modalSending.loading");;
    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() {
    var loading = $(".loading");

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.
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.
1.   Create Procedure Usp_GetCountry
@Name Varchar(50)
Select * from dbo.TblCountry where Name like ‘%’+@Name+’%’
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)
      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;
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.