Tuesday, September 18, 2012

Developing Widgets with ASP.NET

 

In this article i will illustrate how to create simple widget and use that widget in a web page. 

Widget:

Widgets are the small piece of code that can be embedded in any web page. Google Ads is common example for widgets that we see every day. These ads are produced by placing small piece of code( widget) in a webpage.

We can create our own widgets and make available to others or use the widgets created by others in our web pages. Widget is like a normal web page only. So it has its own post backs , click events etc. So be careful while embedding widgets in your webpage.

Here is the code for creating sample calculator widget which just calculates the sum of two numbers and outputs the result

Creating a Widget using C#.net (Sample Calculator Widget)

Aspx Code:

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

<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblWidget" runat="server" Text="Sample Calculator Widget" ForeColor="Red"></asp:Label>
<br />
<br />
<asp:textbox ID="txtNum1" runat="server"></asp:textbox>
<br />
+
<br />
<asp:textbox ID="txtNum2" runat="server"></asp:textbox>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<br />
<asp:textbox ID="txtResult" runat="server" Enabled="false"></asp:textbox>

</div>
</form>
</body>
</html>



Code Behind:

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

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

}
protected void btnAdd_Click(object sender, EventArgs e)
{
txtResult.Text = ( Int32.Parse(txtNum1.Text) + Int32.Parse(txtNum2.Text)).ToString();
}
}



Output:

Widget1

How to use Widgets in a Web Page:

Iframe is used to embed widgets in our web page .

Widget can be present in our local server or in the remote sever.

Specify the absolute path of widget in the “src” attribute of Iframe.

Sample code for using widget in web page :

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

<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblWidget" runat="server" Text="Using Sample Calculator Widget in my web page"
ForeColor="#3366FF"></asp:Label>
<br />
<br />
<iframe id="frm1" runat="server" src="CreateaCalculatorWidget.aspx"></iframe>
</div>
</form>
</body>
</html>




Output:


widget2

Example of ModalpopupExtender – Ajax Control

 

In this article I will illustrate how to create a ModalpopupExtender.

Its Use: ModalpopupExtender is an Ajax Control. It is used to pop up a panel. Whatever the controls you want to see in your ModalPopupExtender add it to a panel and assign this Panel Id to “TargetControlID” attribute of ModalpopupExtender.

Important attributes of this control are :

TargetControlID – to which we need to assign a Id of the Control (like button or hyperlink)

PopupControlID – assign Id of the panel to be shown in the pop up.

OkControlId – Id of Ok / Submit button control.

CancelControlId – Id of Cancel button

OnOkScript – add some java script functionality for click of Ok button

OnCancelScript - add some java script functionality for click of Cancel button.

So to use it we need to either register Ajax Control ToolKit or add namespace in Web.Config file. For adding Ajax Control Toolkit to the project or solution , check my earlier article :

http://sailajareddy-technical.blogspot.in/2012/09/how-to-install-aspnet-ajax-control.  

Aspx Code:

 <form id="form1" runat="server">
<asp:ScriptManager ID="Sc1" runat="server"></asp:ScriptManager>
SAMPLE CODE TO ILLUSTRATE MODELPOPUPEXTENDER OF AJAX CONTROL TOOLKIT
<br />
<br />
<asp:Button ID="btnShow" runat="server" Text="Show Modal Popup" />
<br />
<br />
Text Entered in Modalpopup:
<asp:TextBox ID="txtShow" runat="server"></asp:TextBox>
<asp:Panel ID="Pn1" runat="server">
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
<asp:Button ID="btnCancel" Text ="Cancel" runat="server" />
</asp:Panel>

<ajaxToolkit:ModalPopupExtender
ID="PopUp1" runat="server"
TargetControlID="btnShow"
PopupControlID="Pn1"
CancelControlID="btnCancel">
</ajaxToolkit:ModalPopupExtender>
</form>



Code Behind:

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

