Friday, January 27, 2012

Round Crrner Div CSS

style type="text/css">
.rtop, .rbottom{display:block; }
.rtop *, .rbottom *{display: block; height: 1px; overflow: hidden}
.r1{margin: 0 5px; background:#9BD1FA;}
.r2{margin: 0 3px; background:#9BD1FA;}
.r3{margin: 0 2px; background:#9BD1FA;}
.r4{margin: 0 1px; height: 2px; background:#9BD1FA;}
.contain{background:#9BD1FA;text-align:center;}
/style>
div id="container" style="width:100px;">
b class="rtop">
b class="r1">
b class="r2">
b class="r3">
b class="r4">
/b>
div class="contain">Happy Birthday

b class="rbottom">
b class="r4">
b class="r3">
b class="r2">
b class="r1">
/b>
/div>

Tuesday, October 18, 2011

get http value default.aspx to default.aspx

Drag a textbox, button on the same page

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

if (!string.IsNullOrEmpty(Request.QueryString["TextBoxVal"]))
{
string textboxvalue = Request.QueryString["TextBoxVal"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?TextBoxVal=" + TextBox1.Text);
}
}

Thursday, July 15, 2010

Stored Procedure using Dataset with where clause

<asp:TextBox ID="tbxAccountName" runat="server"></asp:TextBox>
<asp:Button ID="btnAccountName" runat="server" Text="Get Account Name" OnClick="btnAccountName_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<br />
<asp:GridView ID="gvProductDisplay" runat="server">
<Columns>
<asp:TemplateField HeaderText="AccountTypeID">
<ItemTemplate>
<asp:Label ID="lblAccountTypeID" runat="server" Text='<%# Bind("AccountTypeID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountTypeName">
<ItemTemplate>
<asp:Label ID="lblAccountTypeName" runat="server" Text='<%# Bind("AccountTypeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountTypeCode">
<ItemTemplate>
<asp:Label ID="lblAccountTypeCode" runat="server" Text='<%# Bind("AccountTypeCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


protected void btnAccountName_Click(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AccountingConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("sp_AccountType", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add(new SqlParameter("@AccountTypeName", tbxAccountName.Text));
da.SelectCommand.Parameters["@AccountTypeName"].Value = tbxAccountName.Text;
da.Fill(ds, "AccountType");
gvProductDisplay.DataSource = ds;
gvProductDisplay.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

Saturday, June 5, 2010

Sql Connection String Windows Authentication Mode

<add name="NorthwindConnectionString" connectionString="Data Source=ADMIN-PC\SA;Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient" />

Saturday, May 22, 2010

Disable a button control during postback

<asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!" />

File Upload Error

The default size of files uploaded by the FileUpload control is 4MB. So if you try to upload the files larger than 4MB, it won't let you do so. To do so, you need to change the default file size in machine.config file for maxRequestLength of httpRuntime tag. This number is in KB.

<httpRuntime
executionTimeout = "110"
maxRequestLength = "4096"
requestLengthDiskThreshold = "80"
useFullyQualifiedRedirectUrl = "false"
minFreeThreads = "8"
minLocalRequestFreeThreads = "4"
appRequestQueueLimit = "5000"
enableKernelOutputCache = "true"
enableVersionHeader = "true"
apartmentThreading = "false"
requireRootedSaveAsPath = "true"
enable = "true"
sendCacheControlHeader = "true"
shutdownTimeout = "90"
delayNotificationTimeout = "5"
waitChangeNotification = "0"
maxWaitChangeNotification = "0"
enableHeaderChecking = "true"
/>

Friday, May 21, 2010

Asp.Net Ajax Error Handling

Exceptions that occur during Ajax postback are presented as a JavaScript alert, the goal is to hook up on EngRequest event so that you can access EndRequestEventArgs class that provides an information about exceptions occurred. That way you can eliminate JavaScript alert and show useful information in custom message boxes like those I show you in my previous articles CSS Message Boxes and MessageBox user control using ASP.NET and CSS.

However, if you want to be able to do some server processing when error occur you can make use of ScriptManager. You will have to define OnAsyncPostBackError handler in the definition of ScriptManager.

<asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError" />

This will allow you to have the access to the error on the server:

protected void ScriptManager1_AsyncPostBackError(object sender,AsyncPostBackErrorEventArgs e)
{

// do whatever you need to do here
}

Monday, May 17, 2010

Dropdownlist in a Gridview and the default (null) value problem

The problems come if the data in the table doesnt fit your data in the PLZ table. Most common reason is that the field contains a NULL Value. Bind fails!

The trick is that you can add items to the dropdown list by declaration. The second part of the trick is to add the DB entrys to the declarated entrys by AppenddataboundItems. Take care to set the value to "" cause the bind gives also back a "" if the field contains NULL


<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="DSPLZ" DataTextField="PLZ"

DataValueField="PLZ" SelectedValue='<%# Bind("shipPLZ") %>' AppendDataBoundItems=true>

<asp:ListItem Text="wählen" Value=""></asp:ListItem>

</asp:DropDownList>



</asp:TemplateField>

Dropdownlist in a Gridview and the default (null) value problem

The problems come if the data in the table doesnt fit your data in the PLZ table. Most common reason is that the field contains a NULL Value. Bind fails!

The trick is that you can add items to the dropdown list by declaration. The second part of the trick is to add the DB entrys to the declarated entrys by AppenddataboundItems. Take care to set the value to "" cause the bind gives also back a "" if the field contains NULL


;<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="DSPLZ" DataTextField="PLZ"

DataValueField="PLZ" SelectedValue=';<%# Bind("shipPLZ") %;>' AppendDataBoundItems=true;>

;<asp:ListItem Text="wählen" Value="";></asp:ListItem;>

;</asp:DropDownList;>



;</asp:TemplateField;>

Friday, January 8, 2010

Back Up Sql Server Programmatically

Function which is used to take backup from Sql Server via Code


protected void BackUpNow()
{
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString()))
{
string query = "BACKUP DATABASE Northwind " +
"TO DISK = 'C:\\Setup\\Northwind.bak' " +
"WITH NAME = 'ApressFinancial-Full Database Backup', " +
"SKIP, " +
"NOUNLOAD, " +
"STATS = 10";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Write("Your Database Backup Successfully Done");
}

}
}
catch(Exception ex)
{
lblException.Text = ex.Message;
}
}

Call this Function on Page Load


protected void Page_Load(object sender, EventArgs e)
{
BackUpNow();
}

Monday, December 7, 2009

Stored Procedure using Dataset

//Create a Stored Procedure
CREATE PROCEDURE SelProduct
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT Product_id, Product_Name, Product_Prise, Product_Quantity FROM Product
END
GO
//Call the Select Product Stored Procedure into the code
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleConnString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SelProduct", conn);
DataSet ds = new DataSet();
da.Fill(ds);
gvProductDisplay.DataSource = ds;
gvProductDisplay.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Tuesday, November 24, 2009

Apply Parameter Field using Crystal Report

Design View of the Page
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
Code Behind of the Page
ReportDocument objReportDocument;
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["EmployeeID"] != null)
{
string reportPath = Server.MapPath("ProgramaticallyReport.rpt");
objReportDocument = new ReportDocument();
ParameterDiscreteValue objDiscreteValueEmployeeID = new ParameterDiscreteValue();
string objCustomerID = (Convert.ToString(Request.QueryString["EmployeeID"]));
objDiscreteValueEmployeeID.Value = objCustomerID;
//ParameterDiscreteValue objDiscreteValueLastMonth = new ParameterDiscreteValue();
//DateTime objDate2 = (System.Convert.ToDateTime(Request.QueryString["Date2"]));
//objDiscreteValueLastMonth.Value = objDate2;
ParameterField objParameterField = new ParameterField();
objParameterField.Name = "EmpID";
objParameterField.CurrentValues.Add(objDiscreteValueEmployeeID);
//objParameterField.CurrentValues.Add(objDiscreteValueLastMonth);
ParameterFields objParameterFields = new ParameterFields();
objParameterFields.Add(objParameterField);
objReportDocument.Load(reportPath);
objReportDocument.SetDataSource(GetCustomer());
CrystalReportViewer1.ParameterFieldInfo = objParameterFields;
CrystalReportViewer1.ReportSource = objReportDocument;
}
else
{
Exception objException = new Exception();
lblMessage.Text = objException.Message;
}
GetCustomer Dataset Method
public DataSet GetCustomer()
{
string objCustomerID = (Convert.ToString(Request.QueryString["EmployeeID"]));
SqlParameter objParameter = new SqlParameter();
SqlCommand objCommand = new SqlCommand();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID,FirstName, LastName, City, Country " +
"FROM Employees where EmployeeID=@EmployeeID", conn);
da.SelectCommand.Parameters.Add(new SqlParameter("@EmployeeID", objCustomerID));
da.SelectCommand.Parameters["@EmployeeID"].Value = objCustomerID;
DataSet ds = new DataSet();
da.Fill(ds, "Employees");
return ds;
}

Using HyperLink in Gridview

Design View of Page
<asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="BirthDate" HeaderText="BirthDate" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("EmployeeID","Default.aspx?EmployeeID={0}") %>' Text='<%# Bind("EmployeeID") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behing of Page
SqlParameter objParameter = new SqlParameter();
SqlCommand objCommand = new SqlCommand();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, FirstName, LastName, BirthDate, City, Country FROM Employees", conn);
//da.SelectCommand.Parameters.Add(new SqlParameter("@CustomerID", customerid));
//da.SelectCommand.Parameters["@CustomerID"].Value = customerid;
DataSet ds = new DataSet();
da.Fill(ds, "Employees");
gvEmployee.DataSource = ds;
gvEmployee.DataBind();

Tuesday, November 17, 2009

Custom Membership and Role Provider

Membership Provider
<membership defaultProvider="CustomMembershipProvider">
<providers>
<add name="CustomMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MusharkaCertConnString" applicationName="MusharkaCertificate" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Clear" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordStrengthRegularExpression="(\w+)*"/>
<providers>
<membership>
Role Provider
<roleManager enabled="true" defaultProvider="CustomProvider">
<providers>
<add connectionStringName="MusharkaCertConnString" name="CustomProvider" type="System.Web.Security.SqlRoleProvider"/>
</providers>
</roleManager>

Grouping Data into the ListView Control

Beore Designing HTML Page
Add New Item "Linq 2 Sql Classes" and Drag 2 table from Server Explorer
1) Customers
2) Orders

