Saturday, December 10, 2011

Send a Html mail through outlook in asp.net mvc

images (1)
                 Recently we have  faced a situation to send a html formatted mail in our asp.net mvc application. We want to provide an option to users  to open their html formatted mails in outlook because user can edit the mail and can send it to their outlook contacts.Pramod tell me an idea it was quite enough to solve our problem.we have take the html from our template view and send it through smtpClient. we have used pickupDirectory option of webmail, using this we can send mail in to a particular directory, it will save as a .eml file. A custom action result will do all this things and download it as an outlook file. now user can send it by opening it in outlook
Here is the custom action result
public class MailResult : ActionResult    {  
       string _content;         
       string _viewName;         
       string _contentType = "message/rfc822";         
       dynamic _model;         
       string _fromMailAddress;         
       string _toMailAddress;                  
       public MailResult(string AViewName,dynamic AModel,string AFromMail,string AToMail)             {             
           _viewName = AViewName;             
           _model = AModel;             
          _fromMailAddress = AFromMail;             
          _toMailAddress=AToMail;         
        }         
       public override void ExecuteResult(ControllerContext context)         
        {  var view = ViewEngines.Engines.FindView(context, _viewName, null);             
           var ViewData = new ViewDataDictionary();             
           var TempData = new TempDataDictionary();             
           ViewData.Model = _model;             
           using (var writer = new StringWriter())             
            {                 
             var ccontext = new ViewContext(context, view.View, ViewData, TempData, writer);              ViewData.Model = _model;                 
             view.View.Render(ccontext, writer);                 
             writer.Flush();                 
             _content = writer.ToString();             
            }             
          System.Net.Mail.MailMessage msg = new MailMessage();             
          msg.From = new MailAddress(_fromMailAddress);             
         msg.To.Add(new MailAddress(_toMailAddress));             
          msg.IsBodyHtml = true;             
         msg.Body = _content;             
        SmtpClient smtp = new SmtpClient();             
        smtp.PickupDirectoryLocation 
          = context.HttpContext.Request.ServerVariables["APPL_PHYSICAL_PATH"];             
        smtp.PickupDirectoryLocation = smtp.PickupDirectoryLocation + @"\Content\Mail\";             Guid newGuId = Guid.NewGuid();             
        string fname = smtp.PickupDirectoryLocation + newGuId + ".eml";             
        //Save is an Extension method, using this we can specify the guid in to that ie; for            deleting        msg.Save(fname);             
        context.HttpContext.Response.Clear();             
        context.HttpContext.Response.AddHeader("Content-Disposition",string.Format("attachmen         t; filename={0}", "mail.eml"));             
         context.HttpContext.Response.Charset = "";             
         context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);       
         context.HttpContext.Response.ContentType = _contentType              
         context.HttpContext.Response.TransmitFile(fname);
         context.HttpContext.Response.End();             
         System.IO.File.Delete(fname); 
          }     
}



Extension Method:

(extension method source: codeproject)
public static class MailMessageExt
{     
   public static void Save(this MailMessage Message, string FileName)     
    {         
       Assembly assembly = typeof(SmtpClient).Assembly;
       Type _mailWriterType = assembly.GetType("System.Net.Mail.MailWriter"); 
       using (FileStream _fileStream = new FileStream(FileName, FileMode.Create)) 
        {             
          // Get reflection info for MailWriter contructor
           ConstructorInfo _mailWriterContructor = _mailWriterType.GetConstructor(                     BindingFlags.Instance | BindingFlags.NonPublic,null,new Type[] { typeof(Stream) },           null);             
          // Construct MailWriter object with our FileStream
            object _mailWriter = _mailWriterContructor.Invoke(new object[] { _fileStream });             // Get reflection info for Send() method on MailMessage
            MethodInfo _sendMethod 
     = typeof(MailMessage).GetMethod("Send",BindingFlags.Instance | BindingFlags.NonPublic);             // Call method passing in MailWriter            
           _sendMethod.Invoke(Message,BindingFlags.Instance | BindingFlags.NonPublic,                    null,new object[] { _mailWriter, true },null);             
           // Finally get reflection info for Close() method on our MailWriter
            MethodInfo _closeMethod = _mailWriter.GetType().GetMethod("Close",                           BindingFlags.Instance | BindingFlags.NonPublic); 
            // Call close method            
          _closeMethod.Invoke(_mailWriter,BindingFlags.Instance | BindingFlags.NonPublic,                 null,new object[] { },null);         
           }     
     }
}