public partial class Forum_Topics_ModelpopupExtender_Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtShow.Text = txtData.Text;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
txtShow.Text = txtData.Text;
}
}

Monday, September 17, 2012

Sample Code to insert form data into Excel using C#.net

In this article I will illustrate how to insert form data into Excel using OleDBConnection.

For example , we need to capture Product Information through a form and insert this data into Excel ,
where Product Information consists of ItemCode , ItemName and Price.

Design:

Open new project and create three textboxes to capture  ItemCode , ItemName and Price information.
Add a save button to form . Onclick of this button data will be inserted into Excel.
Next time when user enters another record , it will be appended to the data in the excel sheet.

Here is the sample code to insert data into Excel using C#.net

Note:
     Create an Excel file at the location mentioned  i.e "C:/Users/Sony/Desktop/test.xlsx"
and name the columns as ItemCode, ItemName , Price.


string con = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Sony/Desktop/test.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES'";


Aspx Code:


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

<!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>Saving form data to excel</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
        <td colspan="2" style="color: #FF0000">
             <asp:Label ID="lblMsg" runat="server"></asp:Label>        
        </td>
    </tr>
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr>
        <td>
             ENTER ITEM CODE:
        </td>
        <td>
        <asp:textbox ID="txtItemCode" runat="server"></asp:textbox>    
        </td>
    </tr>
     <tr>
        <td>
             ENTER ITEM NAME:
        </td>
        <td>
        <asp:textbox ID="txtItemName" runat="server"></asp:textbox>
        </td>
    </tr>
    <tr>
        <td>
             ENTER PRICE:
        </td>
        <td>
        <asp:textbox ID="txtPrice" runat="server"></asp:textbox>    
        </td>
    </tr>
   <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save to Excel" OnClick="btnSave_Click" />        
        </td>
   </tr>
    </table>
           
        
        <br />

    </div>
    </form>
</body>
</html>

Code behind(.cs file)


using System;
using System.Collections;
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.OleDb;

public partial class Forum_Topics_EditSaveLinksinGridView : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        lblMsg.Text = "";
   }
    protected DataTable MakeDataTable()
    {
        DataTable Dt = new DataTable();
        Dt.Columns.Add("ItemCode", typeof(string));
        Dt.Columns.Add("ItemName", typeof(string));
        Dt.Columns.Add("Price", typeof(string));
        return Dt;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string con = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Sony/Desktop/test.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES'";
        OleDbConnection obj = new OleDbConnection(con);
        obj.Open();
        OleDbCommand cmd = new OleDbCommand("Insert into [Sheet1$](ItemCode , ItemName , Price) values('" + txtItemCode.Text + "','" + txtItemName.Text + "','" + txtPrice.Text + "')", obj);
        cmd.ExecuteNonQuery();
        lblMsg.Text = "RECORD IS INSERTED SUCCESSFULLY!!";
        txtItemCode.Text = txtItemName.Text = txtPrice.Text = string.Empty;
        obj.Close();
    }
}

Saturday, September 15, 2012

ENCRPT AND DECRYPT STORED PROCEDURES IN SQLSERVER 2008



To encrypt a stored procedure in sql server 2008 , use with encryption while


creating it.
if stored procedure is already created , then use it with alter statement.

Here is an example to create an encrypted stored procedure:

CREATE PROCEDURE SP_WITH_ENCRYPTION
WITH ENCRYPTION
AS
BEGIN
SELECT 'HI..THIS STORED PROCEDURE IS ENCRYPTED'
END
GO



Any user , even the user with administrative privileges can not view the text

of this procedure now. It is locked.

To decrypt a stored procedure or any other object, we have to use third party

tools.

One of such third party tool is "OPTILLECT" SQL Decryptor tool.

This tool can be downloaded from this url
http://download.cnet.com/Optillect-SQL-Decryptor/3000-10254_4-75300271.html

Using this tool, one can view the text of the encryted stored procedure or

download/save the script of that procedure at some location on to the disc.

This tool simply connects with the sql server and looks like sql server

