HaresH Chaudhari

Freelance Web Developer

Get First and Last Date from Calender control in Asp.Net

Hello guys

Here I am going to explain how we can get the first date and last date for selected month and year from asp.net calender control. Here we just need quite easy logic on 2 events on calender. The events are Prerender and Dayrender. In PreRender, I have take session as null so everytime when page is loading, it get null before processing on calender days. Then I have write some logic to show FirstDate, Lastdate and also same for each week in the month.

C# Code
protected void Calendar1_PreRender(object sender, EventArgs e)
{
Session["FirstDay"] = null;
Session["LastDay"] = null;
}

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (Session["FirstDay"] == null)
Session["FirstDay"] = e.Day.Date;

if (Session["LastDay"] == null)
Session["LastDay"] = e.Day.Date.AddDays(41);

string LastDates = Convert.ToDateTime(Session["LastDay"]).ToShortDateString();
if (e.Day.Date.ToShortDateString() == LastDates)
{
DateTime FirstDate = Convert.ToDateTime(Session["FirstDay"]);
DateTime LastDate = Convert.ToDateTime(Session["LastDay"]);
Response.Write(“FirstDay:”+Session["FirstDay"].ToString() + “<br />”);
Response.Write(“LastDay:”+Session["LastDay"].ToString() + “<br />”);
for (DateTime i = FirstDate; i <= LastDate; )
{
DateTime WeekStart = i;
DateTime WeekEnd = i.AddDays(6);
Response.Write(“Week Start: ” + WeekStart.ToShortDateString() + “<br />”);
Response.Write(“WeekEnd: ” + WeekEnd.ToShortDateString() + “<br /><br />”);
i = i.AddDays(7);
}
}
}

I have also attached screen for better understand. I hope this will be helpful for you guys.

Thanks

Filed under: Asp.Net, C#.Net, Web Development , , ,

Remove duplicate rows from dataset or datatable in Asp.Net

Hello friend have take look on below code which might useful for you to remove any duplicate rows from your dataset or data table in asp.net with C#.
The first methods return the datatabe which removed duplicate row from your dataset. You cahve to fill your dataset and then in temporary table you can store new returned datatable and store in dataset.

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();

foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}

foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);

return dTable;
}

protected void btnRemoveDuplicate_Click(object sender, EventArgs e)
{
Fill your dataset
string strConn = ConfigurationManager.ConnectionStrings["Your Connection String key from config file"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter(“select * from Test”, conn);
DataSet ds = new DataSet();
da.Fill(ds, “Test”);

Take Temporary table and store 0th position’s table from dataset in your temp table.
DataTable dt = ds.Tables["Test"];

Pass that temp table in above method, so it return fresh table with duplicating rows. You must have to define the columnname for which you are going to remove duplicate rows. Here in example, “Name” column is passed for duplicate wors removal.
dt = RemoveDuplicateRows(dt, “Name”);

You have fresh table with distinct records here in dt table, you can assign in dataset of bing to your any data control
dgTest.DataSource = ds.Tables["Test"].DefaultView;
dgTest.DataBind();
}

I hope it helpful for you.
Thanks

Filed under: 1 , ,

How to expand panel with CollapsiblePanelExtender in Code behind

Hi, you can use following properties to make your extender as expanded in code behind file

YourExtenderControlIDClientState = “false”
YourExtenderControlID.Collapsed = False

Hope this would be helpful for you guys
Thanks

Filed under: 1

Select All Checkboxes in GridView in Asp.Net

I hope the following code will help you out to select all checkboxes in gridview in asp.net.

function SelectAllCheckboxesCategoryList(spanChk)
{
var chkALL = document.getElementById(spanChk);
var the_form = window.document.forms[0];
for(var i=0; i -1)
{
the_form.elements[i].checked = chkALL.checked;
}
}
}
}

function UncheckAllCategoryList(CheckItemClientID)
{
var chkItem = document.getElementById(CheckItemClientID);
var the_form = window.document.forms[0];
for(var i=0; i -1)
{
if(the_form.elements[i].checked = false)
the_form.elements[i].checked = chkItem.checked;
}

}
}
}
function ConfirmDelete()
{
var the_form = window.document.forms[0];
var flagDel=1;
for(var i=0; i -1)
{
if(the_form.elements[i].checked == true)
{
flagDel=0;
break;
}

}
}
}
if(flagDel==0)
{
var DialogRes = confirm(“Are you sure you want to delete records?”);
return DialogRes;
}
else
{
alert(“Must Select Atleast One Record To Delete.”);
return false;
}
}