Monday, November 7, 2011

Windows-8 Developer preview

         One week ago I've installed win-8 developer preview in ma desktop. some screen shots..



Monday, October 24, 2011

Android 4.0 (ice cream sandwich)

                       Android’s new version (4.0) released few days ago. lets check what are the new features are introduced by Google in ice cream sandwich to compete Apples ios 5.

nexus s

                

              Android 4.0, Ice Cream Sandwich brings an entirely new look and feel to Android. The lock screen, widgets, notifications, multi-tasking and everything in between has been rethought and refined to make Android simple, beautiful, and beyond smart.

 

 

 

Galaxy Nexus – Video

New features at a glance

  • Face Unlock

ice-cream-sandwich-android-4

       

           With Face Unlock on ice cream sandwich you can now unlock your phone with a smile. No complicated passwords to remember, just switch on your phone and look into the camera to quickly unlock your phone.

  • Android Beam

android beam

     

               Using this android feature you can easily share your contacts,websites,apps,maps,youtube videos etc by touching two android phones each other.

 

  • Voice typing

voice typing

     

    Use your voice to type Emails,SMS or any where you want to type texts

more to read:

  1. Android 4.0 Ice Cream Sandwich: everything you need to know
  2. Android Ice Cream Sandwich and Galaxy Nexus: Everything You Need to Know
  3. iOS 5 vs. Android 4.0 Ice Cream Sandwich vs. Windows Phone 7.5 Mango – Comparison

Sunday, October 9, 2011

Common Table Expression (CTE)

               few days ago I’ve written a  blog post in SQL server using CTE to find  Sundays. Lets dig some more deep in to this SQL server feature.

                                                        microsoft-sql-server-2008

    What is CTE

     The common table expression is a temporary named result set that can refer in a SELECT,INSERT, UPDATE or DELETE statement.

       simply a CTE is similar to a derived table but it is not stored as an object and lasts only for the duration of the query.

    Unlike a derived table, a CTE can be self referencing and can be referenced multiple times in the same query

we can use a CTE in View create statement also we can add CTE in to the new MERGE statement (In sql server 2008)

SQL Server support two types of CTEs

  • recursive
  • non recursive

 Syntax

A Common Table Expression contains three main parts:

  • The CTE name (this is what follows the WITH keyword)
  • The column list (optional)
  • The query (appears within parentheses after the AS keyword)

With CTE_Name (Column_Name_1, Column_Name_2 … Column_Name_n )
As
(
     cte_Query_Definition
)
--TSQL which uses the CTE

Some Examples

WITH Table1(Name,Designation,DateofJoin)
As   
(
    select CN.Name,D.Name,E.DateOfJoin from ContactName CN
    Inner join AM_Employee E on E.ContactId = CN.ContactId
    Inner join AM_Designation D on E.DesignationId = D.Id
)
select Name,Designation,DateofJoin from Table1

 

Sunday, September 25, 2011

ASP.NET MVC 4 Developer Preview



                 One week ago in Build conference Microsoft  announced a lot of their products latest versions developer previews. They are Including Windows 8, VS 2011, ASP.NET MVC 4 etc. In this post l would like to discuss about ASP.NET MVC 4 and lets check what are the new features are included in MVC 4 Developer preview.you can read more details about ASP.NET MVC 4 from asp.net site
http://www.asp.net/mvc/mvc4


Download links
         you can download and install the mvc-4 developer preview using the following links
Install ASP.NET MVC 4 using the Web Platform Installer
 Features at a glance:
        Cosmetic changes:
             Refreshed and modernized default project Template.
             New Template for mobile web applications.
        Other changes
             Adaptive Rendering.
             Redirect to different views based on requested device.
             Enhanced support for asynchronous methods.

                  