management studio.

 one has to login with " sa" password (administrator account) to decrypt the

procedures.

PASSING TABLE VALUED PARAMETER TO STORED PROCEDURE OR FUNCTION - SQL SERVER 2008


Table value parameters are not available in the earlier versions of sql server.
This is the new feature introduced in sql server 2008.

Advantages:
1) we can reduce no of lines of code 
2)Reduce parameter list that we send to stored procedure or function. 
3)It is used to send multiple rows of data to stored procedure or function.

To use Table Valued Parameters in function or stored procedure , follow these steps:

1)Create  User Defined Table Type.( with table structure)
2)Declare a variable of this   User Defined Table Type .
3)Insert some rows into this Table Type
4)Pass this variable as a parameter to stored procedure or function.

Note:

1) User Defined Table Type can only be used as READONLY parameter.
2)Only select operation can be performed on it.
3)INSERT , UPDATE DELETE ,SELECT * INTO operations can not be performed.


Example : Passing Table Valued Parameter to a function

/* CREATE USER DEFINED TABLE TYPE */
CREATE TYPE StateMaster AS TABLE
(
StateCode VARCHAR(2),
StateDescp VARCHAR(250)
)
GO


/*CREATE  FUNCTION WHICH TAKES TABLE AS A PARAMETER  */
CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
DECLARE @StateDescp VARCHAR(250)
SELECT @StateDescp = StateDescp FROM @TmpTable
RETURN @StateDescp
END
GO


BEGIN

/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* INVOKE FUNCTION */
SELECT elekha.TableValuedParameterExample(@MyTable)
GO



Example : Passing Table Valued Parameter to Stored Procedure

/*CREATE  STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER  */
CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
INSERT INTO StateMst 
SELECT * FROM @TmpTable
END
GO


BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

Friday, September 14, 2012

WPF Application to convert text to speech



In this article I would like to discuss how to convert text to speech using WPF Application.

 Open Visual Studio 2008 ,
 From file menu select New Project , From the templates select WPFApplication .

 By default it creates Window1.xaml , App.xaml , References and Properties folders.

 Right click on the references folder and select “Add Reference” .


















 and from .net tab select System.Speech and click on ok.

 This will add system.speech namespace to the project.

 Open window1.xaml , from toolbar drag and drop a textbox and button controls.

Double click on the button ..it will open button event handler in code behind file(window1.xaml.cs)

Speak function is in the class SpeechSynthesizer , so to use that class add the following in your cs file.

 "using System.Speech.Synthesis;"

 In the function create obj for that class , invoke speak function as follows.

  private void button1_Click(object sender, RoutedEventArgs e)
        {
            SpeechSynthesizer obj = new SpeechSynthesizer();
            obj.Speak(Speak.Text);
        }


The output window looks like this. Type some text in the textbox and click on Speak button .





How to install ASP.net AJAX Control ToolKit

 

ASP.net AJAX Control ToolKit can be downloaded from here:

http://ajaxcontroltoolkit.codeplex.com/

To add Ajax Control Toolkit to Visual Studio follow these steps:

1)Right Click any tab in the toolbar and select “Add Tab” . This adds a new tab in the toolbar. Name it as “Ajax Toolkit Controls”

1

2)Now right click on this tab and Select “Choose Items” option. It opens “Choose Toolbox items” window. In that under “.Net Framework Components” tab browse the folder having AjxControlToolKit.dll and add the two components “Accordion and Accordion Pane” and click ok.

2

 

 3

3)This adds all the controls that are present in the library.

4)Now register the controls in your page using @Register directive and use all the controls in the library with the TagPrefix name mentioned.

 
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagPrefix="ajaxToolkit" %>
 
                                                OR
 
1) Add the following Code to Web.Config file.

 
<add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
 
And make sure “AjaxControlToolKit.dll” is in your bin folder.

NOTE :  If  we add namespace in the web.config file , it makes Ajax Controls available in all the pages.