Take one HeaderTemplate column and add one checkbox with ID=cbheaderCategory

Take one ItemTemplate column and add one checkbox with ID=chkDeleteCategory

Add following vb.net code in code behind file
Protected Sub dgrdCategory_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgrdCategory.ItemDataBound
If (e.Item.ItemType = ListItemType.Header) Then
Dim chk As CheckBox = CType(e.Item.Cells(0).FindControl(“cbheaderCategory”), CheckBox)
chk.Attributes.Add(“onclick”, “SelectAllCheckboxesCategoryList(‘” + chk.ClientID + “‘);”)
End If

If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim chk As CheckBox = CType(e.Item.Cells(1).FindControl(“chkDeleteCategory”), CheckBox)
chk.Attributes.Add(“onclick”, “UncheckAllCategoryList(‘” + chk.ClientID + “‘);”)
End If
End Sub

To add event to check selected check boxes and confirmation message on delete button, use following code.

btnDelete.Attributes.Add(“OnClick”, “javascript: return ConfirmDelete();”)

I hope it helps you.
Thanks

Filed under: 1 ,

How to embad Images in mail body in asp.net

When we send email with images, we must have to provide phisical path of the host where our images are located.  But here is the one solution that we can embad images in email body.

Here we don’t need to provide the path. We just have to create Linked resource and Alternative view  from the mail message object. Now we just have to provide the Resource Id to Alternative view object and bind that linked resource to alternative view’s object. That’s all.  See the following code with example…

//Holds message information.
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
//Add basic information.
mailMessage.From = new System.Net.Mail.MailAddress(txtFrom.Text.Trim());
mailMessage.To.Add(txtTo.Text.Trim());
mailMessage.Subject = txtSubject.Text.Trim();

//Add image to HTML version
string path = Server.MapPath(@”Your Image Name.extention”); // my logo is placed in images folder

System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(path, “image/gif”);
imageResource.ContentId = “HDIImage”;
//Create two views, one text, one HTML.
System.Net.Mail.AlternateView htmlView = AlternateView.CreateAlternateViewFromString(“
” + txtBody, null, MediaTypeNames.Text.Html);
htmlView.LinkedResources.Add(imageResource);

mailMessage.AlternateViews.Add(htmlView);
mailMessage.IsBodyHtml = true;
//Send message
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(“Your Mail Server Name”);
//SmtpClient client = new SmtpClient(strSMTPserver);
smtpClient.Credentials = new NetworkCredential(“Username”, “Password”);
smtpClient.Send(mailMessage);

Thanks you and hope this article will help you lot’s

Filed under: 1 ,

Check file extension using regular expression in asp.net

Following is the regular expression validator that check the list of file extension.
You need to write all the extension in expression of the validator.

<asp:FileUpload ID=”txtUpload” runat=”server” />

<asp:RegularExpressionValidator ID=”RegularExpressionValidator6″ runat=”server” ControlToValidate=”txtUpload” ErrorMessage=”*”
ValidationExpression=”^.+\.((jpg)|(gif)|(jpeg)|(png)|(bmp))$”>
</asp:RegularExpressionValidator>

Hope this example helpful for you

Filed under: 1 ,

Regular expression validatior to allow only numeric value in textbox in asp.net

Following is the regular expression validator that allo only numeric value in textbox in asp.net

<asp:RegularExpressionValidator ID=”RegularExpressionValidator1″ runat=”server”
ControlToValidate=”YourControlId” CssClass=”Message” Display=”Dynamic”
ErrorMessage=”Please enter valid number.”
ValidationExpression=”\d[0-9]*” ValidationGroup=”Issue”></asp:RegularExpressionValidator>

Hope this one helpful for you

Filed under: 1 ,

Encrypt and Decrypt values in C#.Net

This article gives a brief overview of Cryptography and the Cryptography support provided by the .NET Framework. I begin by introducing Cryptography and then proceed to examine the various types of it. In particular, I review and analyze the various cryptography algorithms and objects supported by .NET. I conclude after proposing and briefly discussing the algorithmic technique that would work best for you.

