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();

Monday, April 5, 2010

URL Rewriting with IIS7

full article is at this address http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Approach 3: Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7
The above HttpModule approach works great for scenarios where the URL you are re-writing has a .aspx extension, or another file extension that is configured to be processed by ASP.NET.  When you do this no custom server configuration is required - you can just copy your web application up to a remote server and it will work fine.
There are times, though, when you want the URL to re-write to either have a non-ASP.NET file extension (for example: .jpg, .gif, or .htm) or no file-extension at all.  For example, we might want to expose these URLs as our public catalog pages (note they have no .aspx extension):

With IIS5 and IIS6, processing the above URLs using ASP.NET is not super easy.  IIS 5/6 makes it hard to perform URL rewriting on these types of URLs within ISAPI Extensions (which is how ASP.NET is implemented). Instead you need to perform the rewriting earlier in the IIS request pipeline using an ISAPI Filter.  I'll show how to-do this on IIS5/6 in the Approach 4 section below.
The good news, though, is that IIS 7.0 makes handling these types of scenarios super easy.  You can now have an HttpModule execute anywhere within the IIS request pipeline - which means you can use the URLRewriter module above to process and rewrite extension-less URLs (or even URLs with a .asp, .php, or .jsp extension).  Below is how you would configure this with IIS7:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  
<configSections>
    
<section name="rewriter"
             requirePermission
="false"
             type
="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  configSections>
 
  
<system.web>
     
    
<httpModules>
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
    httpModules>
   
  
system.web>

  
<system.webServer>

    
<modules runAllManagedModulesForAllRequests="true">
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
    modules>

    
<validation validateIntegratedModeConfiguration="false" />

  system.webServer>

  
<rewriter>
    
<rewrite url="~/products/(.+)" to="~/products.aspx?category=$1" />
  rewriter>
  
configuration>
Note the "runAllManagedModulesForAllRequests" attribute that is set to true on the section within .  This will ensure that the UrlRewriter.Net module from Intelligencia, which was written before IIS7 shipped, will be called and have a chance to re-write all URL requests to the server (including for folders).  What is really cool about the above web.config file is that:
1) It will work on any IIS 7.0 machine.  You don't need an administrator to enable anything on the remote host.  It will also work in medium trust shared hosting scenarios.
2) Because I've configured the UrlRewriter in both the and IIS7 section, I can use the same URL Rewriting rules for both the built-in VS web-server (aka Cassini) as well as on IIS7.  Both fully support extension-less URLRewriting.  This makes testing and development really easy.
IIS 7.0 server will ship later this year as part of Windows Longhorn Server, and will support a go-live license with the Beta3 release in a few weeks.  Because of all the new hosting features that have been added to IIS7, we expect hosters to start aggressively offering IIS7 accounts relatively quickly - which means you should be able to start to take advantage of the above extension-less rewriting support soon.  We'll also be shipping a Microsoft supported URL-Rewriting module in the IIS7 RTM timeframe that will be available for free as well that you'll be able to use on IIS7, and which will provide nice support for advanced re-writing scenarios for all content on your web-server.
Sample Download: A sample application that I've built that shows using this extension-less URL technique with IIS7 and the UrlRewriter.Net module can be downloaded here. 

Sunday, April 4, 2010

Linq to SQL a very good tutorial by scott

a very good tutorial series by scott from microsoft.

http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx