Thursday, October 22, 2009

Mail sending using .net

public bool SendEmail(clsmail objmail)
{

try
{
MailMessage mymessage = new MailMessage();
mymessage.From = new MailAddress(objmail.From);
mymessage.To.Add(new MailAddress(objmail.To));
if (objmail.Cc != null && objmail.Cc != string.Empty)
mymessage.CC.Add(new MailAddress(objmail.Cc));
if (objmail.Bcc != null && objmail.Bcc != string.Empty)
mymessage.Bcc.Add(new MailAddress(objmail.Bcc));
//mymessage.Bcc.Add(new MailAddress("keone@oceanviewdubai.com"));
mymessage.ReplyTo = new MailAddress(objmail.From);
mymessage.Subject = objmail.Subject;
mymessage.Body = objmail.Body;
mymessage.IsBodyHtml = true;
mymessage.Priority = MailPriority.Normal;
if (objmail.FilePath != null)
{
mymessage.Attachments.Add(new Attachment(objmail.FilePath));
}
SmtpClient myclient = new SmtpClient();
myclient.Send(mymessage);
return true;
}
catch
{
return false;
}

}

Mail With embeded email


public bool SendEmbeddedImageEmail(clsmail objmail)
{
try
{
MailMessage mymessage = new MailMessage();
mymessage.From = new MailAddress(objmail.From);
mymessage.To.Add(new MailAddress(objmail.To));
if (objmail.Cc != null && objmail.Cc != string.Empty)
mymessage.CC.Add(new MailAddress(objmail.Cc));
if (objmail.Bcc != null && objmail.Bcc != string.Empty)
mymessage.Bcc.Add(new MailAddress(objmail.Bcc));
mymessage.ReplyTo = new MailAddress(objmail.From);
mymessage.Subject = objmail.Subject;
AlternateView plainTextView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(objmail.Body, null, "text/plain");
AlternateView view = AlternateView.CreateAlternateViewFromString(objmail.Body + Environment.NewLine + "", null, "text/html");
LinkedResource imageResource = new LinkedResource(objmail.FilePath);
imageResource.ContentId = "EMDImage";
view.LinkedResources.Add(imageResource);
mymessage.AlternateViews.Add(plainTextView);
mymessage.AlternateViews.Add(view);
SmtpClient myclient = new SmtpClient();
myclient.Send(mymessage);
return true;
}
catch
{
return false;
}
}

Password encrypt decrypt in C#.net

public string Encrypt(string plainText)
{
string passPhrase = "Prajeeshkarayil"; // can be any string
string saltValue = "#!Prajeeshkarayil*#33~"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c0D4e0F6g7H8"; // must be 16 bytes
int keySize = 192; // can be 192 or 128
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 12);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText.Replace("=", "EQ").Replace("?", "QS").Replace("+","PS");
}
public string Decrypt(string cipherText)
{
if (cipherText != null)
{
string passPhrase = "Prajeeshkarayil"; // can be any string
string saltValue = "#!Prajeeshkarayil*#33~"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c0D4e0F6g7H8"; // must be 16 bytes
int keySize = 192; // can be 192 or 128
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText.Replace("EQ", "=").Replace("QS", "?").Replace("PS","+"));
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 12);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
return plainText;
}
return ("");
}

Check/Uncheck all check box using java script

Html code


< input type="checkbox" class="pTable" id="Checkbox1" onclick="checkedAllnonsurgical(this);" runat="server" > Select All

Java script


< script type="text/javascript" language="javascript" >
function checkedAll(e) {
var aa = document.forms[0];
var checked = e.checked
for (var i = 0; i < aa.elements.length; i++) {
var ValId = aa.elements[i].id;
if (ValId.indexOf('chkp') != -1) {
aa.elements[i].checked = checked;
}
}

}
< script >

Friday, September 18, 2009

Country State Ajax binding using ASP.Net

How to bind a State drop down list on change of country drop down list

First we need a to create simple Ajax xmlHttp object and get Which country is selected by using java script. Pass Country to server side Script/page, select all the states with in that country from Data base and pass it to client side using the same xmlHttp
(System.Web.HttpContext.Current.Response.Write("All States"))
server side page name ajaxState.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="StateTableAdapters" %>


<%@ Import Namespace="System.Data" %>


<%
        if (Request.QueryString["Country"] != null)
        {


            String Country = Request.QueryString["Country"].ToString();            StateTableAdapter obpincode = new StateTableAdapter ();nbsp;  DataTableReader Dtr = obpincode.SelectByDt(Country).CreateDataReader() ;


StringBuilder strAllStaters = new StringBuilder();


            strddl.Append(" <select id=selState' style='border: 1px solid DarkBlue; width: 150px;'>");
             strddl.Append("<option value=\"0\">");                strddl.Append("Select One");strddl.Append("</option>");

            while(Dtr.Read()) {strddl.Append("<option value=" + Dtr["Country _Id"].ToString() + ">");
strddl.Append(Dtr["Country "].ToString());strddl.Append("</option>");
}

strddl.Append("</select>");System.Web.HttpContext.Current.Response.Expires = -1;


System.Web.HttpContext.Current.Response.Write(strAllStaters);
>        }


%>
<script type="text/javascript">