MVC team introduced a brand new default Template in MVC 4, using this we can create good looking websites with out much more design effort.

         New Registration and Login windows using JQuery UI
Mobile Application Template with jQuery Mobile
Mobile Log On
Mobile View Registration Form
you can read more details about asp.net mvc 4 developer preview from  Phill Hacck
and Scott Hanselman blog posts. you can read more about mobile features from here .

Tuesday, September 20, 2011

Select All option using jQuery

      selecting some more checkboxes is cumbersome and tedious. usually we are trying select all or Unselect All option by checking or unchecking one. Find the snippet of jQuery to select / unselect the check boxes from a table row by changing one check box value. 

Capture

Here the code:
$(".chkAll").change(function () 
     {           
       var checkState = $(this).attr('checked');
       var row = $(this).closest('tr')   
       $(row).find('input:checkbox').attr('checked', checkState);         
});
by changing the status of first checkbox,we can select or unselect the entire row of checkboxes.

first column checkboxes has contain a class " chkAlland call the jQuery function whenever a change occurred in that checkbox. set the current status of that (chkAll) checkbox in to a variable checkstate and then find the closest table row to the checkbox. After that find all check boxes from that row and change the status of all in to the variable value.

Sunday, July 31, 2011

Generate SQL Queries

select *from AM_DataSource

select 'Insert into AM_CalculationMaster(Id,Name,IsFinancialField,AccountNumber,EquationString)values('+ CAST(Id As Varchar(100))+','+ QUOTENAME(Name,'''')+',1,0,'+ IsNULL(QUOTENAME(EquationString,''''),'')+ ')' from Am_DataSource

 

Capture

Thursday, July 28, 2011

Replace a string value with another in SQL Server

select *from sa_Name
update sa_Name set SurName = REPLACE(SurName,'Aravindakshan','A')
select *from sa_Name

Capture

     after executing this query the Name ‘Aravindakshan’ is replaced with ‘ A’ all the occurrence of this word in Surname column should be replaced with ‘A’.

Thursday, July 14, 2011

Find All Sundays between two dates in SQL server Using CTE

  • A Common table Experession (CTE) can be treated as a temporary result set within the scope of a single SELECT,INSERT,UPDATE or DELTE Statement.
  • A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
  • CTE can be self-referencing and can be referenced multiple times in the same query.

 
declare @DateFrom DateTime ='2011-07-01',
            @DateTo DateTime = '2011-07-31'
;WITH CTE(dt)
AS
(
      Select @DateFrom
      Union All
      Select DATEADD(d,1,dt)FROM CTE
      Where dt<@DateTo
)
select 'Sunday',dt from CTE
where DATENAME(dw,dt)In('Sunday')

Output
 

Thursday, June 2, 2011

Confirm a request using multiple submit buttons.

   Recently i have faced a situation to confirm an Inactivate request from user.I have done it using multiple submit buttons.In ASP.net MVC we can bind the submit buttons value using same binding methods. Use two submit buttons in Confirm view.

<p>
    <input type="submit" name="Confirm" value="Confirm"/>
    <input type ="submit" name="Cancel" value="Cancel" />
</p>


We used name="confirm" and name="cancel" to bind the submit buttons values. if an user clicked on confirm button then  the ActionResult method string variable 'Confirm' will bind with a value "Confirm" and string Cancel will be null else vice versa. By checking this values we can perform the required action.
        [HttpPostActionName("InActive")]
        public ActionResult InActiveConfirmed(string Confirm, string Cancel)
        {
            var response = Confirm ?? Cancel;
 
            if (response == "Confirm")
            {
                // do the things..
                // In Activate the item
            }
            else
            {
                // return back with out InActivating Item
            }
 
 
        }

Saturday, April 30, 2011

