Monday, September 20, 2010

Send Email to Admin on new user creation - via code behind

if you are using simple registration than you can write the code on register button click.If you are using membership api
than you can write the code oon createduser event.This is the code which i am using in my site.
 protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
       {
           UserBAL objuserBAL = new UserBAL();
           MembershipUser username = Membership.GetUser(CreateUserWizard1.UserName);
        try
        {
      
      
       // Membership user = Membership.GetUser(CreateUserWizard1.UserName);
        //TblUser user1 = new TblUser();
        User user1 = new User();
        user1.UserName=CreateUserWizard1.UserName;
        user1.MembershipUserId = (Guid)username.ProviderUserKey;

        CreateUserWizard1.LoginCreatedUser = false;
        username.LastActivityDate = System.DateTime.Today.ToUniversalTime();
        Membership.UpdateUser(username);
    
        Roles.AddUserToRole(CreateUserWizard1.UserName,"Others");
      
        TextBox tb1 = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtFirstName");
        TextBox tb2 = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtLastName");
        user1.FirstName = tb1.Text;
        user1.LastName = tb2.Text;

        //RadioButtonList rdo = (RadioButtonList)CreateUserWizardStep1.ContentTemplateContainer.FindControl("RadioButtonList1");
        //if ((rdo.SelectedValue != null )&& (rdo.SelectedValue != "" ))
        //{
        //user1.UserType  = Convert.ToInt32(rdo.SelectedValue);
        //}
        user1.UserType = 1;
        user1.SubscriptionId = 0;
        int Result = objuserBAL.InsertUser(user1);

    
                MailMessage msgMail = new MailMessage();
                //Net Mail
                msgMail.From = new MailAddress(Email);
                msgMail.To.Add(CreateUserWizard1.Email);
                //msgMail.To.Add("mahajan.namrata@yahoo.com");

                ////Label lblEmail = (Label)GridView1.Rows[i].FindControl("");
                //web Mail
                //msgMail.To = "nanuramp@synoris.com";
                //msgMail.From =("namratam@synoris.com");

                Comman objComman = new Comman();
                MailTemplate currenttemplate = new MailTemplate();
                currenttemplate = objComman.GetTemplate("ActivationEmail");
                //currenttemplate.Body = String.Format(currenttemplate.Body,user1.MembershipUserId.ToString());
                //PropertyMapper mapper = new PropertyMapper(user1);
                //mapper.MapTemplate(currenttemplate);
                //UpdateUI(currenttemplate);
                currenttemplate.Body = currenttemplate.Body.Replace("Domain",System.Web.HttpContext.Current.Request.Url.ToString().Replace(System.Web.HttpContext.Current.Request.RawUrl.ToString(), ""));
                currenttemplate.Body = currenttemplate.Body.Replace("MembershipUserId", user1.MembershipUserId.ToString());
                msgMail.Subject = currenttemplate.Subject;
                msgMail.Body = currenttemplate.Body;
               // msgMail.Subject = "InvestorScopes Account Activation";

               // //msgMail.BodyFormat = MailFormat.Html;
               // string emailbody = "Thanks for registration in Investor scopes.To Activate your account click on the following link";
               // emailbody += "
               // // emailbody += "http://www.google.co.in/";


               // emailbody += System.Web.HttpContext.Current.Request.Url.ToString().Replace(System.Web.HttpContext.Current.Request.RawUrl.ToString(), ""); 
               // emailbody += "/RegistrationActive.aspx?ID=";


               //// emailbody += "http://www.investorscope.synoris.com/RegistrationActive.aspx?ID=";


             
               // emailbody +=(System.Guid)username.ProviderUserKey;
               // emailbody += '"';
               // emailbody += ">";
               // emailbody += "Activate My Account";
               // emailbody += "";
               // msgMail.Body = emailbody;
                //net mail
                msgMail.IsBodyHtml = true;
                msgMail.Priority = MailPriority.High;
                SmtpClient sC = new SmtpClient("smtp.gmail.com");
                //sC.Port = 25;
                sC.Credentials = new NetworkCredential(Email, Pwd);
                sC.EnableSsl = true;
                        
                    //SmtpMail.Send(msgMail);
                    //net mail
                    sC.Send(msgMail);
                    emailid = Encryption.Encrypt(user1.UserName);
                   // msgMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    Response.Redirect("ConfirmEmail.aspx?ID=" + username.ProviderUserKey + "&eid=" + emailid);
                }
                catch(Exception ex)
                {




                    throw new Exception(ex.Message);


                    Response.Redirect("ConfirmEmail.aspx?ID=" + username.ProviderUserKey + "&eid=" + emailid);
                }
                finally
                {
                    objuserBAL = null;
                }
             


              
               
     
       // }
        
    
    }
 protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
       {
           UserBAL objuserBAL = new UserBAL();
           MembershipUser username = Membership.GetUser(CreateUserWizard1.UserName);
        try
        {
       
        
       // Membership user = Membership.GetUser(CreateUserWizard1.UserName);
        //TblUser user1 = new TblUser();
        User user1 = new User();
        user1.UserName=CreateUserWizard1.UserName;
        user1.MembershipUserId = (Guid)username.ProviderUserKey;
        CreateUserWizard1.LoginCreatedUser = false;
        username.LastActivityDate = System.DateTime.Today.ToUniversalTime();
        Membership.UpdateUser(username);
      
        Roles.AddUserToRole(CreateUserWizard1.UserName,"Others");
        
        TextBox tb1 = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtFirstName");
        TextBox tb2 = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtLastName");
        user1.FirstName = tb1.Text;
        user1.LastName = tb2.Text;
        //RadioButtonList rdo = (RadioButtonList)CreateUserWizardStep1.ContentTemplateContainer.FindControl("RadioButtonList1");
        //if ((rdo.SelectedValue != null )&& (rdo.SelectedValue != "" ))
        //{
        //user1.UserType  = Convert.ToInt32(rdo.SelectedValue);
        //}
        user1.UserType = 1;
        user1.SubscriptionId = 0;
        int Result = objuserBAL.InsertUser(user1);
      
                MailMessage msgMail = new MailMessage();
                //Net Mail
                msgMail.From = new MailAddress(Email);
                msgMail.To.Add(CreateUserWizard1.Email);
                //msgMail.To.Add("mahajan.namrata@yahoo.com");
                ////Label lblEmail = (Label)GridView1.Rows[i].FindControl("");
                //web Mail
                //msgMail.To = "nanuramp@synoris.com";
                //msgMail.From =("namratam@synoris.com");
                Comman objComman = new Comman();
                MailTemplate currenttemplate = new MailTemplate();
                currenttemplate = objComman.GetTemplate("ActivationEmail");
                //currenttemplate.Body = String.Format(currenttemplate.Body,user1.MembershipUserId.ToString());
                //PropertyMapper mapper = new PropertyMapper(user1);
                //mapper.MapTemplate(currenttemplate);
                //UpdateUI(currenttemplate);
                currenttemplate.Body = currenttemplate.Body.Replace("Domain",System.Web.HttpContext.Current.Request.Url.ToString().Replace(System.Web.HttpContext.Current.Request.RawUrl.ToString(), ""));
                currenttemplate.Body = currenttemplate.Body.Replace("MembershipUserId", user1.MembershipUserId.ToString());
                msgMail.Subject = currenttemplate.Subject;
                msgMail.Body = currenttemplate.Body;
               // msgMail.Subject = "InvestorScopes Account Activation";
               // //msgMail.BodyFormat = MailFormat.Html;
               // string emailbody = "Thanks for registration in Investor scopes.To Activate your account click on the following link";
               // emailbody += "               
               // msgMail.Body = emailbody;
                //net mail
                msgMail.IsBodyHtml = true;
                msgMail.Priority = MailPriority.High;
                SmtpClient sC = new SmtpClient("smtp.gmail.com");
                //sC.Port = 25;
                sC.Credentials = new NetworkCredential(Email, Pwd);
                sC.EnableSsl = true;
                        
                    //SmtpMail.Send(msgMail);
                    //net mail
                    sC.Send(msgMail);
                    emailid = Encryption.Encrypt(user1.UserName);
                   // msgMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    Response.Redirect("ConfirmEmail.aspx?ID=" + username.ProviderUserKey + "&eid=" + emailid);
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                    Response.Redirect("ConfirmEmail.aspx?ID=" + username.ProviderUserKey + "&eid=" + emailid);
                }
                finally
                {
                    objuserBAL = null;
                }
             
              
               
     
       // }
        
    
    }

Send Email to Admin on new user creation

Most of what you want to do is already there.  This procedure will activate built-in function to send an email to each new user when they register.  Include a 'welcome, thanks for registering' etc text file.  You will have a copy of this email sent to yourself.
I use visual studio.....
  • Open register.aspx .
  • Have the "properties window" open in visual studio.
  • Click on the wizard that registers users.
    (you may have to click around a bit to get the right 'properties' to show. 
  • Keep an eye on the properties and look for "mail definition"
  • enter a body filename -  mine is ~/textfiles/newuserwelcome.txt
    I click on anything inside the registration wizard, then at the bottom of Visual Studio window I select   thing (is this a tag?) and then the properties that we want to chage will appear.
  • enter the destination email address etc etc. .
  • Create the file ~/textfiles/newuserwelcome.txt  (or whatever you like to call it.
    In this file write
    • welcome <%UserName %>   Thanks for registering
    • your password is <%Password %>  Please write it down and store it someplace SAFE.
  • the website will magically insert the username and his password and send an email to him when he registers.
  • Back in the properties, in 'maildefinition'  put  in the CC field, your administation emai address. 
Be aware that your new user WILL see this address in the email he gets.   I wanted to send a BCC to myself instead, but I have given up on that.    So if one of your new users is unethical and knows more about internet than you, he will want to break into your administrator email address and get access to all those usernames and passwords.   So you should go into this email address and delete all of the occasionally.
If someone knows how to get the site to send a BCC (blind-carbon-copy), I would very much like to know how.

     MailAddress bcc = new MailAddress("somedude@somedomain.com");
   message.Bcc.Add(bcc);

User management in ASP.net

a very good tutorial series about managing users, their statuses, user creation wizard and other user related stuff.

User Management in ASP.net

Tuesday, September 7, 2010

using foreach loop in entity framework result

An ideal environment for creation of business applications should allow developers to describe the business logic and state of the problem domain which they are modeling with minimum or no "noise" coming from the underlying representation and the infrastructure that supports it. Applications should be able to interact with the stores that maintain the persistent state of the system in the terms of the problem domain; specifically in the terms of a conceptual domain model, completely separated from the logical schema of the underlying store.
One would expect developers to be able to write something like the piece of code below:
// we'll use the order-tracking store
using(OrderTracking orderTracking = new OrderTracking()) {

    // find all the pending orders for sales people
    // in Washington
    var orders = from order in orderTracking.SalesOrders
                 where order.Status == "Pending Stock Verification" &&
                       order.SalesPerson.State == "WA"
                 select order;

    foreach(SalesOrder order in orders) {

        // obtain a list of StockAppProduct objects
        // to be used for validation
        List products = new List(
            from orderLine in order.Lines
            select new StockAppProduct {
                ProductID = orderLine.Product.ID,
                LocatorCode = ComputeLocatorCode(orderLine.Product)
            }
        );

        // make sure all products for this order
        // are in stock through the stock management
        // system
        if(StockApp.CheckAvailability(products)) {
            
            // mark the order as "shippable"
            order.Status = "Shippable";
        }
    }

    // if we marked one or more orders as shippable, persist
    // the changes in the store
    orderTracking.SaveChanges();
}
There are two elements that are important to highlight in the code above:
  • No artificial constructs. It's common to see applications that need to adapt to peculiarities of the underlying store schema. For example, applications built on top of relational databases often have to make extensive use of joins in order to navigate through relationships. In the code above, in contrast, the "shape" of the data follows the abstractions of the problem being modeled; there are "orders", which have "order lines" and that are related to a "sales person".
  • No plumbing. The code is very database intensive, yet there are no database connection objects, no external language such as SQL for query formulation, no parameter binding, no configuration embedded in code. In this sense, you could say this code is "pure business logic".
This is the class of expressiveness and abstraction level that ADO.NET, and in particular LINQ and the Entity Framework working together, brings to application development.
The rest of this paper describes in detail the various elements that work together in order to make the sample above work.

Increase the number by one in database record

There are times when we need to increase a number in database record by one or any other specific number.

the way is to retrieve the old value of the database record, add desired numbers and save it back

vappDataContext db = new vappDataContext();
        Voucher voucher = new Voucher();
        VoucherRep voucherRep = new VoucherRep();

        var oldVno = (from lstInv in db.Vouchers where lstInv.VoucherPrefix == "CPV" select lstInv.VoucherNo).Max();
        var newVno = (Int32.Parse(oldVno) + 1).ToString();

voucher.VoucherNo = newVno;

 voucherRep.Add(voucher);
        voucherRep.Save();