Please find below a  simple code for how to do encrypt and decrypt values in c#.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
public class EncryptDecrypt
{
#region Declaration
static byte[] TripleDESKey1 = new byte[] { 51, 11, 17, 11, 31, 31, 37, 7, 23, 13, 23, 31, 43, 41, 7, 19, 91, 91, 47, 7, 37, 13, 19, 41 };
static byte[] TripleDESIV1 = new byte[] { 55, 13, 17, 31, 41, 51, 23, 7 };

#endregion

/// <summary>
/// To Encrypt String
/// </summary>
/// <param name=”value”>String To Encrypt</param>
/// <returns>Returns Encrypted String</returns>
public static string ToEncrypt(string value)
{
System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

//des.GenerateIV();
//des.GenerateKey();

des.Key = TripleDESKey1;
des.IV = TripleDESIV1;
//TripleDESKey1 = des.Key;//To Store Current Key To Use it in Decryption
//TripleDESIV1 = des.IV;//To Store Current IV To Use it in Decryption

System.IO.MemoryStream ms;

if (value.Length >= 1)
ms = new System.IO.MemoryStream(((value.Length * 2) – 1));
else
ms = new System.IO.MemoryStream();

ms.Position = 0;
System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(value);
encStream.Write(plainBytes, 0, plainBytes.Length);
encStream.FlushFinalBlock();
encStream.Close();

return Convert.ToBase64String(plainBytes);
}

/// <summary>
/// To Decrypt Data Encrypted From TripleDEC Algoritham
/// </summary>
/// <param name=”value”>String Value To Decrypt</param>
/// <returns>Return Decrypted Data</returns>
public static string ToDecrypt(string value)
{
try
{
System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
//System.IO.MemoryStream ms = new System.IO.MemoryStream(((value.Length * 2) – 1));
System.IO.MemoryStream ms;
if (value.Length >= 1)
ms = new System.IO.MemoryStream(((value.Length * 2) – 1));
else
ms = new System.IO.MemoryStream();

ms.Position = 0;
System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(TripleDESKey1, TripleDESIV1), System.Security.Cryptography.CryptoStreamMode.Write);
byte[] plainBytes = Convert.FromBase64String(value);
encStream.Write(plainBytes, 0, plainBytes.Length);
return System.Text.Encoding.UTF8.GetString(plainBytes);
}
catch (Exception ex)
{
throw ex;
}

}
}
}

Thank you

Filed under: C#.Net, Web Development , , ,

how to access active directory for authentication in c# and asp.net

Here how you will access active directory for authentication in c# and asp.net

It get the current name of your machine and compare with domain which you have defined in webconfig file.

You must have Domain name and its password so you can check your machne name in active directory of that domain.

using System.DirectoryServices;