Design View of HTML Page
<asp:ListView ID="lvCustomerOrders" runat="server" ItemPlaceholderID="itemPlaceHolder">
<LayoutTemplate>
<h2>Customers</h2>
<ul>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server">
</asp:PlaceHolder>
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<b> <%# Eval("FirstName") %> <%# Eval("LastName") %> </b>
<asp:ListView ID="lvOrders" DataSource ='<%# Eval("Orders") %>' runat="server" ItemPlaceholderID="productPlaceHolder">
<LayoutTemplate>
<table>
<tr>
<th>
Order Name
</th>
<th>
Quantity
</th>
</tr>
<asp:PlaceHolder ID="productPlaceHolder" runat="server"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<table width="120px">
<tr>
<td>
<%# Eval("OrderName") %>
</td>
<td>
<%# Eval("Quantity") %>
</td>
</tr>
</table>
</ItemTemplate>
<EmptyDataTemplate>
<li>
<table><tr><td style="color:Red">There are no Orders</td></tr></table>
</li>
</EmptyDataTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
Code Behind of HTML Page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}

}
private void BindData()
{
using (var db = new NwdDataClassesDataContext())
{
lvCustomerOrders.DataSource = from c in db.Customers
select c;
lvCustomerOrders.DataBind();
}

}

Insert Data into Multiple Tables

