Archive

Archive for June, 2012

Rebinding events in jQuery after Ajax update (updatepanel)


Some time we use update panel and $(document).ready(function() {});function of jquery in same page . Then whatever written inside $(document).ready(function() {});not work once we have done or performed partail post back because script inside $(document).ready(function() {}); is not bound with the page .So in this Scenario we have two option for solving the problem for the same.

  1. PageLoad event handler
  2. endRequest event of the PageRequestManager class

let see implementation of both one by one.

Using PageLoad event handler

Since we’re using ASP.NET AJAX,we’ll have access to a pageLoad event handler,that gets called each time the page posts back, be it full or partial from an UpdatePanel.You just need to put this function into your page.


function pageLoad(sender, args)
{
if (args.get_isPartialLoad())
{
//Specific code for partial postbacks can go in here.
}
}

just place your entire  $(document).ready(function() {}); inside pageLoad event handler , now our problem solved.like this.

function pageLoad(sender, args) {
$(document).ready(function() {

$("input[id$=btnMail]").click(function() {
if ($("input[id$=txtMailingList]").val() == '') {
alert('Please enter e-mail Address');
return false;
}
else if ($("input[id$=txtMailingList]").val() != '') {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var eaddress = document.getElementById("<%=txtMailingList.ClientID %>").value;
if (reg.test(eaddress) == false) {
document.getElementById("<%=txtMailingList.ClientID %>").focus();
alert('Please enter valid email address.');
return false;
}
}
});

});
}

using endRequest event of the PageRequestManager class

endRequest event Raised after an asynchronous postback is finished and control has been returned to the browser. way of using :

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(endRequestHandler)

Hope this will help you in solving your problem . if it help leave a comment it encourage to write more on issue.

Advertisements
Categories: ASP.NET, JQuery Tags: ,

Sending email in asp.net

June 8, 2012 2 comments

Sending email’s from web applications is a very common requirement in most projects irrespective of any language site is deveoped .This article explores how to send Emails in ASP.NET  with attachments with gmail account and using custome host address.

Mail Sending using custome host address

using System.Net.Mail;
MailMessage mail = new MailMessage();
mail.To.Add("sToEmail");
mail.From = new MailAddress("sFromEmail");
if (sCCEmail.ToString() != "")
{
mail.CC.Add(sCCEmail");
}
if (sBCCEmail.ToString() != "")
{
mail.Bcc.Add("sBCCEmail");
}
mail.Subject = "put whatever subject you want to give"
mail.Body = "Your complete message you wanna share ";
mail.IsBodyHtml = true/false
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.abc.com" //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential(userName, password); //Or your Smtp Email ID and Password

smtp.EnableSsl = true/false
mail.Priority = System.Net.Mail.MailPriority.High;
mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure;

// want attachment in mail
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
mail .Attachments.Add(attach);
smtp.Send(mail);

Sending Email Using Gmail In ASP.NET.

if you don’t have a working smtp server to send mails than sending
e-mail with Gmail is best option.Otherwise use of it should be avoided
because it has some limitation like.

using System.Net.Mail;
MailMessage mail = new MailMessage();
mail.To.Add("toemailAddress");
mail.From = new MailAddress("yourid@gmail.com");
mail.Subject = "put whatever subject you want to give";
string Body = " ";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

If your are getting error mentioned below “The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.”

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file

<system.net>
<defaultProxy>
<proxy proxyaddress="ProxyIpaddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587

smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("emailid@gmail.com","GmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

If it help you solving your problem then give comment or if any wrong in this then let me know i will rectify.

Categories: ASP.NET

Keep session alive as long as you want


Most of the time we face problem of session time out . for this there are number of  options are available to solve this like:

Using Web.config file 

<system.web>
    <sessionState mode=”InProc” cookieless=”false” timeout=”15″>
    </sessionState>
</system.web>
 
 Set session timeout in Global.asax
void Session_Start(object sender, EventArgs e)
{
  // Code that runs when a new session is started
  Session.Timeout = 15;
}
 Set session timeout in IIS

Open IIS manager by typing inetmgr in Start > run in windows.
Right click on websites > Select Properties.

Go to ASP.NET tab, Click on Edit Configuration.
Click on State Management Tab, Set Session TimeOut value (In Minutes).

however all this option not work in some cases or you can say most of the time it does not works. so there is other option for same .

Using Web.config file 

<sessionState mode=”InProc” stateConnectionString=”tcpip=127.0.0.1:42424″
 sqlConnectionString=”data source=127.0.0.1;Trusted_Connection=yes” cookieless=”false” timeout=”60″/>

Using asp.net handler

step 1) Write a handler

using System;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myservice: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string ulname = context.Request.QueryString[“ulname”];
string ultype = context.Request.QueryString[“ultype”];
if (ultype == “a”)
{
context.Session[“UserUniqueIdAdmin”] = ulname;
}
if (ultype == “u”)
{
context.Session[“UserUniqueId”] = ulname;
}
if (ultype == “b”)
{
context.Session[“UserUniqueId”] = ulname;

}
}

public bool IsReusable
{
get
{
return false;
}
}

now you have written handler , call it from master page or any page using this java script

  <script language=”javascript” type=”text/javascript”>
        $(function() {
            setInterval(myservice123, 10000);
        });
 
        function myservice123() {
            $.post(“../myservice.ashx?ultype=a&ulname=

         ” + $(‘#<%     = dn_uid.ClientID %>’).val(), null, function() {
                alert($(‘#<%= Hdn_uid.ClientID %>’).val());
            });
        }   
    </script>

}

Hope this will solve your problem , comment is welcome for any error in this or any thing you like to share. comment encourage  to write more on issue.

 
 

Categories: ASP.NET Tags:

Convert a dataset into IEnumerable

June 5, 2012 2 comments

convert a dataset information into a IEnumerable collection
Create a user class
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}

private List<User> userList = null;
userList = dataSet.Tables[0].AsEnumerable()
.Select(row => new User
{
UserID = row.Field<int>(“userid”),
UserName = row.Field<string>(“username”),
Password = row.Field<string>(“password”)
}).ToList();

}
if it help , leave a comment please.

Categories: ADO.NET Tags:
%d bloggers like this: