Wednesday, January 30, 2013

How to generate and download iCalendar file in ASP.NET MVC?

public ActionResult DownloadiCalendar()
        {
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, System.Text.Encoding.UTF8);
            writer.WriteLine(GetCalendarString());
            writer.Flush();
            output.Seek(0, SeekOrigin.Begin);
            return File(output, "text/calendar", "appointment.ics");
        }

        private string GetCalendarString()
        {
            string DateFormat = "yyyyMMddTHHmmssZ";
            DateTime startDate = DateTime.Now.AddDays(5);
            DateTime endDate = startDate.AddMinutes(35);
            string organizer = "foo@bar.com";
            string location = "My House";
            string summary = "My Event";
            string description = "Please come to\\nMy House";


            string calendar = "BEGIN:VCALENDAR";
            calendar = calendar + "\nVERSION:2.0";
            calendar = calendar + "\nMETHOD:PUBLISH";
            calendar = calendar + "\nBEGIN:VEVENT";
            calendar = calendar + "\nORGANIZER:MAILTO:" + organizer;
            calendar = calendar + "\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nLOCATION:" + location;
            calendar = calendar + "\nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com";
            calendar = calendar + "\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nSUMMARY:" + summary;
            calendar = calendar + "\nDESCRIPTION:" + description;
            calendar = calendar + "\nPRIORITY:5";
            calendar = calendar + "\nCLASS:PUBLIC";
            calendar = calendar + "\nEND:VEVENT";
            calendar = calendar + "\nEND:VCALENDAR";

            return calendar;
        }

How run a ASP.NET project without Visual Studio and IIS configuration?

By ASP.NET development server:

"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\webdev.webserver40.exe" /path:"C:\ProjectFolder" /vpath:/

Tuesday, January 29, 2013

Monday, January 28, 2013

How to delete cookies in ASP.NET?

In fact, delete mean "expire"

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

iPhone 4 simulator

http://iphone4simulator.com/

ASP.NET Image Control With Fallback URL

http://weblogs.asp.net/ricardoperes/archive/2013/01/23/asp-net-image-control-with-fallback-url.aspx

Friday, January 18, 2013

How to validate an email address by Model DataAnnotations in ASP.NET MVC

[Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        [RegularExpression(@"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",ErrorMessage="Invalid email address")]
        public string Email { get; set; }

What is the best regular expression for an email address?

^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$

??

http://fightingforalostcause.net/misc/2006/compare-email-regex.php

Adding SignalR to an ASP.Net WebForms Project

http://www.csharpfritz.com/blog/2013/1/10/adding-signalr-to-an-aspnet-webforms-project

Tuesday, January 15, 2013

How to solve "The XML is not well-formed." problem ?

Need to locate and replace special characters
"& < > \" \'".Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("\'", "'");

Monday, January 14, 2013

Server Side Model Validation in MVC Razor

http://www.dotnet-tricks.com/Tutorial/mvc/F16Q301112-Server-Side-Model-Validation-in-MVC-Razor.html

Friday, January 11, 2013

Why session timeout setting not working


    
          
    

    


if use form authentication, need to change two places

Thursday, January 10, 2013

How to fix error "project type is not supported by this installation" while open a ASP.NET MVC 3 project?

Install ASP.NET MVC3
http://www.asp.net/mvc/mvc3

Creating a Pinterest Like Layout in ASP.NET

http://techbrij.com/asp-net-pinterest-infinite-scroll-jquery-masonry

Wednesday, January 9, 2013

How to sovle loading XmlDocument throwing “An error occurred while parsing EntityName”

The XML is not well-formed.
Maybe includes special characters.

Ampersand & &
Left angle bracket < < Right angle bracket > >
Straight quotation mark " "
Apostrophe ' '


http://support.microsoft.com/kb/316063

Function for checking if .net Framework installed

        private static bool IsNetFrameWork45()
        {
            //            Following are the different version for .Net 4.0 
            //4.0.30319.1 = .NET 4.0 RTM
            // 4.0.30319.269 = most common .NET 4.0 version we're seeing in the data collected from our users
            // 4.0.30319.544 = another .NET 4.0 version that a small portion of our users have installed
            // 4.0.30319.17626 = .NET 4.5 RC
            // 4.0.30319.17929 = .NET 4.5 RTM
            // 4.0.30319.18010 = current version on my Windows 8 machine
            Assembly assembly = typeof(System.String).Assembly;
            System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
            if (fvi.FileMajorPart != 4) return false;
            if (fvi.ProductPrivatePart < 17626) return false;
            return true;
        }

Tuesday, January 8, 2013

Mobile Web Applications with ASP.NET WebForms

http://roopeshreddy.wordpress.com/2012/12/29/mobile-web-applications-with-asp-net-webforms/


Monday, January 7, 2013

How to use UserControl in ASP.NET MVC?

1. Create UserControl as same as in the webforms. But change base class from System.Web.UI.UserControl to System.Web.Mvc.ViewUserControl
    public partial class TestUserControl : System.Web.Mvc.ViewUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Label1.Text = "Loaded";
        }
    }