DECLARE @ID int
INSERT INTO Customers
(FirstName, LastName)
VALUES ('Sheeban', 'Ahmed')
SET @ID = SCOPE_IDENTITY()
INSERT INTO Orders
(CustomerID, OrderName, Quantity)
VALUES (@ID,'IPhone',100)

Wednesday, August 26, 2009

Saving Word Document to the Sql Server

First we have to create a table to store the Word Document
CREATE TABLE [dbo].[File1](
[id] [int] IDENTITY(1,1) NOT NULL,
[Filename] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[FileBytes] [varbinary](max) NOT NULL
) ON [PRIMARY]
The Design view of a Web Form
<asp:Label id="lblFile" Text="wordDocument" AssociatedControlID="upFile" runat="server" />
<asp:FileUpload id="upFile" runat="Server" />
<asp:Button id="btnAdd" Text="Add Documents" runat="server" OnClick="btnAdd_Click" />
<hr />
<asp:Repeater id="rptFiles" DataSourceID="srcFiles" runat="Server">
<HeaderTemplate>
<ul class="fileList">
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink id="lnkFile" Text='<%#Eval("FileName")%>' NavigateUrl='<%#Eval("id","~/FileHandler.ashx?id={0}")%>' runat="Server" />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
<asp:SqlDataSource id="srcFiles"
ConnectionString="<%$ ConnectionStrings:FileDBConnectionString %>"
SelectCommand="SELECT [id], [Filename] FROM [File1]"
InsertCommand="INSERT INTO [File1] (Filename, FileBytes) values (@fileName,@FileBytes)"
runat="server">
<InsertParameters>
<asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
<asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
</InsertParameters>
</asp:SqlDataSource>
The Code Behind of Button Add Documents
if (upFile.HasFile)
{
if (CheckFileType(upFile.FileName))
srcFiles.Insert();
}
The Function CheckFileType
bool CheckFileType(string fileName)
{
return Path.GetExtension(fileName).ToLower() == ".doc";
}
Then Add Custom Handler on to the Page
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/msword";
SqlConnection con = new SqlConnection(@"Data Source=SHEEBAN\SQLEXPRESS;Initial Catalog=FileDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select filebytes from [file1] where id=@id", con);
cmd.Parameters.AddWithValue("@id", context.Request["id"]);
using (con)
{
con.Open();
byte[] file = (byte[])cmd.ExecuteScalar();
context.Response.BinaryWrite(file);
}
}
public bool IsReusable
{
get
{
return false;
}
}

