HaresH Chaudhari

Freelance Web Developer

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,

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

Java script validation to enter only numeric value in textbox

Hello friends,
I am showing here hot to prevent non-numeric value in TextBox in javascripts

// Function That allow only Digits

function numbersonly(e)
{

var unicode=e.charCode? e.charCode : e.keyCode;
//if(unicode==8 || unicode==9 || unicode==46 || (unicode>=33 && unicode<=40) || unicode==45)
if(unicode==8 || unicode==9 || unicode==46)
{
return true;
}
else
{
if (unicode57) //if not a number
return false //disable key press
}
}
Hope this article helpful for you.
Enjoy!

Filed under: 1, Asp.Net, Web Development,

DotNetNuke Installation and Configuration

Hi guys,
here I am posting one good tutorials for dotnetnuke guys to how to install it and configure it in your local machine to run successfully.
You just need to follow a few steps and make your application running in your machine.

Before you start, you must have installed StarterKit and source (zip file). If you dont have it then go to dotnetnuke.com site and download two zip formatted files.

DotNetNuke_05.00.00_StarterKit
D
otNetNuke_05.00.00_Source.zip

Now unzip first zip StarterKit file and then install framework to start wok on dotnetnuke. You can not run application without installing this StarterKit.

Unzip DotNetNuke_05.00.00_Source.zip file. Go to Website folder inside unzipped file and delete development.config and rename release.config file to web.config file.

Create one database in your MS SQL Server and provide information about your database in stpe 3.

By default the virtual directory name is “DotNetNuke_Cambrian”, you can change it if you want, if you want to change it then open .sln file in notepad and change DotNetNuke_Cambrian-> your website name and save it.

Now right click on unzipped folder “DotNetNuke_05.00.00_Source” and give aspnet permission and rights. You can also set aspnet permission to website folder inside unzipped source file. See below image

aspnetpermission


    Open solution in .Net environment and build solutions, make sure it build successfully.
    Open browser and type http://your_virtual_directory_Name/Install/Installwizard.aspx

Now follow the below few steps to configure your DNN application

Step 1

When you open http://your_virtual_directory_Name/Install/Installwizard.aspx”, the installation wizard will start, here you have to click on Next button, see below image

11

Step 2

One dialog about file permission will be opened, see below image

21


We already given aspnet permission to folder if you remember, or in case if you want to check that then click on “Test Permissions”, It will show the message about permissions checked, see below image

31


now click on next

Step 3

Here, you can configure your database setting by providing Server name, database name, uid and password. Here I hope you have little bit knowledge about how we can connect sql database, so we don’t need to discuss more about this, see below image

41


now if you want to check this all information are correct then click on “Test Database Connection” button, it will show message for success or failure, see below image

51


now click “Next”

Step 4

Here, one progress bar appeared and show the progress of installing database in your SQL server

61


once it will completed, it show the success message and then you can click on “Next”

Step 5

Here you have to configure your host account information to access the admin section of your site. You have to submit Username, Password, Confirm Password and Email Address, see below image

71


You can also set your smpt setting for sending mails. You have to enter your SMTP address and test it by clicking on “Test SMTP Settings” button, see below image

81


It show the success message if your SMTP address correct, if its correct then it send one test mail on your host email address. Now, click on “Next”

Step 6

Here you have to configure your admin account information and Portal Name, its little bit same as above step 5.

91


Click on “Next”

Step 7

Congratulations. Your DNN project is ready to run in your machine. See below image and click on “Finished (Goto Site)” button, It redirect to your site’s home page.

101

Its completed.
If you want to contact me , please feel free to send me mail on hareshfchaudhari@gmail.com

Hope this article will help you to install and configure DotNetNuke application.

Filed under: 1, , , , , ,

Blog Stats

  • 1,762 hits

 

May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Follow

Get every new post delivered to your Inbox.