2. Put this UserControl all related files into Views/Shared folder
3. Then able to load by Partial view
@Html.Partial("TestUserControl");

Asynchronously streaming video with ASP.NET Web API

http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/

Friday, January 4, 2013

How to save MailMessage into eml file by Reflection on .net framework 4.5?

/// 
        /// HACK - SmtpClient does not give access to filenames when outputting e-mails to disk.  The following extension method
        /// uses reflection to call the internal MailWriter type so that mails can be created with a specified filename.
        /// 
        /// Code taken from: http://www.codeproject.com/KB/IP/smtpclientext.aspx
        /// 
        /// Mail message to be serialized./// Filename of mail message.public static void Save(this MailMessage Message, string FileName)
        {
            // TODO: See if the Mono framework has serialization code we can use.

            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, 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);
            }
        }

How to know if .Net Framework 4.5 installed?

.NET 4.5 is not running side by side with .Net 4.0. It is a upgrade.
.NET 4.5 overwrites .NET 4. So all of files are in the same folder.

Following are the different version for .Net 4.0
4.0.30319.1 = .NET 4.0 RTM
4.0.30319.269 = most common .NET 4.0 version we're seeing in the data collected from our users
4.0.30319.544 = another .NET 4.0 version that a small portion of our users have installed
4.0.30319.17626 = .NET 4.5 RC
4.0.30319.17929 = .NET 4.5 RTM
4.0.30319.18010 = current version on my Windows 8 machine

So there are many ways to know if .Net 4.5 installed
1. By System.dll version number: 4.0.30319.17626 or greater
2. By Registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client
3. By code
  public static bool IsNet45OrNewer()
  {
      // Class "ReflectionContext" exists from .NET 4.5 onwards.
      return Type.GetType("System.Reflection.ReflectionContext", false) != null;
  }

SignalR: Building real time web applications

http://blogs.msdn.com/b/webdev/archive/2012/12/17/signalr-building-real-time-web-applications.aspx

Thursday, January 3, 2013

How to disable double click event by jQuery?

$("*").dblclick(function(event){
event.preventDefault();
});

Wednesday, January 2, 2013

How to map part of table (only for specific columns) in Entity Framework?


No, you can’t.
The workaround is to create store procedure or view, the map from there

Exporting The Razor WebGrid To Excel

http://www.mikesdotnetting.com/Article/204/Exporting-The-Razor-WebGrid-To-Excel

@{
    Layout = null;
    var db = Database.Open("Northwind");
    var sql = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers";
    var data = db.Query(sql);
    var grid = new WebGrid(data, canPage: false, canSort: false);
    Response.AddHeader("Content-disposition", "attachment; filename=report.xls");
    Response.ContentType = "application/octet-stream";
}
@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("CustomerID", "ID"),
        grid.Column("CompanyName", "Company Name"),
        grid.Column("ContactName", "Contact Name"),
        grid.Column("Address"),
        grid.Column("City"),
        grid.Column("Country"),
        grid.Column("Phone")
    )
)

Tuesday, January 1, 2013

How to add robots.txt into ASP.NET MVC site?

There are two ways to do so:
First one:
http://rayaspnet.blogspot.ca/2011/04/how-to-implment-dynamic-robotstxt-in.html

Second, the simpler one:
Add robots.txt into your website root, and Add one line into Global.asax file
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("robots.txt");
        }

Inside the ASP.NET Single Page Apps Template

http://www.johnpapa.net/inside-the-asp-net-single-page-apps-template/