Wednesday, February 6, 2013

SQL function for getting mid string


CREATE function [dbo].[MidString](@string varchar(100))
RETURNS varchar(100)
as
begin
Declare @strtloc int
Declare @endloc int
declare @result varchar(50)
set @strtloc = charindex('|',@string)+1
set @endloc = charindex('|',substring(@string,@strtloc,len(@string)))-1
if @endloc = -1
begin
set @endloc=len(@string)
end
set @result=substring(@string,@strtloc,@endloc)
return @result
end

Wednesday, January 23, 2013

Convert Datareader to Datatable in asp.net



using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    IDataAdapter da;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(string));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        DataRow drQuery;
      
      
        da = getReader();

        da.Fill(ds);
        int QCount1 = 0;
        while (QCount1 < ds.Tables[0].Rows.Count)
        {
            drQuery = dt.NewRow();

            drQuery["ID"] = Convert.ToString(ds.Tables[0].Rows[QCount1][1].ToString());
            drQuery["Name"] = ds.Tables[0].Rows[QCount1][3].ToString();
            drQuery["Age"] = ds.Tables[0].Rows[QCount1][2].ToString();
            drQuery["Address"] = ds.Tables[0].Rows[QCount1][9].ToString();
            dt.Rows.Add(drQuery);
            QCount1 = QCount1 + 1;
        }
      
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    private IDataAdapter getReader()
    {
     
    
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["testcon"].ToString());
        SqlDataAdapter da = new SqlDataAdapter("select * from t_users",con);
      


        return da;
    }
}



Thursday, January 17, 2013

Cross-Site Scripting Protection in ASP.NET(A potentially dangerous Request.Form value was detected from the client)

This is basically to  catches malicious scripting code used by hacker.This is simply done in ASP.net by using a filter....
We need to add this in webconfig file as: 



<configuration>
    <system.web>
        <httpModules>
            <add name="ValidateInput" 
               type="Corillian.Web.ValidateInput,ValidateInputASPNET10" />
        </httpModules>
    </system.web>
</configuration>




For more reference use this link
http://msdn.microsoft.com/en-us/library/ms972967.aspx


Tuesday, January 15, 2013

How to Enable TLS for SMTP Authentication ?

I have made a function for sending email and inside here smtp client object is created and set TLS for it



public Boolean SendMailNew(string filename, bool isAttach)
        {
            mailSent = false;
            Boolean IsSuccess = false;
            try
            {

                MailAddress senderAddress = new MailAddress(fromAddress, fromWhom);
                MailMessage message = new MailMessage();
                string messageString = "";
                message.From = senderAddress;
                string[] toAddressArray = ToAddressArray(toAddress);
                foreach (string recAddress in toAddressArray)
                {
                    message.To.Add(new MailAddress(recAddress, recAddress));
                }

                if (ccAddress != null && ccAddress.Trim().Length > 0)
                {
                    string[] ccAd = ToAddressArray(ccAddress);
                    foreach (string ccAddStr in ccAd)
                    {
                        MailAddress ccAddr = new MailAddress(ccAddStr);
                        message.CC.Add(ccAddr);
                    }
                }

                if (bccAddress != null && bccAddress.Trim().Length > 0)
                {
                    string[] bccAd = ToAddressArray(bccAddress);
                    foreach (string bccAddStr in bccAd)
                    {
                        MailAddress bcc = new MailAddress(bccAddStr);
                        message.Bcc.Add(bcc);
                    }
                }

                string path = ConfigurationSettings.AppSettings["ImagePath"].ToString();

                LinkedResource lnkResource1 = new LinkedResource(path + "header1.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource1.ContentId = "headerPict1";
                LinkedResource lnkResource2 = new LinkedResource(path + "dotted.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource2.ContentId = "dottedPict1";
                LinkedResource lnkResource3 = new LinkedResource(path + "footer.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource3.ContentId = "footerPict1";
                LinkedResource lnkResource4 = new LinkedResource(path + "f.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource4.ContentId = "fPict1";
                LinkedResource lnkResource5 = new LinkedResource(path + "t.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource5.ContentId = "tPict1";
                LinkedResource lnkResource6 = new LinkedResource(path + "yt.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource6.ContentId = "ytPict1";
                LinkedResource lnkResource7 = new LinkedResource(path + "l.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource7.ContentId = "lPict1";
                LinkedResource lnkResource8 = new LinkedResource(path + "robot.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource8.ContentId = "RobotPict1";

                ContentType ct = new ContentType();
                ct.MediaType = MediaTypeNames.Text.Html;
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(messageBody, ct);

                htmlView.LinkedResources.Add(lnkResource1);
                htmlView.LinkedResources.Add(lnkResource2);
                htmlView.LinkedResources.Add(lnkResource3);
                htmlView.LinkedResources.Add(lnkResource4);

                htmlView.LinkedResources.Add(lnkResource5);
                htmlView.LinkedResources.Add(lnkResource6);
                htmlView.LinkedResources.Add(lnkResource7);
                htmlView.LinkedResources.Add(lnkResource8);
                message.AlternateViews.Add(htmlView);

                messageString = messageBody;
                message.Subject = subjectLine;

                if (isAttach)
                {
                    Attachment attach = new Attachment(filename);
                    // Add time stamp information for the file.
                    ContentDisposition disposition = attach.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(filename);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(filename);
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(filename);
                    // Add the file attachment to this e-mail message.
                    message.Attachments.Add(attach);
                }
               

                message.IsBodyHtml = true;
                message.Body = messageString;
             
                //NetworkCredential loginInfo = new NetworkCredential(ConfigurationSettings.AppSettings["UserId"].ToString(), ConfigurationSettings.AppSettings["Password"].ToString());
                //SmtpClient client = new SmtpClient("pod51014.outlook.com", 587);
               
                //client.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["SMTPport"]);
                //client.EnableSsl = true;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //client.UseDefaultCredentials = false;
                //client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //client.Credentials = loginInfo;

                SmtpClient client = new SmtpClient(smtpClientString);
                client.EnableSsl = true;
               //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);


                client.Send(message);
                message.Attachments.Clear();
                message.Dispose();

                return (IsSuccess = true);

            }
            catch (Exception exc)
            {
                exc.ToString();
                return IsSuccess;
                //throw exc;
            }
        }


======================

Add the setting in webconfig file,Here from adress address must be same as user name

<system.net>
<mailSettings>
<smtp from="abc@test.net" deliveryMethod="Network">
<network userName="abc@test.net" password="5ama" host="po.outlook.com" port="587" />
</smtp>
</mailSettings>
</system.net>



Thursday, December 20, 2012

Javascript for character count on keypress

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


maxL = 1000;
    var bName = navigator.appName;
    function taLimit(taObj) {
        if (taObj.value.length == maxL) return false;
        return true;
    }

    function taCount(taObj, Cnt) {
        objCnt = createObject(Cnt);
        objVal = taObj.value;
        if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
        if (objCnt) {
            if (bName == "Netscape") {
                objCnt.textContent = maxL - objVal.length;
            }
            else { objCnt.innerText = maxL - objVal.length; }
        }
        return true;
    }
    function createObject(objId) {
        if (document.getElementById) return document.getElementById(objId);
        else if (document.layers) return eval("document." + objId);
        else if (document.all) return eval("document.all." + objId);
        else return eval("document." + objId);
    }


 </script>


==================
It is used like as mention below


 <asp:TextBox ID="txtImportaintInfo" runat="server" TextMode="MultiLine"
                                    CssClass="textarea_field2" Width="681px" onpaste="return false" onkeypress="return taLimit(this)" onkeyup="return taCount(this,'myCounter1')"></asp:TextBox>
                                   
<br />     You have <b><span id="myCounter1">1000</span></b>
                                characters remaining for your description...</td>

Tuesday, December 4, 2012

How to convert Sesstion object to array,arrylist in asp.net

converting sesstion to arry

 string[] arrFile = (string[])Session["arrFile"];

converting sesstion to arraylist

 Arraylist arrFile = (Arraylist)Session["arrFile"];

Adding Symbol like as ❏ and ❑ with string in asp.net

There is two sysbole  with shadow:

&#x274f;
&#x2751;

as ❏ and ❑

You can use it  and display like :


❏ Organising necessary form of order to transfer county court possession order to the High Court

❏ Shergroup Legal to attend High Court in London to organisecollection of necessary paperwork

❏ Experienced eviction locksmith on site to change locks and deal with roller shutters etc

❏ Shergroup Security to handle post eviction security services

❏ Shergroup Security to arrange post eviction cleansing

❏ Shergroup Security Risk Assessment Report to highlight measures to prevent further trespass or damage to      property

❏ Any other service not listed here – let us help you complete your eviction process


For this i have use various check box tick value and concatenated and displayed with this function

 private string ConcatCheckBoxText(CheckBox chkBox)
    {
        string str = chkBox.Checked ? "&#x274f; " + chkBox.Text + "<br/><br/>" : "";
        return str;
    }

This bold value in above function is responsible for adding these symbols  ❏ and ❑  in c#