Monday, August 24, 2009

Saving Data into XML Format

DataSet ds = new DataSet();
Xml Xml1 = new Xml();
protected void Page_Load(object sender, EventArgs e)
{
//Create a connection string.
string sqlConnect=@"Data Source=SHEEBAN\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlConnection sqlconnect = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
//Create a connection object to connect to the web shoppe database
try
{
SqlConnection nwconnect = new SqlConnection(sqlConnect);
String scommand = "select top 10 * from customers";
//Create an adapter to load the dataset
SqlDataAdapter da = new SqlDataAdapter(scommand, nwconnect);
//Fill the dataset
da.Fill(ds, "Customers");
XmlDataDocument doc = new XmlDataDocument(ds);
//Xml1.Document = doc;
doc.Save(MapPath("Customers.xml"));//This is where we are saving the data in an XML file Customers.xml
Label1.Text = "Your Data saved succesfully";
}
catch
{
//if there is any error then Label1 will give the Error
Label1.Text = "Error while connecting to database";
}
}

SQL Injection Example

Design A Form of the Web Page
<table>
<tr>
<td>
UserName:
</td>
<td>
<asp:TextBox ID="tbxUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="tbxPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server" Text="Login" Width="150px" OnClick="btnLogin_Click"/>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<asp:Literal ID="Literal1" runat="server" Text=""></asp:Literal>
</td>
</tr>
</table>
//Now the Code Behind of the Button Login
string conn = ConfigurationManager.ConnectionStrings["FileDBConnectionString"].ConnectionString;
string query = "Select Count(*) From Users Where Username = '" + tbxUserName.Text + "' And Password = '" + tbxPassword.Text + "'";
int result = 0;
SqlConnection connection = new SqlConnection(conn);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
result = (int)cmd.ExecuteScalar();
if (result > 0)
{
connection.Close();
Response.Redirect("LoggedIn.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
connection.Close();
}
If we copy the "'or'1'='1"(without quotation marks) both in the password textbox and username textbox it will redirect you on to the LoggedIn page this is what we called SQL Injection


In order to control the SQL Injection we have to add few code of line Just before the Query
string username = tbxUserName.Text.Replace("'", "''");
string password = tbxPassword.Text.Replace("'", "''");
And query would be change into
string query = "Select Count(*) From Users Where Username = '" + username + "' And Password = '" + password + "'";

Saturday, August 22, 2009

Toggle HTML Element

//Just Design of a Web Form
Enter the Text:<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" onclick="toggle()" />

//JavaScript to toggle the HTML Element
<script type="text/javascript">
function toggle(){
document.getElementById('Text1').style.display == '' ? document.getElementById('Text1').style.display = 'none'
: document.getElementById('Text1').style.display = '';
}
</script>