function ajaxFunction() {
var xmlHttp;
               try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari


}
               catch (e) { // Internet Explorer


                   try {                       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");


                   }                   catch (e) {                       try {


                           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                       }                       catch (e) {                           alert("Your browser does not support AJAX!");                           return false;                       }                   }               }               xmlHttp.onreadystatechange = function() {                   if (xmlHttp.readyState == 4) {                       document.getElementById("divState").innerHTML = xmlHttp.responseText;                   }


               }               var OId = 0;


               if (document.getElementById('selCountry’).selectedIndex > 0)                   OId = document.getElementById('selCountry’).value;                              xmlHttp.open("GET", "ajaxState.aspx?CId=" + OId, true);               xmlHttp.send(null);           }</script>
Note:I am setting the respose text to innerHTML of a div (selDiv)
document.getElementById("divState").innerHTML = xmlHttp.responseText;

Thursday, September 17, 2009

Refresh Parent window from Child window after postback/Submit

set window.opener = self;
then change location window.opener.location.href ="URL"

<script language="javascript" type="text/javascript">

    function close1() {

        window.opener = self;

        window.opener.location.href = "http://URL";

        window.close();

       

    }

</script>

Filtered text field using javascript

<script type="text/javascript" language="javascript">

    function getkey(e) {

        if (window.event)

            return window.event.keyCode;

        else if (e)

            return e.which;

        else

            return null;

    }

    function goodchars(e, goods) {

        // alert(e.value);

        var key, keychar;

        key = getkey(e);

        if (key == null) return true;

        keychar = String.fromCharCode(key);

        if (goods.indexOf(keychar) != -1)

            return true;

        if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27 || key == 40 || key == 41 || key == 32 || key == 45)

            return true;

        return false;

    }

</script>


<input name="textfield5" type="text" class="pTable" id="textPrimphone" runat="server" onkeypress="return goodchars(event,'1234567890')" />

How to validate checkbox inside CreateUserwizard Control/Wizard control ?

Validate checkbox inside Wizard step
We need a custom validator and a small client side javascript
<asp:WizardStep runat="server"
AllowReturn="False">


<asp:CheckBox ID="chkterm"
runat="server"
/>I agree with the Terms and Conditions


<asp:CustomValidator ID="CustomValidatorAgree"
runat="server"
ClientValidationFunction='validatechkbox'

ControlToValidate="txtinterest" ErrorMessage="Please read and agree Terms and Conditions" ValidateEmptyText="True"></asp:CustomValidator>

</asp:WizardStep>
< script language="javascript" type="text/javascript"> function validatechkbox(obj, args) {

var controlID1 = '<%= chkterm.ClientID %>';var checkbox = document.getElementById(controlID1); args.IsValid = checkbox.checked;} </script>

Note :Set the ControlToValidate validate property of custom validator to any other controles in the formValidate checkbox inside CreateUserWizard<asp:CreateUserWizard ID="CreateUserWizard1" runat="server">            <WizardSteps>                <asp:CreateUserWizardStep runat="server">                    <ContentTemplate>


<asp:CheckBox ID="chkterm" runat="server" /><asp:TextBox runat="server" ID="txtvalidate" Text="I agree with the Terms and Conditions" ReadOnly ="true" Width="250px" ></asp:TextBox><asp:CustomValidator ID="CustomValidatorAgree" runat="server" ClientValidationFunction='validatechkbox'
ControlToValidate="txtvalidate" ErrorMessage="Please read and agree Terms and Conditions" ValidateEmptyText="True" Display="Dynamic" ValidationGroup="CreateUserWizard1" ></asp:CustomValidator>
<script language="javascript" type="text/javascript">


        function validatechkbox(obj, args) {            var controlID1 = 'CreateUserWizard1_CreateUserStepContainer_chkterm';
            var checkbox = document.getElementById(controlID1);           args.IsValid = checkbox.checked;
}</script>

How to validate ImageButton through W3C ?

This is a problem caused by W3C running validation whilst reading the HTML rendered for a simple broswer like netscape, Image button's source code render like this
<asp:ImageButton ID="IbSubmit" CssClass="class" BorderWidth="0px" runat="server" ImageUrl="~/images/img1.jpg" />
The "BorderWidth="0px" " is aproblem it wont validate through W3C .
Try the following
Right click on the project folder and Add App_Browsers folder (select it from Add Asp.NET Folder)
Right click on the App_Browsers folder and choose Add New Item and add Browser File
Its content like this

<browsers>

<browser id="NewBrowser" parentID="Mozilla">

<identification>

<userAgent match="Unique User Agent Regular Expression" />

identification>

<capture>

<userAgent match="NewBrowser (?'version'\d+\.\d+)" />

capture>

<capabilities>

<capability name="browser" value="My New Browser" />

<capability name="version" value="${version}" />

capabilities>

browser>

<browser refID="Mozilla">

<capabilities>

<capability name="xml" value="true" />

capabilities>

browser>

<browser id="w3cValidator" parentID="default">

<identification>

<userAgent match="^W3C_Validator" />

identification>

<capture>

<userAgent match="^W3C_Validator/(?'version'(?'major'\d+)(?'minor'\.\d+)\w*).*" />

capture>

<capabilities>

<capability name="browser" value="w3cValidator" />

<capability name="majorversion" value="${major}" />

<capability name="minorversion" value="${minor}" />

<capability name="version" value="${version}" />

<capability name="w3cdomversion" value="1.0" />

<capability name="xml" value="true" />

<capability name="tagWriter" value="System.Web.UI.HtmlTextWriter" />

capabilities>

browser>

browsers>