HaresH Chaudhari

Freelance Web Developer

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

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 , , , , , ,

How to get Image Size (Width and Height) in VB.Net

Here you will get your uploading Image Width and Height. Just take namespaces and one bitmap object and set some properties and finally you will get width and height of your image

Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D

Dim LogoHeight, LogoWidth As Double
Dim obj As Bitmap

obj = New Bitmap(YourFileUploaderControlID.PostedFile.InputStream, False)

LogoHeight = obj.Height ‘ Your Image Height
LogoWidth = obj.Width ‘Your Image Width

Filed under: 1 ,