Sunday, June 29, 2014

get checkbox checked in gridview in asp.net

 foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
                if (chkRow.Checked)
                {
                    string name = row.Cells[1].Text;
               
                }
            }
        }

convert datetime format to date only in asp.net

  string sessionscheduleid, sessionname, sessionid, duration, startdate, enddate;
            DateTime fromdate, todate;
     
            fromdate = Convert.ToDateTime(hdffromdate.Value);
            todate = Convert.ToDateTime(hdftodate.Value);

            startdate = fromdate.ToShortDateString();
            enddate = todate.ToShortDateString();

send multiple parameters to javascript in asp.net

<a href="#" onclick="BindSessionId('<%#Eval("ID") %>','<%#Eval("SessionName") %>','<%#Eval("fromDate") %>','<%#Eval("toDate") %>','<%#Eval("SessionID") %>');"
                                                                            data-reveal-id="myModal" data-animation="fade">Invite </a>


 function BindSessionId(sessionscheduleid, sessioname, fromdate, todate, sessionid) {
            alert(sessionid);
            $('input[id$=hdfsessionid]').val(sessionid);
            $('input[id$=hdfsessionscheduleid]').val(sessionscheduleid);
            $('input[id$=hdfsessionname]').val(sessioname);
            $('input[id$=hdffromdate]').val(fromdate);
            $('input[id$=hdftodate]').val(todate);
        }

send mail in asp.net with attachment and images

   MailMessage m = new MailMessage();
            SmtpClient sc = new SmtpClient();

            try
            {
                m.From = new MailAddress("from@gmail.com", "Shekhar");
                m.To.Add(new MailAddress("snawale@curologic.com", "Amit"));
                // m.CC.Add(new MailAddress("CC@yahoo.com", "Display name CC"));
                //similarly BCC


                m.Subject = " This is a Test Mail";
                m.IsBodyHtml = true;
                m.Body = "Phone number - 9822647640";




                /* // Send With Attachements.
                FileStream fs = new FileStream("E:\\TestFolder\\test.pdf",
                                   FileMode.Open, FileAccess.Read);
                Attachment a = new Attachment(fs, "test.pdf",
                                   MediaTypeNames.Application.Octet);
                m.Attachments.Add(a);
                 */




                /* // Send html email wiht images in it.
                string str = "<html><body><h1>Picture</h1><br/><img
                                 src=\"cid:image1\"></body></html>";
                AlternateView av =
                             AlternateView.CreateAlternateViewFromString(str,
                             null,MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg",
                             MediaTypeNames.Image.Jpeg);
                lr.ContentId = "image1";
                av.LinkedResources.Add(lr);
                m.AlternateViews.Add(av);
                 */


                sc.Host = "smtp.gmail.com";
                sc.Port = 587;
                sc.Credentials = new
                System.Net.NetworkCredential("from@gmail.com", "password");
                sc.EnableSsl = true;
                sc.Send(m);


                Response.Write("Email Send sucessfully");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

code for Send mail in asp.net

 MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("from@gmail.com");
            mail.To.Add("send@curologic.com");
            //mail.To.Add("toaddress2@gmail.com");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";

            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";

            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";

            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("from@gmail.com", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

Friday, June 27, 2014

How to Get Window NT Logged User Name Using ASP.NET



1) System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string strName = p.Identity.Name;


2) string strName = HttpContext.Current.User.Identity.Name.ToString();


3string strName = Request.ServerVariables["AUTH_USER"]; //Finding with name

string strName = Request.ServerVariables[5]; //Finding with index

set hiddenfield value in jquery

  function BindSessionId(id) {
            $('input[id$=hdfsessionid]').val(id);
        }

Wednesday, June 25, 2014

Get Year Only from date in javascript

var startYear = new Date().getFullYear();

Append in jquery

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
  });

  $("#btn2").click(function(){
    $("ol").append("<li>Appended item</li>");
  });
});
</script>
</head>

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>

Sunday, June 22, 2014

Remove all commas from string in jquery

 var income = $("#txtincome").val(); //12,000
 income = income.replace(/\,/g, '');//12000

Friday, June 20, 2014

make checkbox checked in jquery on dropdown on change

 $("#ddlCladded").change(function () {
            var ddlCladdedval= parseInt($("#ddlCladded").val());
            if(ddlCladdedval==1){
                     $('#chkCladded').prop('checked',true);
            }
            else{
                     $('#chkCladded').prop('checked',false);
            }        
        });

dropdown on change event and current dropdown value

 $("#ddlCladded").change(function () {
            var ddlCladdedval= parseInt($("#ddlCladded").val());
         
        });

Thursday, June 19, 2014

check if string is empty in javascript

function isEmpty(str) {
            return (!str || 0 === str.length);
        }

check for nan javascript

The isNaN() function returns true if the value is NaN (Not-a-Number), and false if not.

var a = isNaN(123) + "<br>";
var b = isNaN(-1.23) + "<br>";
var c = isNaN(5-2) + "<br>";
var d = isNaN(0) + "<br>";
var e = isNaN("Hello") + "<br>";
var f = isNaN("2005/12/12") + "<br>";

false
false
false
false
true
true

how to remove read only attribute of textbox control through codebehind using asp.net

 txtusername.Attributes.Remove("readonly");

Wednesday, June 18, 2014

Get Data From datatable

DataTable dt = new DataTable();
            dt = _newleadspresenter.getAllLeaddata(LeadId);

