ASP.NET MVC, Javscript, JQuery, Angular JS, HTML 5, CSS3
Web Services, Web Api, SQL Server, C#.NET, Azure
01 June 2017
12 October 2011
XML File Reading & Writing - Simplified
Simple Example of Reading & Writing a xml file
Sample XML File:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<Id>1</Id>
<Name>Froyo</Name>
<Cost>10.50</Cost>
</Product>
<Product>
<Id>2</Id>
<Name>Gingerbread</Name>
<Cost>20.60</Cost>
</Product>
<Product>
<Id>3</Id>
<Name>Ice Cream Sandwich</Name>
<Cost>30.70</Cost>
</Product>
</Products>
C# code to create such file:
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("Products");
doc.AppendChild(root);
//ProductList can be any collection or array etc
foreach (product p1 in productList)
{
XmlElement product = doc.CreateElement("Product");
XmlElement id = doc.CreateElement("Id");
id.InnerText = p1._id.ToString();
XmlElement name = doc.CreateElement("Name");
name.InnerText = p1._name;
XmlElement validation = doc.CreateElement("Validation");
validation.InnerText = p1._validation.ToString();
product.AppendChild(id);
product.AppendChild(name);
product.AppendChild(validation);
root.AppendChild(product);
}
string xmlOutput = doc.OuterXml;
C# code to read such a file:
if (File.Exists(FilePath))
{
XmlDocument doc = new XmlDocument();
doc.Load(FilePath);
foreach (XmlNode node in doc.DocumentElement.SelectNodes("Product"))
{
int pid = Convert.ToInt32(node.SelectSingleNode("Id").InnerText);
string pname = node.SelectSingleNode("Name").InnerText;
double cost= Convert.ToDouble(node.SelectSingleNode("Cost").InnerText);
}
}
Short an simple....something to remember :)
Sample XML File:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<Id>1</Id>
<Name>Froyo</Name>
<Cost>10.50</Cost>
</Product>
<Product>
<Id>2</Id>
<Name>Gingerbread</Name>
<Cost>20.60</Cost>
</Product>
<Product>
<Id>3</Id>
<Name>Ice Cream Sandwich</Name>
<Cost>30.70</Cost>
</Product>
</Products>
C# code to create such file:
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("Products");
doc.AppendChild(root);
//ProductList can be any collection or array etc
foreach (product p1 in productList)
{
XmlElement product = doc.CreateElement("Product");
XmlElement id = doc.CreateElement("Id");
id.InnerText = p1._id.ToString();
XmlElement name = doc.CreateElement("Name");
name.InnerText = p1._name;
XmlElement validation = doc.CreateElement("Validation");
validation.InnerText = p1._validation.ToString();
product.AppendChild(id);
product.AppendChild(name);
product.AppendChild(validation);
root.AppendChild(product);
}
string xmlOutput = doc.OuterXml;
C# code to read such a file:
if (File.Exists(FilePath))
{
XmlDocument doc = new XmlDocument();
doc.Load(FilePath);
foreach (XmlNode node in doc.DocumentElement.SelectNodes("Product"))
{
int pid = Convert.ToInt32(node.SelectSingleNode("Id").InnerText);
string pname = node.SelectSingleNode("Name").InnerText;
double cost= Convert.ToDouble(node.SelectSingleNode("Cost").InnerText);
}
}
Short an simple....something to remember :)
05 June 2011
Windows App - Detecting Running Instance
Code to detect if an windows application instance is already running or not:
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
if (IsPreviousInstanceRunning)
{
MessageBox.Show("Another instance of this application is already running...", "Application already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
private static bool IsPreviousInstanceRunning
{
get
{
// get the name of our process
string proc = Process.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes = Process.GetProcessesByName(proc);
// if there is more than one process...
if (processes.Length > 1)
return true;
return false;
}
}
}
20 May 2011
16 May 2011
Dynamic Stored Procedures
Have you every felt the need to write a stored procedure that would be modified at runtime?
Well then let me show you how you can achieve this in SQL Server 2005 or upper version.
First of all let me tell you about the scenario where i had to write such a stored procedure:
Recently i was dealing with a large database (having more than 5 million records), and i had to provide the client with an option to search and filter data from a table with various search parameters in an asp.net web page.
Now few of the parameters when combined together in the where clause of the search query worked fine without much delay (mostly integer columns), but some the text columns took really long time especially when combined together in the where clause. For instance:
Query: select * from table 1 where
personame ='' or
cityid= '' or
state='' .....
In such a scenario i had to write an dynamic stored procedure which would accept parameters and form query according to the number of paramters passed.
Here is the stored procedure that i had wrote for fetching some patients information from an insurance database:
ALTER procedure [dbo].[sp_GetEligibility]
(@Insured nvarchar(50)=null,@GroupKey nvarchar(50)=null,MAX_RESULTS nvarchar(50)=null )
AS
BEGIN
if @MAX_RESULTS is null
begin
set @MAX_RESULTS=250
end
DECLARE @SQL nvarchar(MAX)
DECLARE @SQLWhere nvarchar(MAX)
set @SQLWhere = ''
set @Insured = LTRIM(RTRIM(@Insured))
set @GroupKey = LTRIM(RTRIM(@GroupKey))
if (@Insured is not null And @Insured <> '')
begin
--set @SQLWhere = @SQLWhere + ' and (I.ssn LIKE ''%' + @Insured + '%'' ) '
set @SQLWhere = @SQLWhere + ' and (I.ssn LIKE ''%'' + @Insured + ''%'' ) '
end
if (@GroupKey is not null And @GroupKey = '')
begin
set @GroupKey = null
end
Else if @GroupKey <> '0'
begin
--set @SQLWhere = @SQLWhere + ' and (E.fk_group = '+ @GroupKey + ')'
set @SQLWhere = @SQLWhere + ' and (E.fk_group = @GroupKey )'
end
IF not (@Insured is null and @GroupKey is null)
BEGIN
Select @SQL ='Select TOP(' + @MAX_RESULTS + ') * from (' +
'select TOP(' + @MAX_RESULTS + ') I.first_name,' +
'R.Relationship,' +
'I.last_name, ' +
'I.SSN,' +
'E.subscriber_id,' +
'I.first_name + '' ''+ I.last_name as Names,' +
'e.eff_date,' +
'e.term_date,' +
'G.group_name,' +
'B.benefitPlan_name, ' +
'convert(varchar,D.eff_date ,101) as dependEffDate,' +
'convert(varchar,d.Term_date ,101) as dependTermdate,' +
'I.pk_insured,' +
'(SELECT top 1 ' +
'(' +
' SELECT distinct(C.benefit_name + '', '')' +
' FROM EligibilityBenefitCodes B ' +
' left join BenefitPlanCodes C on c.pk_benefitplancodes = B.fk_benefitplancodes' +
' left join BenefitPlan BP on BP.pk_benefitplan= C.fk_benefitplan ' +
' WHERE C.pk_benefitplancodes = B.fk_benefitplancodes' +
' and B.fk_eligibility = E.pk_eligibility FOR XML PATH('''')' +
' )' +
')AS TypeofCoverage ' +
'from Eligibility E With(NOLOCK) ' +
'Inner Join Dependents D With(NOLOCK) ON e.fk_insured=D.fk_ insuredprimary ' +
'Inner Join Insured I With(NOLOCK) ON I.pk_insured=D.fk_ insuredDependent and E.fk_insured = I.pk_insured ' +
'Inner Join BenefitPlan B With(NOLOCK) ON E.fk_benefitplan=B.pk_ benefitplan ' +
'Inner Join Relation R With(NOLOCK) ON I.fk_relation=R.pk_relation ' +
'Inner Join [Group] G With(NOLOCK) ON E.fk_group = G.pk_group ' +
'where e.eff_date <= getDate() and E.IsArchived=0 ' +
@SQLWhere +
' UNION ' +
'select TOP(' + @MAX_RESULTS + ') I.first_name,R.Relationship,I. last_name, I.SSN, E.subscriber_id, ' +
'I.first_name + '' ''+ I.last_name as Names, e.eff_date, ' +
'e.term_date, G.group_name, B.benefitPlan_name, ' +
'convert(varchar,D.eff_date ,101) as dependEffDate, ' +
'convert(varchar,d.Term_date ,101) as dependTermdate, ' +
'I.pk_insured , ' +
'(SELECT top 1' +
' ( ' +
' SELECT distinct(C.benefit_name + '', '')' +
'FROM EligibilityBenefitCodes B ' +
'left join BenefitPlanCodes C on c.pk_benefitplancodes = B.fk_benefitplancodes ' +
'left join BenefitPlan BP on BP.pk_benefitplan= C.fk_benefitplan ' +
'WHERE C.pk_benefitplancodes = B.fk_benefitplancodes and B.fk_eligibility = E.pk_eligibility ' +
' FOR XML PATH('''') ' +
' )) AS BenefitCode ' +
'from Eligibility E With(NOLOCK) ' +
'Inner Join Dependents D With(NOLOCK) ON e.fk_insured=D.fk_ insuredprimary ' +
'Inner Join Insured I With(NOLOCK) ON I.pk_insured=D.fk_ insuredDependent ' +
'Inner Join BenefitPlan B With(NOLOCK) ON E.fk_benefitplan=B.pk_ benefitplan ' +
'Inner Join Relation R With(NOLOCK) ON I.fk_relation=R.pk_relation ' +
'Inner Join [Group] G With(NOLOCK) ON E.fk_group = G.pk_group ' +
'where e.eff_date <= getDate() and E.IsArchived=0 ' +
@SQLWhere +
')A ' +
' order by A.Relationship,A.first_name,A. last_name desc'
--EXEC(@SQL)
--For preventing SQL Injection use following method
EXEC sp_executesql @SQL, N'@Insured nvarchar(50),@GroupKey nvarchar(50)',@Insured,@ GroupKey
END
END
As you can see in this example, the stored procedure generates the sql query as string and at the end the parameters are passed to the generated final query.
This is pretty much similar to the if else conditions that we used to write in code behind to generate a query.
Well then let me show you how you can achieve this in SQL Server 2005 or upper version.
First of all let me tell you about the scenario where i had to write such a stored procedure:
Recently i was dealing with a large database (having more than 5 million records), and i had to provide the client with an option to search and filter data from a table with various search parameters in an asp.net web page.
Now few of the parameters when combined together in the where clause of the search query worked fine without much delay (mostly integer columns), but some the text columns took really long time especially when combined together in the where clause. For instance:
Query: select * from table 1 where
personame ='' or
cityid= '' or
state='' .....
In such a scenario i had to write an dynamic stored procedure which would accept parameters and form query according to the number of paramters passed.
Here is the stored procedure that i had wrote for fetching some patients information from an insurance database:
ALTER procedure [dbo].[sp_GetEligibility]
(@Insured nvarchar(50)=null,@GroupKey nvarchar(50)=null,MAX_RESULTS nvarchar(50)=null )
AS
BEGIN
if @MAX_RESULTS is null
begin
set @MAX_RESULTS=250
end
DECLARE @SQL nvarchar(MAX)
DECLARE @SQLWhere nvarchar(MAX)
set @SQLWhere = ''
set @Insured = LTRIM(RTRIM(@Insured))
set @GroupKey = LTRIM(RTRIM(@GroupKey))
if (@Insured is not null And @Insured <> '')
begin
--set @SQLWhere = @SQLWhere + ' and (I.ssn LIKE ''%' + @Insured + '%'' ) '
set @SQLWhere = @SQLWhere + ' and (I.ssn LIKE ''%'' + @Insured + ''%'' ) '
end
if (@GroupKey is not null And @GroupKey = '')
begin
set @GroupKey = null
end
Else if @GroupKey <> '0'
begin
--set @SQLWhere = @SQLWhere + ' and (E.fk_group = '+ @GroupKey + ')'
set @SQLWhere = @SQLWhere + ' and (E.fk_group = @GroupKey )'
end
IF not (@Insured is null and @GroupKey is null)
BEGIN
Select @SQL ='Select TOP(' + @MAX_RESULTS + ') * from (' +
'select TOP(' + @MAX_RESULTS + ') I.first_name,' +
'R.Relationship,' +
'I.last_name, ' +
'I.SSN,' +
'E.subscriber_id,' +
'I.first_name + '' ''+ I.last_name as Names,' +
'e.eff_date,' +
'e.term_date,' +
'G.group_name,' +
'B.benefitPlan_name, ' +
'convert(varchar,D.eff_date ,101) as dependEffDate,' +
'convert(varchar,d.Term_date ,101) as dependTermdate,' +
'I.pk_insured,' +
'(SELECT top 1 ' +
'(' +
' SELECT distinct(C.benefit_name + '', '')' +
' FROM EligibilityBenefitCodes B ' +
' left join BenefitPlanCodes C on c.pk_benefitplancodes = B.fk_benefitplancodes' +
' left join BenefitPlan BP on BP.pk_benefitplan= C.fk_benefitplan ' +
' WHERE C.pk_benefitplancodes = B.fk_benefitplancodes' +
' and B.fk_eligibility = E.pk_eligibility FOR XML PATH('''')' +
' )' +
')AS TypeofCoverage ' +
'from Eligibility E With(NOLOCK) ' +
'Inner Join Dependents D With(NOLOCK) ON e.fk_insured=D.fk_
'Inner Join Insured I With(NOLOCK) ON I.pk_insured=D.fk_
'Inner Join BenefitPlan B With(NOLOCK) ON E.fk_benefitplan=B.pk_
'Inner Join Relation R With(NOLOCK) ON I.fk_relation=R.pk_relation ' +
'Inner Join [Group] G With(NOLOCK) ON E.fk_group = G.pk_group ' +
'where e.eff_date <= getDate() and E.IsArchived=0 ' +
@SQLWhere +
' UNION ' +
'select TOP(' + @MAX_RESULTS + ') I.first_name,R.Relationship,I.
'I.first_name + '' ''+ I.last_name as Names, e.eff_date, ' +
'e.term_date, G.group_name, B.benefitPlan_name, ' +
'convert(varchar,D.eff_date ,101) as dependEffDate, ' +
'convert(varchar,d.Term_date ,101) as dependTermdate, ' +
'I.pk_insured , ' +
'(SELECT top 1' +
' ( ' +
' SELECT distinct(C.benefit_name + '', '')' +
'FROM EligibilityBenefitCodes B ' +
'left join BenefitPlanCodes C on c.pk_benefitplancodes = B.fk_benefitplancodes ' +
'left join BenefitPlan BP on BP.pk_benefitplan= C.fk_benefitplan ' +
'WHERE C.pk_benefitplancodes = B.fk_benefitplancodes and B.fk_eligibility = E.pk_eligibility ' +
' FOR XML PATH('''') ' +
' )) AS BenefitCode ' +
'from Eligibility E With(NOLOCK) ' +
'Inner Join Dependents D With(NOLOCK) ON e.fk_insured=D.fk_
'Inner Join Insured I With(NOLOCK) ON I.pk_insured=D.fk_
'Inner Join BenefitPlan B With(NOLOCK) ON E.fk_benefitplan=B.pk_
'Inner Join Relation R With(NOLOCK) ON I.fk_relation=R.pk_relation ' +
'Inner Join [Group] G With(NOLOCK) ON E.fk_group = G.pk_group ' +
'where e.eff_date <= getDate() and E.IsArchived=0 ' +
@SQLWhere +
')A ' +
' order by A.Relationship,A.first_name,A.
--EXEC(@SQL)
--For preventing SQL Injection use following method
EXEC sp_executesql @SQL, N'@Insured nvarchar(50),@GroupKey nvarchar(50)',@Insured,@
END
END
As you can see in this example, the stored procedure generates the sql query as string and at the end the parameters are passed to the generated final query.
This is pretty much similar to the if else conditions that we used to write in code behind to generate a query.
06 September 2010
IntelliSense & Type Safety for Session Variables
Keeping track of your Session variables in ASP.NET can become a bit cumbersome task if you end up creating many variables across a large Web Application. Sometimes you might make common mistakes like misspelling the session variable name or at times end up with incorrect data types.
I have found a very good solution for this problem which i use regularly in my ASP.NET applications. The solution is to use an "SessionHandler" class in your Application in which one creates properties to access the session variables. By this method we not only are able to access the Session variables through Visual Studio IntelliSense but also apply type safety to them.
Here is an quick example of this class:
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;
/*
*
File Name : SessionHandler.cs
Class Name: SessionHandler
Summary : This class is used to handle the session variables and keep a track of them using the
SessionHandler class object.
Advantage is that these variables are shown in VS Intellisense.
And we can also implement type safety.
*
*/
public static class SessionHandler
{
////////////////////////////// ////////////////////////////// ////////////////////////////// /
private static string _UserKey = "UserKey";
private static string _Username = "Username";
private static string _LoginType = "LoginType";
////////////////////////////// ////////////////////////////// ////////////////////////////// /
public static string UserKey
{
get
{
object obj = HttpContext.Current.Session[ SessionHandler._UserKey];
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[ SessionHandler._UserKey] = value;
}
}
////////////////////////////// ////////////////////////////// ////////////////////////////// /
public static string LoginType
{
get
{
object obj = HttpContext.Current.Session[ SessionHandler._LoginType];
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[ SessionHandler._LoginType] = value;
}
}
////////////////////////////// ////////////////////////////// ////////////////////////////// /
public static string Username
{
get
{
object obj = HttpContext.Current.Session[ SessionHandler._Username];
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[ SessionHandler._Username] = value;
}
}
}
Please Note: You need to add this class file to your AppCode folder in your Web Application.
I have found a very good solution for this problem which i use regularly in my ASP.NET applications. The solution is to use an "SessionHandler" class in your Application in which one creates properties to access the session variables. By this method we not only are able to access the Session variables through Visual Studio IntelliSense but also apply type safety to them.
Here is an quick example of this class:
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.
using System.Web.UI.HtmlControls;
/*
*
File Name : SessionHandler.cs
Class Name: SessionHandler
Summary : This class is used to handle the session variables and keep a track of them using the
SessionHandler class object.
Advantage is that these variables are shown in VS Intellisense.
And we can also implement type safety.
*
*/
public static class SessionHandler
{
//////////////////////////////
private static string _UserKey = "UserKey";
private static string _Username = "Username";
private static string _LoginType = "LoginType";
//////////////////////////////
public static string UserKey
{
get
{
object obj = HttpContext.Current.Session[
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[
}
}
//////////////////////////////
public static string LoginType
{
get
{
object obj = HttpContext.Current.Session[
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[
}
}
//////////////////////////////
public static string Username
{
get
{
object obj = HttpContext.Current.Session[
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
set
{
HttpContext.Current.Session[
}
}
}
Please Note: You need to add this class file to your AppCode folder in your Web Application.
06 June 2010
Working On Windows Application
Web to Windows Application shift was not something i was hoping for when i stared with ASP.NET.
But as it turns around i got a Good Domain "Medical Insurance" to work on, and so i readily accepted the challange.
Been busy eversince last 4 months.
Hey it does get boring at times but just look at the good things i got to learn...
1.Large database handling techniques!!
2.Really improved my SQL Server knowledge and skills.
3.Learnt a lot more about Crystal Reports and Windows Application.
4.Got to know how to communicate with clients (USA). And loving it!
5.Really learnt how to work in a shared environment, using source safe, communicating with developers across the globe, coding standards etc etc.
So all in all its a great addition to my Resume!
And now the Best Part is that we are implementing the same functionality on a Web Portal as well.
Ain't that great!!
ASP.NET here i come again!!
But as it turns around i got a Good Domain "Medical Insurance" to work on, and so i readily accepted the challange.
Been busy eversince last 4 months.
Hey it does get boring at times but just look at the good things i got to learn...
1.Large database handling techniques!!
2.Really improved my SQL Server knowledge and skills.
3.Learnt a lot more about Crystal Reports and Windows Application.
4.Got to know how to communicate with clients (USA). And loving it!
5.Really learnt how to work in a shared environment, using source safe, communicating with developers across the globe, coding standards etc etc.
So all in all its a great addition to my Resume!
And now the Best Part is that we are implementing the same functionality on a Web Portal as well.
Ain't that great!!
ASP.NET here i come again!!
01 April 2010
Web 2.0 pop-up dialog using Ajax Control Toolkit
Tired of using the old boring Windows Xp style JavaScript pop-ups to get user confirmation on a web page?
Then you have come to the right place cause i will just show you how easy it is to create a customized Vista type confirm dialog using the Ajax Control Toolkit and ASP.NET 2.0 or greater.
There's absolutely no need to know any hard core JavaScript here !!
So here are the steps:
Step 1: Install the Ajax Control Toolkit on your machine if already not done. Start your web application and add the Ajax Control Toolkit dll to your bin folder.
Step 2: Include the following the reference on your page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
Alternative if you have configured your Toolbox then simply ignore the step 1,2 and go directly to step 3.
Step 3: Now you would require to add a asp:Panel on your page that will hold the HTML required for the popup screen. ex:
<asp:Panel ID="PanelDeleteAlert" runat="server" CssClass="confirmBox"
Style="display: none;width: 300px;">
<div id="confirmHeader">
<span>Confirm</span></div>
<div id="confirmMsg" align="center">
<div class="rowdiv">
<div class="celldiv">
<img src="../images/confirm.gif" alt="" /></div>
<div class="celldiv">
<span>Delete<asp:Label ID="lblDeleteName"
runat="server" Font-Bold="true" Text="Do you want to delete this?"></asp:Label>
from contact list?</span></div>
</div>
</div>
<div id="confirmButtons">
<asp:Button ID="ButtonOk2" runat="server" Text="OK"
CssClass="button" />
<asp:Button ID="ButtonCancel2" runat="server"
Text="Cancel" CssClass="button" />
</div>
</asp:Panel>
Step 4: Now you need a LinkButton/Button on who's click you need to show the pop-up, an ConfirmButtonExtender & an ModalPopupExtenderfrom from Toolkit. Configure these as follows:
<div style="float: right">
<asp:LinkButton ID="butDelete" OnClick="butDelete_Click"
runat="server" CssClass="linktext" Text="Delete Contact"></asp:LinkButton>
<cc1:ConfirmButtonExtender ID="ConfirmButtonExtender2"
runat="server" TargetControlID="butDelete" ConfirmText="Do you want to delete this
contact?" DisplayModalPopupID="ModalPopupExtender2" Enabled="True">
</cc1:ConfirmButtonExtender>
<cc1:ModalPopupExtender ID="ModalPopupExtender2"
runat="server" TargetControlID="butDelete" PopupControlID="PanelDeleteAlert"
OkControlID="ButtonOk2" CancelControlID="ButtonCancel2" BackgroundCssClass="modalBackground" />
</div>
Step 5: You need to create proper CSS for the Panel and for the background when the Pop-up is open. You can use your imagination for designing the Panel and for the Background you can use the following CSS
/*Modal Popup*/
.modalBackground {
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}
.modalPopup {
background-color:#ffffdd;
border-width:3px;
border-style:solid;
border-color:Gray;
padding:3px;
width:250px;
}
Step 6: That's it go ahead and test your application
So as you can see using your own imagination and some good CSS techniques , you can come up with a really neat looking confirmation dialog!!
Then you have come to the right place cause i will just show you how easy it is to create a customized Vista type confirm dialog using the Ajax Control Toolkit and ASP.NET 2.0 or greater.
There's absolutely no need to know any hard core JavaScript here !!
So here are the steps:
Step 1: Install the Ajax Control Toolkit on your machine if already not done. Start your web application and add the Ajax Control Toolkit dll to your bin folder.
Step 2: Include the following the reference on your page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
Alternative if you have configured your Toolbox then simply ignore the step 1,2 and go directly to step 3.
Step 3: Now you would require to add a asp:Panel on your page that will hold the HTML required for the popup screen. ex:
<asp:Panel ID="PanelDeleteAlert" runat="server" CssClass="confirmBox"
Style="display: none;width: 300px;">
<div id="confirmHeader">
<span>Confirm</span></div>
<div id="confirmMsg" align="center">
<div class="rowdiv">
<div class="celldiv">
<img src="../images/confirm.gif" alt="" /></div>
<div class="celldiv">
<span>Delete<asp:Label ID="lblDeleteName"
runat="server" Font-Bold="true" Text="Do you want to delete this?"></asp:Label>
from contact list?</span></div>
</div>
</div>
<div id="confirmButtons">
<asp:Button ID="ButtonOk2" runat="server" Text="OK"
CssClass="button" />
<asp:Button ID="ButtonCancel2" runat="server"
Text="Cancel" CssClass="button" />
</div>
</asp:Panel>
Step 4: Now you need a LinkButton/Button on who's click you need to show the pop-up, an ConfirmButtonExtender & an ModalPopupExtenderfrom from Toolkit. Configure these as follows:
<div style="float: right">
<asp:LinkButton ID="butDelete" OnClick="butDelete_Click"
runat="server" CssClass="linktext" Text="Delete Contact"></asp:LinkButton>
<cc1:ConfirmButtonExtender ID="ConfirmButtonExtender2"
runat="server" TargetControlID="butDelete" ConfirmText="Do you want to delete this
contact?" DisplayModalPopupID="ModalPopupExtender2" Enabled="True">
</cc1:ConfirmButtonExtender>
<cc1:ModalPopupExtender ID="ModalPopupExtender2"
runat="server" TargetControlID="butDelete" PopupControlID="PanelDeleteAlert"
OkControlID="ButtonOk2" CancelControlID="ButtonCancel2" BackgroundCssClass="modalBackground" />
</div>
Step 5: You need to create proper CSS for the Panel and for the background when the Pop-up is open. You can use your imagination for designing the Panel and for the Background you can use the following CSS
/*Modal Popup*/
.modalBackground {
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}
.modalPopup {
background-color:#ffffdd;
border-width:3px;
border-style:solid;
border-color:Gray;
padding:3px;
width:250px;
}
Step 6: That's it go ahead and test your application
So as you can see using your own imagination and some good CSS techniques , you can come up with a really neat looking confirmation dialog!!
14 June 2009
Encrypt Sensitive Data in SQL Server 2005
SQL Server 2005 provides easier functions for encrypting and decrypting user sensitive information such as credit card numbers or bank account details, so as to deter any hacking attempts.
Data encryption in SQL Server 2005 can be done either by using password mechanism or by making use of keys and certificates. These methods are as follows:
1.Encryption by PassPhrase
This is a simple method in which we use the SQL method EncryptByPassPhrase('password','original_value') with our insert,update,select queries.
For an example suppose we have a table named user_info with the column named credit_card_no (varchar) in which we have to stored the encrypted credit card no then the query would be as follows:
Update user_info set credit_card_no=EncryptByPassPhrase('password',@credit_card_no);
where password is the key used to generate the encrypted value.
The same key is used to decrypt the credit_card_no as follows:
Select DecryptByPassPhrase('password',credit_card_no) as decrypted_no from user_info.
Note:The password has to be protected and remembered by the programmer. Hence can be vulnerable.
2.Encryption by Keys
The limitation of encryption by passphrase method is that we have to supply the password each time the data has to be accessed. But if we encrypt our symmetric key with a certificate then we won't have to pass the passphrase each time. To create a key or its certificate, we must first create or open the master key for the database.
The following command creates a master key:
create master key encryption by password='password';
Now we can create a certificate and then a symmetric key that is attached to that certificate. The following SQL script creates the certificate 'DemoCert' and a key 'DemoKey' associated with that certificate:
create certificate DemoCert with subject='Demo Certificate;
create symmetric key DemoKey with algorithm=AES_256 encryption by certificate DemoCert;
Now that we possess a key we can do encryption using the EncryptByKey() method and considering the previous table user_info as follows:
open symmetric key DemoKey decryption by certificate DemoCert;
update user_info set credit_card_no=EncryptByKey(Key_GUID('DemoKey'),@credit_card_no);
Similarly we can decrypt it as follows:
open symmetric key DemoKey decryption by certificate DemoCert;
select cast(DecryptByKey(credit_card_no) as varchar(16)) as decrypted_no from user_info;
This is a lenghty method but is very secure as we do not have to pass the password for the process of encryption/decryption.
So this is one advance features of SQL Server 2005 that not many of us use. But it can surely come in handy when dealing with large user database that requires some security features!!
Data encryption in SQL Server 2005 can be done either by using password mechanism or by making use of keys and certificates. These methods are as follows:
1.Encryption by PassPhrase
This is a simple method in which we use the SQL method EncryptByPassPhrase('password','original_value') with our insert,update,select queries.
For an example suppose we have a table named user_info with the column named credit_card_no (varchar) in which we have to stored the encrypted credit card no then the query would be as follows:
Update user_info set credit_card_no=EncryptByPassPhrase('password',@credit_card_no);
where password is the key used to generate the encrypted value.
The same key is used to decrypt the credit_card_no as follows:
Select DecryptByPassPhrase('password',credit_card_no) as decrypted_no from user_info.
Note:The password has to be protected and remembered by the programmer. Hence can be vulnerable.
2.Encryption by Keys
The limitation of encryption by passphrase method is that we have to supply the password each time the data has to be accessed. But if we encrypt our symmetric key with a certificate then we won't have to pass the passphrase each time. To create a key or its certificate, we must first create or open the master key for the database.
The following command creates a master key:
create master key encryption by password='password';
Now we can create a certificate and then a symmetric key that is attached to that certificate. The following SQL script creates the certificate 'DemoCert' and a key 'DemoKey' associated with that certificate:
create certificate DemoCert with subject='Demo Certificate;
create symmetric key DemoKey with algorithm=AES_256 encryption by certificate DemoCert;
Now that we possess a key we can do encryption using the EncryptByKey() method and considering the previous table user_info as follows:
open symmetric key DemoKey decryption by certificate DemoCert;
update user_info set credit_card_no=EncryptByKey(Key_GUID('DemoKey'),@credit_card_no);
Similarly we can decrypt it as follows:
open symmetric key DemoKey decryption by certificate DemoCert;
select cast(DecryptByKey(credit_card_no) as varchar(16)) as decrypted_no from user_info;
This is a lenghty method but is very secure as we do not have to pass the password for the process of encryption/decryption.
So this is one advance features of SQL Server 2005 that not many of us use. But it can surely come in handy when dealing with large user database that requires some security features!!
03 June 2009
Directory, Files Listing using GridView
Web Hosting Control Panel Type Directory Listing!!
Have you ever seen a Control Panel provided for a web hosting account? Notice the way they use, to show all the files and folders inside your sites folders? Well just in case you were wondering how to do the same using ASP.NET 2.0 then let me tell you that i have achieved the same using quiet a simple technique that i found Googling around!
The following piece of code demonstrated how by using the System.IO namespace and the ASP.NET 2.0 GridView, we can achieve the task of folder/files listing very easily........
ASPX Page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" />
Code Behind:
protected void page_load()
{
ListFolder();
}
protected void ListFolder()
{
string basepath="~/myfolder";
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(basepath));
//For All Files
FileInfo[] fileInfo = dirInfo.GetFiles("*.*",SearchOptions.AllDirectories);
//For All Subdirectories
DirectoryInfo[] subDirInfo = dirInfo.GetDirectories("*.*",AllDirectories);
GridView1.DataSource = fileInfo;
GridView1.DataBind();
GridView2.DataSource = subDirInfo;
GridView2.DataBind();
}
As you can see this method takes very little code and you can even customize it to provide delete functionality. Furthermore by combining the files and folders dataset we can achieve a complete directory listing.
Have you ever seen a Control Panel provided for a web hosting account? Notice the way they use, to show all the files and folders inside your sites folders? Well just in case you were wondering how to do the same using ASP.NET 2.0 then let me tell you that i have achieved the same using quiet a simple technique that i found Googling around!
The following piece of code demonstrated how by using the System.IO namespace and the ASP.NET 2.0 GridView, we can achieve the task of folder/files listing very easily........
ASPX Page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" />
Code Behind:
protected void page_load()
{
ListFolder();
}
protected void ListFolder()
{
string basepath="~/myfolder";
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(basepath));
//For All Files
FileInfo[] fileInfo = dirInfo.GetFiles("*.*",SearchOptions.AllDirectories);
//For All Subdirectories
DirectoryInfo[] subDirInfo = dirInfo.GetDirectories("*.*",AllDirectories);
GridView1.DataSource = fileInfo;
GridView1.DataBind();
GridView2.DataSource = subDirInfo;
GridView2.DataBind();
}
As you can see this method takes very little code and you can even customize it to provide delete functionality. Furthermore by combining the files and folders dataset we can achieve a complete directory listing.
17 May 2009
Free Shopping Cart Solutions
Free Shopping Carts - OsCommerce, Cre Loaded, Magento....
Its been days since i have return my last post. I was kept really busy by my employer. To be honest i was also a bit lazy in thinking of something new for my blog.
None of the less i spent a lot of my recent time working on free Shopping Cart Applications.
There are some really interesting points that i would like to share about these Apps.
First of all the very thing that came to my mind is that "If people are providing good free software on the internet then what will happen to us hard working Software Developers".
To back up my thoughts i would like to press the points that these free Shopping Cart solutions provide a great bit of functionality, something that would take a lot of time to build from the scratch. Also the communities are pretty active and provide further customization support.
A few of their cool features include.
1.CMS support
2.Paypal , Authorize.Net etc payment modules.
3.FedEx , UPS, UPSC etc shipping modules.
4.Multilingual Suppport.
5.Multi Store Support (Magento)
6. And off course great catalog support
The sad part for me was that the only major thing that i was doing is understanding the structure, design integration and bug solving!!
There were times when i was really scratching my brains trying to search solution to a simple problem and just couldn't find it. Yes and Magento was the one to be blamed!!!
But the fact that not may people are aware of these Free Applications (yes these people are the end clients), having knowledge of customizing them can really be very handy.
Here's a short rating of the apps based on my experience of handling them:
1.CRE Loaded - Great out of the box and easy to setup, tech support
2.Magento - Huge functionality provided but takes ages to understand and setup due to overly streched mechanism. Also functions really Slowly(and i mean really slowly compared to any PHP site)
3.Oscommerce - Base version of cre loaded. Needs lot of customization.
4.Joomla-Virtue Mart - Has the power of Joomla with it. Good for setting up small store.
Its been days since i have return my last post. I was kept really busy by my employer. To be honest i was also a bit lazy in thinking of something new for my blog.
None of the less i spent a lot of my recent time working on free Shopping Cart Applications.
There are some really interesting points that i would like to share about these Apps.
First of all the very thing that came to my mind is that "If people are providing good free software on the internet then what will happen to us hard working Software Developers".
To back up my thoughts i would like to press the points that these free Shopping Cart solutions provide a great bit of functionality, something that would take a lot of time to build from the scratch. Also the communities are pretty active and provide further customization support.
A few of their cool features include.
1.CMS support
2.Paypal , Authorize.Net etc payment modules.
3.FedEx , UPS, UPSC etc shipping modules.
4.Multilingual Suppport.
5.Multi Store Support (Magento)
6. And off course great catalog support
The sad part for me was that the only major thing that i was doing is understanding the structure, design integration and bug solving!!
There were times when i was really scratching my brains trying to search solution to a simple problem and just couldn't find it. Yes and Magento was the one to be blamed!!!
But the fact that not may people are aware of these Free Applications (yes these people are the end clients), having knowledge of customizing them can really be very handy.
Here's a short rating of the apps based on my experience of handling them:
1.CRE Loaded - Great out of the box and easy to setup, tech support
2.Magento - Huge functionality provided but takes ages to understand and setup due to overly streched mechanism. Also functions really Slowly(and i mean really slowly compared to any PHP site)
3.Oscommerce - Base version of cre loaded. Needs lot of customization.
4.Joomla-Virtue Mart - Has the power of Joomla with it. Good for setting up small store.
28 February 2009
Windows Media Service
Windows Media Services For Website
Well its been some time since i have updated my blog, i had my own reasons. Any way this is something that i was working on this month.
My main goal was to create a live audio/video broadcast over the internet and show it on my web page.
Well i searched high and low over the internet and the best possible solution that i found was the Windows Media Services!
Yes! Its very simple to setup and not much programing need. All you need is a web server(can even be your own system), the Windows Media Encoder software and a Web page with a media player that plays the audio-video stream.
You can loads of info on setting up the Windows Media Encoder on the internet.
Now the HTML required for setting up the Active X media player control on your web page is as follows:
<object ID="MediaPlayer" WIDTH="320" HEIGHT="270"
CLASSID="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" STANDBY="Loading
Windows Media Player components..." TYPE="application/x-oleobject"
CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112">
<param name="autoStart" value="True">
<param name="filename" value="http://myserver.mystream.com:1121">
<param NAME="ShowControls" VALUE="False">
<param NAME="ShowStatusBar" VALUE="False">
<embed TYPE="application/x-mplayer2" SRC="myserver.mystream.com:1121"
NAME="MediaPlayer" WIDTH="320" HEIGHT="270" autostart="1"
showcontrols="0">
</embed>
</object>
Please note that the address:" myserver.mystream.com:1121" is generated by the media encoder software based on the Web Server and the network port(1121) you select for broadcasting!
Well its been some time since i have updated my blog, i had my own reasons. Any way this is something that i was working on this month.
My main goal was to create a live audio/video broadcast over the internet and show it on my web page.
Well i searched high and low over the internet and the best possible solution that i found was the Windows Media Services!
Yes! Its very simple to setup and not much programing need. All you need is a web server(can even be your own system), the Windows Media Encoder software and a Web page with a media player that plays the audio-video stream.
You can loads of info on setting up the Windows Media Encoder on the internet.
Now the HTML required for setting up the Active X media player control on your web page is as follows:
<object ID="MediaPlayer" WIDTH="320" HEIGHT="270"
CLASSID="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" STANDBY="Loading
Windows Media Player components..." TYPE="application/x-oleobject"
CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112">
<param name="autoStart" value="True">
<param name="filename" value="http://myserver.mystream.com:1121">
<param NAME="ShowControls" VALUE="False">
<param NAME="ShowStatusBar" VALUE="False">
<embed TYPE="application/x-mplayer2" SRC="myserver.mystream.com:1121"
NAME="MediaPlayer" WIDTH="320" HEIGHT="270" autostart="1"
showcontrols="0">
</embed>
</object>
Please note that the address:" myserver.mystream.com:1121" is generated by the media encoder software based on the Web Server and the network port(1121) you select for broadcasting!
12 January 2009
Discovering Twitter
Twitter as we all know is the latest buzz word talked about over the Internet. For those who don't know Twitter is a free social networking service that allows its users to send and read other users' updates (otherwise known as tweets). You can read a hell lot about it on Wikipedia.Excited and eager to check out this new website i immediately created and account and started tweeting(Check Out here). Guess what Twitter even has big celebrities like Britney Spears and popular people like the new US President Barak Obama having their own Twitter account(i don't think they actually post there though) which were recently Hacked!!
Initially i found the idea of tweeting quiet original and unique. But as with many things it soon got boring. The fact that i had to get people to follow me in order to view their tweets and updates is just so repeating procedure. Even most of my friends didn't reply to the invitations that i sent. For many people are getting tired of Social Networking sites.
But to be honest i was quiet disappointed !
Eventually i have discovered a good use of Twitter and that's using it to promote your site/blog and following some famous, geeky, new etc etc people!
Lets see if twitter can be the next big thing on the WEB especially since it has competitions like MySpace, Facebook & Orkut.
07 January 2009
Re Thinking Blogging Strategy ??
When i started blogging, I had a mission in my mind and it was to make $ money $....some really good $ money $ using various add programs like Google Adsense. The 'weapon' of my choice for a 'Blog Topic' naturally was by default Web Development as i was already into it.
But soon after searching various blogs, articles and stuff on Google Search (and even reading them) it just struck my mind that earning money from blogging no child's play!!
You gotta think...think and think before writing a good article, play with keywords and other SEO techniques and sit on your butt! for couple more hours in day to finally just get some Internet Traffic.
And even after doing all this activity on regular basis you have to pray that people who do visit your blog also mercy fully click on the ADDS!! Well its been three months for my blog and there's hardly any revenue form it!
Well the New Years here and so I have finally decided that its about time that I Re Think my Blogging Strategy ! should i continue Blogging ? should i change my Blog Topic ? should i buy a separate web space with my very own domain ? Uh.... So confusing .....
Anyway my Blog still helps me keep important piece of software CODE that i cant really remember in a place where i can find it easily and that too for ABSOLUTELY FREE!!
That's something that still kept me going on.
Well i am no J.K. Rowling to come up with exciting stuff each time to write on blogs, so changing the topic is just out of question!
Lets see where the light takes me........................................................
But soon after searching various blogs, articles and stuff on Google Search (and even reading them) it just struck my mind that earning money from blogging no child's play!!
You gotta think...think and think before writing a good article, play with keywords and other SEO techniques and sit on your butt! for couple more hours in day to finally just get some Internet Traffic.
And even after doing all this activity on regular basis you have to pray that people who do visit your blog also mercy fully click on the ADDS!! Well its been three months for my blog and there's hardly any revenue form it!
Well the New Years here and so I have finally decided that its about time that I Re Think my Blogging Strategy ! should i continue Blogging ? should i change my Blog Topic ? should i buy a separate web space with my very own domain ? Uh.... So confusing .....
Anyway my Blog still helps me keep important piece of software CODE that i cant really remember in a place where i can find it easily and that too for ABSOLUTELY FREE!!
That's something that still kept me going on.
Well i am no J.K. Rowling to come up with exciting stuff each time to write on blogs, so changing the topic is just out of question!
Lets see where the light takes me........................................................
06 January 2009
Javascript for TextBox Restriction
JavaScript for restricting users from entering unwanted characters in a textbox/ text field.!
One of the easiest way of restricting a user from entering unwanted characters in a text field can be accomplished by using JavaScript functions as below:
<script type="text/javascript" language="javascript">
function keyRestrict(e, validchars)
{
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}
function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
</script>
After placing the above script in your head section of the web page all you need to do is call the function on the keypress event of a textbox/text field and pass in all the characters that you want to be allowed as follows:
< type="text" name="zip" id="zip" style="width:100px;" maxlength="7" onkeypress="return keyRestrict(event,'1234567890. ')" />>
Note: Please ensure that you conduct server side validations for user input, as JavaScript can be easily disabled in any browser and the above restrictions can be bypassed.
One of the easiest way of restricting a user from entering unwanted characters in a text field can be accomplished by using JavaScript functions as below:
<script type="text/javascript" language="javascript">
function keyRestrict(e, validchars)
{
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}
function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
</script>
After placing the above script in your head section of the web page all you need to do is call the function on the keypress event of a textbox/text field and pass in all the characters that you want to be allowed as follows:
< type="text" name="zip" id="zip" style="width:100px;" maxlength="7" onkeypress="return keyRestrict(event,'1234567890. ')" />>
Note: Please ensure that you conduct server side validations for user input, as JavaScript can be easily disabled in any browser and the above restrictions can be bypassed.
01 January 2009
28 December 2008
GridView Custom Pager Template
This is a Custom GridView Pager Template with DropDownList for pagination , Next-Previous, First-Last navigation and TextBox with save button to control the Page Size.
I had searched many site for this functionality. Finally after referring a few good examples I came up with the following according to my need.
****************************HTML*****************************
<PagerTemplate>
<div id="pager" >
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true">
</asp:DropDownList>
View
<asp:TextBox ID="txtPageSize"
runat="server" Width="25px" EnableViewState="true"></asp:TextBox>
results per page <asp:LinkButton ID="lnkSavePageSize" runat="server"
OnClick="lnkSavePageSize_click"><strong>Save</strong></asp:LinkButton>
|
<asp:Label ID="lblNumber" runat="server"></asp:Label> |
<asp:LinkButton Text="First" CommandName="Page" CommandArgument="First" runat="server" ID="btnFirst" />
<asp:LinkButton Text="Previous" CommandName="Page" CommandArgument="Prev" runat="server" ID="btnPrevious" /> -
<asp:LinkButton Text="Next" CommandName="Page" CommandArgument="Next" runat="server" ID="btnNext" />
<asp:LinkButton Text="Last" CommandName="Page" CommandArgument="Last" runat="server" ID="btnLast" />
</div>
</PagerTemplate>
******************************CODE BEHIND************************
//need to bind the following event with your gridview control
protected void myGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(myGridView, e.Row, this);
}
}
//This is a custom function
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page)
{
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
LinkButton btnFirst = (LinkButton)gvPagerRow.FindControl("btnFirst");
LinkButton btnPrevious = (LinkButton)gvPagerRow.FindControl("btnPrevious");
LinkButton btnNext = (LinkButton)gvPagerRow.FindControl("btnNext");
LinkButton btnLast = (LinkButton)gvPagerRow.FindControl("btnLast");
Label lblNumber = (Label)gvPagerRow.FindControl("lblNumber");
TextBox txtPageSize = (TextBox)gvPagerRow.FindControl("txtPageSize");
lblNumber.Text = "Pages " + Convert.ToString(pageIndex+1) + " of " + pageCount.ToString();
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
if (btnNext.Enabled == false)
{
btnNext.Attributes.Remove("CssClass");
}
DropDownList ddlPageSelector =
(DropDownList)gvPagerRow.FindControl("ddlPageSelector");
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
txtPageSize.Text = gridView.PageSize.ToString();
//Used delegates over here
ddlPageSelector.SelectedIndexChanged += delegate
{
gridView.PageIndex = ddlPageSelector.SelectedIndex;
gridView.DataBind();
};
}
protected void lnkSavePageSize_click(object sender, EventArgs e)
{
GridViewRow pagerRow = myGridView.BottomPagerRow;
TextBox temp1= (TextBox)pagerRow.FindControl("txtPageSize");
if(temp1.Text!="")
{
myGridView.PageSize = Convert.ToInt32(temp1.Text);
}
}
Link for Reference:Click Here
I had searched many site for this functionality. Finally after referring a few good examples I came up with the following according to my need.
****************************HTML*****************************
<PagerTemplate>
<div id="pager" >
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true">
</asp:DropDownList>
View
<asp:TextBox ID="txtPageSize"
runat="server" Width="25px" EnableViewState="true"></asp:TextBox>
results per page <asp:LinkButton ID="lnkSavePageSize" runat="server"
OnClick="lnkSavePageSize_click"><strong>Save</strong></asp:LinkButton>
|
<asp:Label ID="lblNumber" runat="server"></asp:Label> |
<asp:LinkButton Text="First" CommandName="Page" CommandArgument="First" runat="server" ID="btnFirst" />
<asp:LinkButton Text="Previous" CommandName="Page" CommandArgument="Prev" runat="server" ID="btnPrevious" /> -
<asp:LinkButton Text="Next" CommandName="Page" CommandArgument="Next" runat="server" ID="btnNext" />
<asp:LinkButton Text="Last" CommandName="Page" CommandArgument="Last" runat="server" ID="btnLast" />
</div>
</PagerTemplate>
******************************CODE BEHIND************************
//need to bind the following event with your gridview control
protected void myGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(myGridView, e.Row, this);
}
}
//This is a custom function
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page)
{
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
LinkButton btnFirst = (LinkButton)gvPagerRow.FindControl("btnFirst");
LinkButton btnPrevious = (LinkButton)gvPagerRow.FindControl("btnPrevious");
LinkButton btnNext = (LinkButton)gvPagerRow.FindControl("btnNext");
LinkButton btnLast = (LinkButton)gvPagerRow.FindControl("btnLast");
Label lblNumber = (Label)gvPagerRow.FindControl("lblNumber");
TextBox txtPageSize = (TextBox)gvPagerRow.FindControl("txtPageSize");
lblNumber.Text = "Pages " + Convert.ToString(pageIndex+1) + " of " + pageCount.ToString();
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
if (btnNext.Enabled == false)
{
btnNext.Attributes.Remove("CssClass");
}
DropDownList ddlPageSelector =
(DropDownList)gvPagerRow.FindControl("ddlPageSelector");
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
txtPageSize.Text = gridView.PageSize.ToString();
//Used delegates over here
ddlPageSelector.SelectedIndexChanged += delegate
{
gridView.PageIndex = ddlPageSelector.SelectedIndex;
gridView.DataBind();
};
}
protected void lnkSavePageSize_click(object sender, EventArgs e)
{
GridViewRow pagerRow = myGridView.BottomPagerRow;
TextBox temp1= (TextBox)pagerRow.FindControl("txtPageSize");
if(temp1.Text!="")
{
myGridView.PageSize = Convert.ToInt32(temp1.Text);
}
}
Link for Reference:Click Here
26 December 2008
Javascript RegExp Function
JavaScript provides a very useful function for client side user input validation. This function uses regular expressions for validation against the input.
If you are a PHP developer then you must have knowledge of this feature, whereas for ASP.NET 2.0 we already have the regular expression validator control which also uses similar regular expressions.
A simple example of the RegExp is as follows:
<script type="text/javascript" langusge="javascript">
function validate_phone(obj)
{
//for US phone number format: (xxx) xxx-xxxx
var RegExp=/\(\d{3}\)\ \d{3}-\d{4}/;
if(RegExp.test(obj.value))
{
return true;
}
else
{
obj.select();
obj.focus();
return false;
}
}
</script>
Note: Passing a correct regular expression is very important. You can find various regular expressions according to your need by Googling around. Also note that the regular expression must be inside the / / i.e var RegExp=/ /;
If you are a PHP developer then you must have knowledge of this feature, whereas for ASP.NET 2.0 we already have the regular expression validator control which also uses similar regular expressions.
A simple example of the RegExp is as follows:
<script type="text/javascript" langusge="javascript">
function validate_phone(obj)
{
//for US phone number format: (xxx) xxx-xxxx
var RegExp=/\(\d{3}\)\ \d{3}-\d{4}/;
if(RegExp.test(obj.value))
{
return true;
}
else
{
obj.select();
obj.focus();
return false;
}
}
</script>
Note: Passing a correct regular expression is very important. You can find various regular expressions according to your need by Googling around. Also note that the regular expression must be inside the / / i.e var RegExp=/ /;
24 December 2008
Regular Expression for File Upload Validation
This is a Regular Expression for validating the file upload HTML/ASP.NET control on the client side using JavaScript!
" ^.+\.(([jJ][pP][eE]?[gG]) | ([gG][iI][fF]) | ([bB][mM][pP]) | ([pP][nN][gG]) |([wW][mM][fF]))$ "
As you can see you can specify any file format between the | | fields which stand for OR.
You can use this function in ASP.NET 2.0 with the Regular Expression Validator or can use the JavaScript RegExp function for PHP.
Note: Its always a good idea to validate the user input on the server side!!
" ^.+\.(([jJ][pP][eE]?[gG]) | ([gG][iI][fF]) | ([bB][mM][pP]) | ([pP][nN][gG]) |([wW][mM][fF]))$ "
As you can see you can specify any file format between the | | fields which stand for OR.
You can use this function in ASP.NET 2.0 with the Regular Expression Validator or can use the JavaScript RegExp function for PHP.
Note: Its always a good idea to validate the user input on the server side!!
22 December 2008
Using Session variables in Javascript
One of the common problems Web Developers face is interaction between client side and server side scripts. With the advent of AJAX it has become very simple.
But there are situations were we need to change the JavaScript variables dynamically without changing the rest of the script. For example some flash elements require JavaScript variables for their functionality like keeping track of the tabs.
This can be achieved very easily through the use of session variable as follows:
<script type="text/javascript" language="javascript">
function myFunction()
{
var var1=21;
var var2=<%=Convert.ToString(Session["myVariable"])%>
------
------
------
}
</script>
All you need to do is assign the session variable with the value you want on the page load in code behind.
I was quiet curious and also tried the vice verse i.e assigning a Session Variable in JavaScript. But it doesn't work !!!! Have to use alternate methods. If any one knows a way of doing so..Please Comment
But there are situations were we need to change the JavaScript variables dynamically without changing the rest of the script. For example some flash elements require JavaScript variables for their functionality like keeping track of the tabs.
This can be achieved very easily through the use of session variable as follows:
<script type="text/javascript" language="javascript">
function myFunction()
{
var var1=21;
var var2=<%=Convert.ToString(Session["myVariable"])%>
------
------
------
}
</script>
All you need to do is assign the session variable with the value you want on the page load in code behind.
I was quiet curious and also tried the vice verse i.e assigning a Session Variable in JavaScript. But it doesn't work !!!! Have to use alternate methods. If any one knows a way of doing so..Please Comment
Subscribe to:
Posts (Atom)