public Boolean CheckActiveDirectory(string strUsername)
{
DirectoryEntry de = null;
DirectorySearcher searchUser = null;
DirectoryEntry localMachine = null;
DirectorySearcher search = null;

try
{
string struser = ConfigurationSettings.AppSettings["DomainUserName"];
string domainName = ConfigurationSettings.AppSettings["DomainName"];
string servername = ConfigurationSettings.AppSettings["serverpath"];
string pwd = ConfigurationSettings.AppSettings["DomainPassword"];
string domainAndUsername = strUsername;// domainName + “\\” + struser;

localMachine = new DirectoryEntry(“LDAP://” + servername, domainAndUsername, pwd);
search = new DirectorySearcher(localMachine);

search.Filter = “(&(objectcategory=user)(name=*))”;
search.SearchScope = SearchScope.Subtree;
search.PropertiesToLoad.Add(“cn”);

string userid = Convert.ToString(Session["CurrentUser"]);
string[] strUserDetails = userid.Split(‘\\’);
bool StatusFlag = false;
if (Convert.ToString(strUserDetails[0]) == domainName)
{
foreach (SearchResult sr in search.FindAll())
{
de = sr.GetDirectoryEntry();
strUsername = de.Properties["sAMAccountName"].Value.ToString();
if (Convert.ToString(strUserDetails[1]) == strUsername)
{
StatusFlag = true;
break;
}
}
}
return StatusFlag;
}
catch (Exception ex)
{
throw ex;
return false;
}
finally
{
if (de != null)
de.Dispose();
if (searchUser != null)
searchUser.Dispose();
if (localMachine != null)
localMachine.Dispose();
if (search != null)
search.Dispose();

}
}

Filed under: 1 ,

javascript’s article to insert text on focus of mouse cursor in Textbox

Here i am posting this javascript’s article to insert text on focus of mouse cursor in Textbox.

The whole concept behind this is somethng like to insert some text where your mouse cursor in other text ares.

Here i have taken one DataList control and one multiline textbox. I have filled 3 countryname in DataList control.
In ItemDataBound event of datalist control, i have set Attributes on onclick client side event, I have pass client id of control which contain the name of 3 countres and called one function insertAtCursor().

inertoncursor

Here we get the start and end points of the selection. Then we create substrings up to the start of the selection and from the end point of the selection to the end of the field value. Then we concatenate the first substring, myValue, and the second substring to get the new value.

Javascript:

<script type=”text/javascript” language=”javascript”>
function insertAtCursor(myValue)
{
if (document.selection)
{
document.getElementById(‘<%=txtBody.ClientID %>’).focus();
sel = document.selection.createRange();
sel.text = myValue;
}

else if (document.getElementById(‘<%=txtBody.ClientID %>’).selectionStart >= ’0′)
{
var startPos = document.getElementById(‘<%=txtBody.ClientID %>’).selectionStart;
var endPos = document.getElementById(‘<%=txtBody.ClientID %>’).selectionEnd;
alert(document.getElementById(‘<%=txtBody.ClientID %>’).value.substring(0, startPos) + myValue + document.getElementById(‘<%=txtBody.ClientID %>’).value.substring(endPos, document.getElementById(‘<%=txtBody.ClientID %>’).value.length));
document.getElementById(‘<%=txtBody.ClientID %>’).value = document.getElementById(‘<%=txtBody.ClientID %>’).value.substring(0, startPos)+ myValue+ document.getElementById(‘<%=txtBody.ClientID %>’).value.substring(endPos, document.getElementById(‘<%=txtBody.ClientID %>’).value.length);
}
else
{
document.getElementById(‘<%=txtBody.ClientID %>’).value += myValue;
}
return false;
}
</script>
<!–
function insertAtCursor(myValue)
{
if (document.selection)
{
document.getElementById(”).focus();
sel = document.selection.createRange();
sel.text = myValue;
}

else if (document.getElementById(”).selectionStart >= ’0′)
{
var startPos = document.getElementById(”).selectionStart;
var endPos = document.getElementById(”).selectionEnd;
alert(document.getElementById(”).value.substring(0, startPos) + myValue + document.getElementById(”).value.substring(endPos, document.getElementById(”).value.length));
document.getElementById(”).value = document.getElementById(”).value.substring(0, startPos)+ myValue+ document.getElementById(”).value.substring(endPos, document.getElementById(”).value.length);
}
else
{
document.getElementById(”).value += myValue;
}
return false;
}
// –>

Html Code:

<asp:DataList ID=”dlValues” runat=”server” OnItemDataBound=”dlDynamicHeaders_ItemDataBound”>
<ItemTemplate>
<asp:LinkButton ID=”lbtnName” CausesValidation=”false” runat=”server” Text=’<%# DataBinder.Eval(Container.DataItem,”Name”) %>’></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
<br />
<br />
<asp:TextBox ID=”txtBody” runat=”server” TextMode=”MultiLine” Width=”300″ Wrap=”true”
Height=”80″ CssClass=”marginleft”></asp:TextBox>

C#.Net Code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(“Name”);

if (!IsPostBack)
{
DataRow dr1 = dt.NewRow();
dr1["Name"] = “America”;
dt.Rows.Add(dr1);

DataRow dr2 = dt.NewRow();
dr2["Name"] = “Canada”;
dt.Rows.Add(dr2);

DataRow dr3 = dt.NewRow();
dr3["Name"] = “India”;
dt.Rows.Add(dr3);

dlValues.DataSource = dt.DefaultView;
dlValues.DataBind();
}
}
protected void dlDynamicHeaders_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton lbtnName = (LinkButton)e.Item.FindControl(“lbtnName”);
lbtnName.Attributes.Add(“onclick”, “javascript:return insertAtCursor(‘[" + lbtnName.Text.Trim() + "]‘);”);
}
}

Hope this article will help you.
Thank you

Filed under: 1

Blog Stats

  • 1,585 hits

 

January 2012
M T W T F S S
« Apr    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
Follow

Get every new post delivered to your Inbox.