SEO Friendly MVC routing

            
              Normal routing in asp.net mvc is not much SEO friendly. Commonly we are using {controller}/{action}/id route by default.


  Default routing:
                   routes.MapRoute(
                "Default"// Route name
                "{controller}/{action}/{id}"// URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
normally we are using an integer number in the place of id (usually database table keys). Urls like this is not SEO friendly ( eg:    www.yourdomain.com/Location/details/2). If  we can build a url with string which is the name of the particular item( eg: location,book,movie etc). it will become more SEO friendly. Such as www.yourdomain.com/Location/details/Location name.
      This is possible in asp.net mvc by adding one more route in Global.asax. Note that newly added url parameter must be optional because we dont need that parameter in normal cases. It's been purely using for  SEO.

Here is the Global.asax code.


 routes.MapRoute(
                "Default1"// Route name
                "{controller}/{action}/{id}/{id1}"// URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional, id1 = UrlParameter.Optional } // Parameter defaults
            );
Add the above code also in Global.asax Default route.
The action will be like this
[OutputCache(CacheProfile = "Cache1Hour")]
    public ActionResult Details(decimal id, string id1)
    {
        CDataStructLocationDetails objeDetails = new CDataStructLocationDetails{Id = id,Typeid        =3};
        return ViewEx(EnActions.Details, objeDetails);
        
    }


Sample Urls:
     www.yourdomain.com/Package/Details/5/Kerala-Honeymoon-Package.

Blank spaces in Urls replaced by %20 to avoid this we can send the name by replacing blank spces with '-'
here is the sample.


<%= Html.ActionLink("View Package Details""Details",
                              new{id=item.Id,id1=item.PackageName.Trim().Replace(' ','-')})%>

Saturday, April 2, 2011

NuGet

What is NuGet?
                                                      
        NuGet is a package manager for .Net. Using this you can search the packages and add it in to your project very easily.


      How can I install NuGet?
                   Installing of NuGet is very simple, Now NuGet is available as a VS Extension. You can install NuGet very quickly.
                   Tools -> Extension Manager ->
and search NuGet and Install it.



How can I Add a Package using NuGet?
             Adding Packages for our Project is very simple using NuGet.

right click on References and Select Add Library Package Reference Option. This will shows an add Libraypackage window from this you can search your package and install it in to your project using a single click(also uninstall by a single click) or you can select it in Project menu
Project -> Add Library Package Reference



Here I'm going to add ELMAH(Error Logging Modules and Handlers)  package reference.


   After Installing ELMAH package reference you can see the Elmah reference at the reference folder
Also NuGet added a new configuration file package.config and made some changes in web.config to work ELMAH

Automatically generated Package.config contents


                                 Here is the automatically created changes in web.config



Here is the elmah.axd view where we can see the logged errors

If you want to remove the ELMAH, you can simply do it by selecting uninstall option
after uninstalling elmah NuGet will remove all added references and files (Package.config file and changes in web.config etc)
You can create your own package for your company framework or other requirement. I will explain it in my next blog post.

Read More about Nuget:
Microsoft opened a Nuget gallery http://nuget.org. This site allows anyone to search and browse a online gallery of  open source packages availble via NuGet.
Read more from  Phill Haack  and  Scott Hanselman blog posts


Friday, April 1, 2011

@helper in Razor view.

          You can create your own custom html helpers in Razor, using a brand new syntax @helper in Razor. Creating a html helper using @helper is very much easier than our current html extension method types.

@helper in Razor view engine.

            This is a sample example for @helper usage. I've create a textbox helper which accepts a name and a value and will create a text box for MVC 3 Unobstructive JavaScript validation. ( I used it for dynamically created views)

   You can read more about @helper in the from here and here

       @helper TextBox(string Name, object Value)
    {
     <input class="text-box single-line required" id='@Name' data-val-required='This field is required' name='@Name' type="text" data-val="true" value='@Value'/>
     <span class="field-validation-valid" data-valmsg-for='@Name' data-valmsg-replace="true">
     </span>     
}
Truncate Helper
@helper Truncate(string input, int length)
{
    if (input.Length <= length) 
        { @input } 
    else 
        { @input.Substring(0, length)<text>..</text>}
}