string s = dt.rows[0].itemarray[0];

Read From Sqldatareader in asp.net

cmdstr = @"SELECT UserName, FirstName, MiddleName, LastName, Phone, Email, Profession, CategoryId, ReferredBy, LeadCategoryId, BirthDate, MaritalStatus, Note
                           FROM  Lead
                           WHERE (LeadId = " + LeadId + ")";
                myConnection.Open();
                SqlCommand cmd = new SqlCommand(cmdstr, myConnection);
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {

                    txtusername.Text = reader.GetString(0);                  

                    txtfirstname.Text = reader.GetString(1);

                    txtmiddlename.Text = reader.GetString(2);

                    txtlastname.Text = reader.GetString(3);

                    txtphone.Text = reader.GetString(4);

                    txtemail.Text = reader.GetString(5);

                    txtprofession.Text = reader.GetString(6);

                    ddlcategory.SelectedValue = reader.GetString(7);

                    ddlstatus.SelectedValue = reader.GetString(9);

                    txtbirthdate.Text = reader.GetString(10);

                    ddlmaritalstatus.SelectedValue = reader.GetString(11);

                    txtnote.Text = reader.GetString(12);

                }

                myConnection.Close();

            }

jquery check val is empty

if($('#person_data[document_type]').val() != ''){}

scriptmanager does not exist in the current context

add using System.Web.UI;

Tuesday, June 17, 2014

Common Session methods Use By Creating separate class

 //added by shekhar 13/6/2014 To Clear Current Session
        public void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }
        //End Of Clear Session
        //added by shekhar 13/6/2014 To Remove item in session
        public void RemoveFromSession(string key)
        {
            HttpContext.Current.Session.Remove(key);
        }
        //end Of remove  

        public void SetInSession(string key, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

        public object GetFromSession(string key)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return null;
            }
            return HttpContext.Current.Session[key];
        }

        public void UpdateInSession(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

use httpcontext and server mappath in a c# class library

1) add using System.Web;

2)string  filePath = HttpContext.Current.Server.MapPath("~/TextFiles/StylePath.txt");

Monday, June 16, 2014

Access asp.net session value in javascript

 var Guest = '<%=HttpContext.Current.Session["Advisorguest"]%>';

Common Logic For Getting Single Value From Database Asp.Net

1)  string[,] param1 = new string[1, 2];
                param1[0, 0] = "@userName";
                param1[0, 1] = username;

2) string status = CommonClass.Common.Instance.getSingleValue("checkIsExistUserName", param1);

3)  SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ValweaveFa"].ConnectionString);
        SqlCommand sm;
public string getSingleValue(string procNm, string[,] paramVal)
        {
            try
            {
                myConnection.Open();
                sm = new SqlCommand(procNm, myConnection);
                sm.CommandType = CommandType.StoredProcedure;

                for (int i = 0; i < paramVal.Length / 2; i++)
                {
                    if ((paramVal[i, 0] != null) && (paramVal[i, 1] != null))
                        sm.Parameters.Add(paramVal[i, 0], paramVal[i, 1]);
                }
                string Password = Convert.ToString(sm.ExecuteScalar());
                myConnection.Close();
                return Password;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Thursday, June 12, 2014

Always Add Two connection strings in ASP.NET Web.config

1) <add name="read" connectionString="Data Source=Test\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=false;uid=userid; password=password#123; Persist Security Info=True;" providerName="System.Data.SqlClient"/>

Use This Connection string for Read data from database

2) <add name="readandwrite" connectionString="Data Source=Test1\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=false;uid=userid1; password=password#1234; Persist Security Info=True;" providerName="System.Data.SqlClient"/>

Use This for Read and write data from and to database

3) With use of this performance will get better.

4)  TO get better Security

Tuesday, June 10, 2014

Best Site For ASP.NET Sample projects,code and developement

1) Go To http://www.packtpub.com/

2) In Menu -> Under Support -> Code Download and Errata

3) Select ASP.Net 4 social networking

4) Or you can download other projects

5) This projects are best you will really love it and you will enjoy it while coding

Configuration-Specific web.config Files

Managed Extensibility Framework

Managed Extensibility Framework:
Three core concepts with MEF:
1)      Export(s) : It exposes Contracts and contract like .NET Interface or Class or property
Code:
[Export(typeof(ICache))]
Public class Caching: ICache
{
               Public object Get(string cache_key)
{
               //Caching implementation
}
}
2)      Imports: Used to consume exported instances.
Code:
[Import()]
Private ICache cache;
3)      Catalog: hosts components that need to be composed.
Code:
Public static void Compose(object o)
{
               var container = new CompositionContainer(
                                             new DirectoryCatalog(Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
@”bin\MEFBin”)));
                              Var batch = new CompostionBatch();
batch.AddPart(o);
               container.Compose(batch);

}

Monday, June 9, 2014

Application Design - Layered Architecture

 Layered Architecture:
           1)      Presentation Layer - User Interface of application
           2)      Business Logic Layer – Rules of application
           3)      Data Access Layer – Responsible for connecting to data source and interacting with data that is stored in that location.
e.g. database, some XML files, text files or web service.  
4)   Utility /Components Layer – Mechanism of caching, logging errors, reading from configuration files.
Create independent project called Component layer   

           a)      Presentation layer – Web
           b)      Business layer – entities, business logic, components, interfaces
           c)      Data Layer – Entities, Data Access
           d)      Components Layer – Caching, logging, Configuration