using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO.MemoryStream;using System.Drawing.Imaging;using System.Net;using System.IO.FileStream;public partial class Default11 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){string urlToDownload = "http://www.google.co.in/images/srpr/nav_logo14.png";// May be you need to add some code to determine the type of the imagestring pathToSave = Server.MapPath("~/") + "/saved.png";// Download itWebClient client = new WebClient();client.DownloadFile(urlToDownload, pathToSave);})
Tuesday, April 22, 2014
How to save an image using the image URL
Sunday, April 20, 2014
Validate ASP.Net CheckBoxList control using JavaScript (Select atleast one item)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %><!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><script type = "text/javascript">var atLeast = 1function ValidateCheckBoxList() {var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");var checkbox = CHK.getElementsByTagName("input");var counter = 0;for (var i = 0; i < checkbox.length; i++) {if (checkbox[i].checked) {counter++;}}if (atLeast > counter) {alert("Please select atleast " + atLeast + " item(s)");return false;}return true;}</script></head><body><form id="form1" runat="server"><div><asp:CheckBoxList ID="CheckBoxList1" runat="server"><asp:ListItem Text = "Apple" Value = "1"></asp:ListItem><asp:ListItem Text = "Mango" Value = "2"></asp:ListItem><asp:ListItem Text = "Orange" Value = "3"></asp:ListItem></asp:CheckBoxList><asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="*Required"ClientValidationFunction = "ValidateCheckBoxList"></asp:CustomValidator><asp:Button ID="Button1" runat="server" Text="Button" /></div></form></body></html>
Validate ASP.Net ListBox control using JavaScript
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %><!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><script type = "text/javascript">function ValidateListBox(sender, args) {var options = document.getElementById("<%=ListBox1.ClientID%>").options;for (var i = 0; i < options.length; i++) {if (options[i].selected == true) {args.IsValid = true;return;}}args.IsValid = false;}</script></head><body><form id="form1" runat="server"><div><asp:ListBox ID="ListBox1" runat="server" SelectionMode = "Multiple"><asp:ListItem Text = "Apple" Value = "1"></asp:ListItem><asp:ListItem Text = "Mango" Value = "2"></asp:ListItem><asp:ListItem Text = "Orange" Value = "3"></asp:ListItem></asp:ListBox><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="*Required"ClientValidationFunction = "ValidateListBox"></asp:CustomValidator><asp:Button ID="Button1" runat="server" Text="Button" /></div></form></body></html>
Saturday, April 19, 2014
Date Range Validation in AJAX CalendarExtender Control using ASP.Net Range Validator
In this article I will explain how to implement Range Validation in ASP.Net AJAX Control Toolkit CalendarExtender Control.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager><asp:TextBox ID="txtDate" runat="server" ReadOnly = "true"></asp:TextBox><br /><asp:RangeValidator runat="server" ID="RangeValidator1" Type="Date" ControlToValidate="txtDate" MaximumValue='09/20/2011' MinimumValue="09/01/2011"ErrorMessage="Date should be between 09/01/2011 and 09/20/2011" Display="Dynamic" /><cc1:CalendarExtender ID = "Calender1" runat = "server" TargetControlID = "txtDate"></cc1:CalendarExtender><br /><asp:Button ID="Button1" runat="server" Text="Submit" /></form>
Above you will notice that I have an ASP.Net TextBox Control txtDate for which I have specified AJAX Control Toolkit CalendarExtender Control Calender1.
Also I have specified ASP.Net RangeValidator Control RangeValidator1 for the TextBox txtDate. This range validator will throw error when the selected date does not fit in the specified range.
In order to make the Range Validator work for the Dates. You need to specify the following paramaters
Type – Specifies that the range validations are for Dates.
MinimumValue – Specifies the minimum value of the range.
MaximumValue - Specifies the minimum value of the range.
Screenshot
ASP.NET AJAX Calendar Extender – Tips and Tricks
ASP.NET AJAX Calendar Extender – Tips and Tricks
The CalendarExtender is an ASP.NET AJAX control that is associated with a TextBox control. When the user clicks on the TextBox, a client-side Calendar control pops up. The user can then set a date by clicking on a day, navigate months by clicking on the left and right arrow and perform other such actions without a postback. In this article, we will see some tips and tricks that can be applied to a CalendarExtender control. If you are new to the CalendarExtender control, you can check out some information about it over here.
I assume you have some basic experience developing ASP.NET Ajax applications and have installed theASP.NET Ajax Library and ASP.NET Control Toolkit. As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008).
All the tips shown below have been created using Version 3.0.20229 (targeting .NET Framework 3.5 and Visual Studio 2008).
Tip 1: How to display and hide a Calendar on the click of a Button
If you want to popup a Calendar on the click of a button, you can use set the PopupButtonID of the CalendarExtender to the ID of the button. In this case, we will be using an ImageButton as shown below:
<asp:ImageButton runat="Server" ID="ImageButton1" ImageUrl="~/Images/Icon1.jpg"AlternateText="Click here to display calendar" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1" PopupButtonID="ImageButton1"/>
If you are using an earlier version of the toolkit, you may observe that the ImageButton causes a postback when you click on it again, to close the Calendar. To avoid the postback, use a HTML Image Control instead of the Server side Image Control as shown below:
<img alt="Icon" src="/Images/Icon1.jpg" id="Image1" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1" PopupButtonID="Image1"/>
Note: In case you are clicking on the textbox to open the calendar, then in earlier versions of the toolkit, the calendar would not hide automatically when the user clicked anywhere outside the Calendar control. However this was fixed in the later versions. In fact, in the latest version, the Calendar hides automatically when a date is selected.
If for some reason you are facing issues with the Calendar not hiding automatically, make sure that you have the latest version of the AJAX Control Toolkit.
Tip 2: How to Add a CalendarExtender to a GridView
If you want to add a CalendarExtender to a GridView, use a template field with a TextBox and CalendarExtender as shown below:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"DataKeyNames="CategoryID"
DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True"AllowSorting="True">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server"TargetControlID="TextBox1"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]" >
</asp:SqlDataSource>
</div>
</form>
Tip 3: Enable Year Navigation in CalendarExtender
When the calendar appears, click on the title of the calendar to change the view to Months in the current year. Clicking it again, switches the view to Years, showing 10 years at a time.
If you plan to do this programmatically, here’s some code for you. Use the OnClientShown event and switch the mode using javascript. This tip was shared by one of the Microsoft® support person at the asp.net forums.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1"
runat="server" TargetControlID="TextBox1" OnClientShown="ChangeCalendarView" />
Then add this to the <head> section
<head runat="server">
<title>CalendarExtender</title>
<script type="text/javascript">
function ChangeCalendarView(sender,args)
{
sender._switchMode("years", true);
}
</script>
</head>
Tip 4: Display only the day and month in the CalendarExtender
To select only the day and month without the year, use the Format property of the CalendarExtender and set it to “dd/MM” as shown below:
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" Format="dd/MM"TargetControlID="TextBox1" />
Tip 5: How to Set Culture to work with CalendarExtender
Make sure that the ScriptManager has EnableScriptGlobalization="true" and EnableScriptLocalization="true".
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableScriptGlobalization="true" EnableScriptLocalization="true" />
Tip 6: How to make sure user does not select a date earlier than today or greater than today
There could be instances where you do not want the user to select a day earlier than the current date. For example: when you are providing the user a form to book tickets, you would not like him to choose an earlier date. To achieve this requirement, use the following javascript code.
Prevent the User from selecting a Date Earlier than today
<head runat="server">
<title>Calendar Extender</title>
<script type="text/javascript">
function checkDate(sender,args)
{
if (sender._selectedDate < new Date())
{
alert("You cannot select a day earlier than today!");
sender._selectedDate = new Date();
// set the date back to the current date
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}
</script>
</head>
Call the code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1"
runat="server"OnClientDateSelectionChanged="checkDate" TargetControlID="TextBox1" />
</div>
</form>
Select Date Greater than today
In the javascript, just change this line
sender._selectedDate > new Date()
Note: You may argue that the user can still change the date by typing into the textbox or entering an invalid date. Well that can be easily handled using a ValidationControl and is covered in the next tip.
Tip 7: Add validation to the CalendarExtender Control
A simple way to add validation to the Calendar is to add a ValidationControl to the textbox associated with a CalendarExtender. You have two choices:
A. Add an ‘Extender’ to the ValidationControl. To do so, drag and drop a ValidationControl > click on the smart tag of the ValidationControl > choose ‘Add Extender’. From the Extender Wizard, choose ValidatorCalloutExtender. Using this approach makes it extremely easy to discover and attach control extenders to your controls. In VS 2005, you had to do this process manually, by wiring up control extenders.
B. You can choose not to add the Extender.
We will go ahead with option A. We will be adding two ValidationControls to the textbox. The first, a CompareValidator to check if the user does not enter an invalid date (Eg: May 32) and second, a RangeValidator to keep the date range as desired.
Adding CompareValidator
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Invalid Date"
Operator="DataTypeCheck" Type="Date">
</asp:CompareValidator>
<cc1:ValidatorCalloutExtender ID="CompareValidator1_ValidatorCalloutExtender"
runat="server" Enabled="True" TargetControlID="CompareValidator1">
</cc1:ValidatorCalloutExtender>
Adding RangeValidator – We will restrict the user to select a date range starting from today to 15 days from now.
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RangeValidator"
Type="Date">
</asp:RangeValidator>
<cc1:ValidatorCalloutExtender ID="RangeValidator1_ValidatorCalloutExtender"
runat="server" Enabled="True" TargetControlID="RangeValidator1">
</cc1:ValidatorCalloutExtender>
In the code behind of your page, add this code
C#
protected void Page_Load(object sender, EventArgs e)
{
RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString();
RangeValidator1.MaximumValue = System.DateTime.Now.AddDays(15).ToShortDateString();
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString()
RangeValidator1.MaximumValue = System.DateTime.Now.AddDays(15).ToShortDateString()
End Sub
Well those were some tips associated with the CalendarExtender. As future versions of the toolkit are released, we should be hopeful that there will exist easier ways, of achieving the functionality discussed in this article. I hope this article was useful and I thank you for viewing it.
Saturday, April 5, 2014
Read a Text file line by line in C# .NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %><!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><h2>Read txt file</h2><asp:Label ID="Label1" runat="server"></asp:Label></div></form></body></html>
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;public partial class Default7 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){ReadLineByLine();ReadTextFileAndSplit();}void ReadLineByLine(){string inputString;using (StreamReader streamReader = File.OpenText(Server.MapPath("~") + @"\test.txt")){inputString = streamReader.ReadLine();while (inputString != null){Label1.Text += inputString + "<br \\>";inputString = streamReader.ReadLine();}}}void ReadTextFileAndSplit(){string inputString;using (StreamReader streamReader = File.OpenText(Server.MapPath("~") + @"\test.txt")){inputString = streamReader.ReadLine();while (inputString != null){string[] spilt = inputString.Split(' ');string Name = spilt[0];string Location = spilt[1];string Id = spilt[2];inputString = streamReader.ReadLine();}}}}
test.txtRakesh NY 101Ram Canada 102Suresh India 103
Save To Xml temporarily and then save to database
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"><title></title></head><body><form id="form1" runat="server"><h2>Save To Xml temporarily and then save to database</h2><div><table><tr><td style="width: 100px">Name:</td><td style="width: 100px"><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td></tr><tr><td style="width: 100px">Location:</td><td style="width: 100px"><asp:TextBox ID="txtLocation" runat="server"></asp:TextBox></td></tr><tr><td style="width: 100px">Email:</td><td style="width: 100px"><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td></tr><tr><td style="width: 100px" valign="top">Comments:</td><td style="width: 100px"><asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="104px"></asp:TextBox></td></tr><tr><td></td><td><asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td></tr></table><br /><asp:DataList ID="dlComments" Runat="server" Width="100%" OnItemCommand="dlComments_ItemCommand"><ItemTemplate><asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Id") %>' Visible="false"></asp:Label>Name:<asp:Label ID="lblName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label><br />E-mail:<a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%# DataBinder.Eval(Container.DataItem, "email") %></a><asp:Label ID="lblEmail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "email") %>' Visible="false"></asp:Label> <br />Location:<asp:Label ID="lblLocation" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "location") %>'></asp:Label><br />Date:<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Date") %>'></asp:Label><br />Description:<asp:Label ID="lblDescription" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>'></asp:Label><br /><asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Deletes" CommandArgument='<%#Eval("Id") %>'/></ItemTemplate></asp:DataList><br /><br /><br /><br /><br /><asp:Button ID="btnSaveInDatabase" runat="server" Text="Save To database" OnClick="btnSaveInDatabase_Click"/></div></form></body></html>
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Text.RegularExpressions;using System.Xml;using System.Data;public partial class Default5 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){//Bind xml data to datalistBindDatalist();}}/// <summary>/// btnSubmit event is used to insert data into XML file/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void btnSubmit_Click(object sender, EventArgs e){XmlDocument xmldoc = new XmlDocument();xmldoc.Load(Server.MapPath("Sample1.xml"));XmlElement parentelement = xmldoc.CreateElement("Comments");XmlElement Id = xmldoc.CreateElement("Id");Id.InnerText = Convert.ToString(Guid.NewGuid());XmlElement name = xmldoc.CreateElement("Name");name.InnerText = txtName.Text;XmlElement location = xmldoc.CreateElement("location");location.InnerText = txtLocation.Text;XmlElement email = xmldoc.CreateElement("Email");email.InnerText = txtEmail.Text;XmlElement Description = xmldoc.CreateElement("Description");Description.InnerText = txtComments.Text;XmlElement date = xmldoc.CreateElement("Date");date.InnerText = DateTime.Now.ToString();parentelement.AppendChild(Id);parentelement.AppendChild(name);parentelement.AppendChild(location);parentelement.AppendChild(email);parentelement.AppendChild(Description);parentelement.AppendChild(date);xmldoc.DocumentElement.AppendChild(parentelement);xmldoc.Save(Server.MapPath("Sample1.xml"));BindDatalist();}/// <summary>/// Bind xml data to datalist/// </summary>private void BindDatalist(){XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample1.xml"));DataSet ds = new DataSet();ds.ReadXml(xmlreader);xmlreader.Close();if (ds.Tables.Count != 0){dlComments.DataSource = ds;dlComments.DataBind();}else{dlComments.DataSource = null;dlComments.DataBind();}}protected void dlComments_ItemCommand(object sender, CommandEventArgs e){string ComamndName = e.CommandName;switch (ComamndName){case "Deletes":Guid Id = new Guid(Convert.ToString(e.CommandArgument));//Add Delete Method here;deleteNode(Id);break;}}public void deleteNode(Guid Id){XmlDocument xmldoc = new XmlDocument();xmldoc.Load(Server.MapPath("Sample1.xml"));foreach (XmlNode node in xmldoc.SelectNodes("CommentsInformation/Comments")){if (node.SelectSingleNode("Id").InnerText == Id.ToString()){node.ParentNode.RemoveChild(node);}}xmldoc.Save(Server.MapPath("Sample1.xml"));BindDatalist();}protected void btnSaveInDatabase_Click(object sender, EventArgs e){foreach (DataListItem item in dlComments.Items){//We have already binded the values in the datalist in design page (Note:if u have not set - u can assign the values in OnItemDataBound event)Label lblId = (Label)item.FindControl("lblId");Label lblName = (Label)item.FindControl("lblName");Label lblEmail = (Label)item.FindControl("lblEmail");Label lblLocation = (Label)item.FindControl("lblLocation");Label lblDate = (Label)item.FindControl("lblDate");Label lblDescription = (Label)item.FindControl("lblDescription");string Id = lblId.Text;string Name = lblName.Text;string Email = lblEmail.Text;string Location = lblLocation.Text;string Date = lblDate.Text;string Description = lblDescription.Text;//write your save method here eg://SaveToDb(Id, Name, Email, Location, Date, Description);}}}
Sample1.xml<?xml version="1.0" encoding="utf-8"?><CommentsInformation><Comments><Id>4fc979eb-c451-424d-960a-a2c99c834768</Id><Name>Name1</Name><location>NY</location><Email>test@test.com</Email><Description>test</Description><Date>4/5/2014 7:47:50 PM</Date></Comments><Comments><Id>5f3700d3-8247-47fb-ad27-7150922026c8</Id><Name>Name2</Name><location>India</location><Email>test@test.com</Email><Description>test</Description><Date>4/5/2014 7:48:02 PM</Date></Comments></CommentsInformation>