Friday, November 23, 2012

C# - Encryption Decryption for URL Query String

Encryption for URL Querystring parameter.

Normal encryption will not restrict URL Reserved character, but here you can update your reserve characters.


public static class EncryptDecryptQueryString
    {
        private static byte[] key = { };
        private static string sEncryptionKey = "B@|@j!";
        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
        public static string Decrypt(string stringToDecrypt)
        {
            //URL Decrytion Avoid Reserved Characters
            stringToDecrypt = stringToDecrypt.Replace("-2F-", "/");
            stringToDecrypt = stringToDecrypt.Replace("-21-", "!");
            stringToDecrypt = stringToDecrypt.Replace("-23-", "#");
            stringToDecrypt = stringToDecrypt.Replace("-24-", "$");
            stringToDecrypt = stringToDecrypt.Replace("-26-", "&");
            stringToDecrypt = stringToDecrypt.Replace("-27-", "'");
            stringToDecrypt = stringToDecrypt.Replace("-28-", "(");
            stringToDecrypt = stringToDecrypt.Replace("-29-", ")");
            stringToDecrypt = stringToDecrypt.Replace("-2A-", "*");
            stringToDecrypt = stringToDecrypt.Replace("-2B-", "+");
            stringToDecrypt = stringToDecrypt.Replace("-2C-", ",");
            stringToDecrypt = stringToDecrypt.Replace("-3A-", ":");
            stringToDecrypt = stringToDecrypt.Replace("-3B-", ";");
            stringToDecrypt = stringToDecrypt.Replace("-3D-", "=");
            stringToDecrypt = stringToDecrypt.Replace("-3F-", "?");
            stringToDecrypt = stringToDecrypt.Replace("-40-", "@");
            stringToDecrypt = stringToDecrypt.Replace("-5B-", "[");
            stringToDecrypt = stringToDecrypt.Replace("-5D-", "]");

            byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
            try
            {
                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToDecrypt);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms,
                  des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;

                return encoding.GetString(ms.ToArray());
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        public static string Encrypt(string stringToEncrypt)
        {
            string returnstring = "";
            try
            {
               
                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms,
                  des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                returnstring = Convert.ToBase64String(ms.ToArray());
                
                //URL Encryption Avoid Reserved Characters
                returnstring = returnstring.Replace("/", "-2F-");
                returnstring = returnstring.Replace("!", "-21-");
                returnstring = returnstring.Replace("#", "-23-");
                returnstring = returnstring.Replace("$", "-24-");
                returnstring = returnstring.Replace("&", "-26-");
                returnstring = returnstring.Replace("'", "-27-");
                returnstring = returnstring.Replace("(", "-28-");
                returnstring = returnstring.Replace(")", "-29-");
                returnstring = returnstring.Replace("*", "-2A-");
                returnstring = returnstring.Replace("+", "-2B-");
                returnstring = returnstring.Replace(",", "-2C-");
                returnstring = returnstring.Replace(":", "-3A-");
                returnstring = returnstring.Replace(";", "-3B-");
                returnstring = returnstring.Replace("=", "-3D-");
                returnstring = returnstring.Replace("?", "-3F-");
                returnstring = returnstring.Replace("@", "-40-");
                returnstring = returnstring.Replace("[", "-5B-");
                returnstring = returnstring.Replace("]", "-5D-");


                return returnstring;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }

Wednesday, November 21, 2012

C# - Convert string as Uri type

Uri myuri = new uri(string)

MVC C# - Create iCal calendar ICS Feed using DDay.ical library


Following Code download the iCal file, Host this application in any URL and refer it as Feed in any Calendar application (Google calendar, Microsoft Calendar etc.,)


Requirements:
DDay.iCal library dll
MVC3 .Net 4 framework

public ActionResult iCalendar(string DownloadFileName)
{
DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();

// Create the event, and add it to the iCalendar
Event evt = iCal.Create<Event>();

// Set information about the event
evt.Start = iCalDateTime.Today.AddHours(8);
evt.End = evt.Start.AddHours(18); // This also sets the duration
evt.Description = "The event description";
evt.Location = "Event location";
evt.Summary = "18 hour event summary";

// Set information about the second event
evt = iCal.Create<Event>();
evt.Start = iCalDateTime.Today.AddDays(5);
evt.End = evt.Start.AddDays(1);
evt.IsAllDay = true;
evt.Summary = "All-day event";

// Create a serialization context and serializer factory.
// These will be used to build the serializer for our object.
ISerializationContext ctx = new SerializationContext();
ISerializerFactory factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
// Get a serializer for our object
IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

string output = serializer.SerializeToString(iCal);
var contentType = "text/calendar";
var bytes = Encoding.UTF8.GetBytes(output);

return File(bytes, contentType, DownloadFileName);
}

Monday, November 19, 2012

Markdown: An introduction


Markdown is a way to format your text to add bold and italic text, images, headings and a few other things, without having to use HTML.
SimpleEditions is one of many websites that support Markdown, so when you write a tutorial you can format your text using the following syntax:

Bold and italic text

To create italic text, surround one or a few words with stars:
This is how you create *italic text*.
To create bold text, surround one or a few words with double stars:
This is how you create **bold text**.
If you have to, you can make your text both bold and italic:
This is how you create ***bold and italic text***.

A bullet list

Create bullet lists using stars:
* Item 1  
* Item 2  
* Item 3
Will look like this:
  • Item 1
  • Item 2
  • Item3
You can also use plus (+) or minus (-) instead of a star.

Creating links

Combine brackets and parenthesis to create links in the text. It's quite simple:
Here's [a great website](http://www.simpleeditions.com). It'll float your boat.
Will look like this:
Here's a great website. It'll float your boat.

Headers

Markdown has support for different levels of headers using the hash sign (#):
# This is the title
Here's some very good boiler plate text. I don't even know what a boiler is, even less a plate.

## This is the subheader
Subheaders are awesome. Even better than you think.

### This is the third level header.
And so on.
Will look like this:

This is the title

Here's some very good boiler plate text. I don't even know what a boiler is, even less a plate.

This is the subheader

Subheaders are awesome. Even better than you think.

THIS IS THE THIRD LEVEL HEADER.

And so on.
When converted to HTML, the first level header will be a <h1> element, a third level header will be a <h3>, etc. At SimpleEditions there's only one first level header per page, namely the title (in this case, it's "Markdown: An introduction", a bit further up). Therefore, you typically always begin with a second level header (## Like this) when you write your tutorial text.

Quotes

Add a greater-than sign (>) in front of anything you are quoting, and the text will be moved slightly towards the middle.
> "Never increase, beyond what is necessary,   
> the number of entities required to explain anything."  
> – *William Ockham*
Will look like this:
"Never increase, beyond what is necessary,
the number of entities required to explain anything."
– William Ockham
Note how the name, William Ockham, is surrounded by stars to make it render in italic text.

IIS7 - 10 URL Rewriting Tips and Tricks


1. Add or Remove Trailing Slash

Many web applications use “virtual URLs” – that is the URLs that do not directly map to the file and directory layout on web server’s file system. An example of such application may be an ASP.NET MVC application with URL format similar to this:http://stackoverflow.com/questions/60857/modrewrite-equivalent-for-iis-7-0 or a PHP application with URL format that looks like this: http://ruslany.net/2008/11/url-rewrite-module-release-to-web/. If you try to request these URLs with or without trailing slash you will still get the same page. That is OK for human visitors, but may be a problem for search engine crawlers as well as for web analytics services. Different URLs for the same page may cause crawlers to treat the same page as different pages, thus affecting the page ranking. They will also cause Web Analytics statistics for this page to be split up.
This problem is very easy to fix with a rewrite rule. Having or not having a trailing slash in the URL is a matter of taste, but once you’ve made a choice you can enforce the canonical URL format by using one of these rewrite rules:
To always remove trailing slash from the URL:

  1. <rule name="Remove trailing slash" stopProcessing="true">  
  2.   <match url="(.*)/$" />  
  3.   <conditions>  
  4.     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />  
  5.     <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />  
  6.   </conditions>  
  7.   <action type="Redirect" redirectType="Permanent" url="{R:1}" />  
  8. </rule>  
To always add trailing slash to the URL:

  1. <rule name="Add trailing slash" stopProcessing="true">  
  2.   <match url="(.*[^/])$" />  
  3.   <conditions>  
  4.     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />  
  5.     <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />  
  6.   </conditions>  
  7.   <action type="Redirect" redirectType="Permanent" url="{R:1}/" />  
  8. </rule>  

2. Enforce Lower Case URLs

A problem similar to the trailing slash problem may happen when somebody links to your web page by using different casing, e.g. http://ruslany.net/2008/07/IISNET-Uses-Url-Rewrite-Module/vs. http://ruslany.net/2008/07/iisnet-uses-url-rewrite-module/. In this case again the search crawlers will treat the same page as two different pages and two different statistics sets will show up in Web Analytics reports.
What you want to do is to ensure that if somebody comes to your web site by using a non-canonical link, then you redirect them to the canonical URL that uses only lowercase characters:
  1. <rule name="Convert to lower case" stopProcessing="true">  
  2.   <match url=".*[A-Z].*" ignoreCase="false" />  
  3.   <action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />  
  4. </rule>  

3. Canonical Hostnames

Very often you may have one IIS web site that uses several different host names. The most common example is when a site can be accessed via http://www.yoursitename.com and viahttp://yoursitename.com. Or, perhaps, you have recently changed you domain name fromoldsitename.com to newsitename.com and you want your visitors to use new domain name when bookmarking links to your site. A very simple redirect rule will take care of that:

  1. <rule name="Canonical Host Name" stopProcessing="true">  
  2.   <match url="(.*)" />  
  3.   <conditions>  
  4.     <add input="{HTTP_HOST}" negate="true" pattern="^ruslany\.net$" />  
  5.   </conditions>  
  6.   <action type="Redirect" url="http://ruslany.net/{R:1}" redirectType="Permanent" />  
  7. </rule>  
To see an example of how that works try browsing to http://www.ruslany.net/2008/10/aspnet-postbacks-and-url-rewriting/. You will see in the browser’s address bar that “www” is removed from the domain name.

4. Redirect to HTTPS

When a site that requires SSL is accessed via non-secure HTTP connection, IIS responds with HTTP 403 (Unauthorized) status code. This may be fine if you always expect that your site visitors will be typing “https://…” in the browser’s address bar. But if you want your site to be easily discoverable and more user friendly, you probably would not want to return 403 response to visitors who came over unsecure HTTP connection. Instead you would want to redirect them to the secure equivalent of the URL they have requested. A typical example is this URL:http://www.paypal.com. If you follow it you will see that browser gets redirected tohttps://www.paypal.com.
With URL Rewrite Module you can perform this kind of redirection by using the following rule:

  1. <rule name="Redirect to HTTPS" stopProcessing="true">  
  2.   <match url="(.*)" />  
  3.   <conditions>  
  4.     <add input="{HTTPS}" pattern="^OFF$" />  
  5.   </conditions>  
  6.   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />  
  7. </rule>  
Note that for this rule to work within the same web site you will need to disable “Require SSL” checkbox for the web site. If you do not want to do that, then you can create two web sites in IIS – one with http binding and another with https binding – and then add this rule to the web.config file of the site with http binding.

5. Return HTTP 503 Status Code in Response

HTTP status code 503 means that the server is currently unable to handle the request due to maintenance. This status code implies that the outage is temporary, so when search engine crawler gets HTTP 503 response from your site, it will know not to index this response, but instead to come back later.
When you stop the IIS application pool for your web site, IIS will return HTTP 503 for all requests to that site. But what if you are doing maintenance to a certain location of the web site and you do not want to shut down the entire site because of that? With URL Rewrite Module you can return 503 response only when HTTP requests are made to a specific URL path:

  1. <rule name="Return 503" stopProcessing="true">  
  2.   <match url="^products/sale/.*" />  
  3.   <action type="CustomResponse" statusCode="503"  
  4.                subStatusCode="0"  
  5.                statusReason="Site is unavailable"  
  6.                statusDescription="Site is down for maintenance" />  
  7. </rule>   

6. Prevent Image Hotlinking

Image Hotlinking is the use of an image from one site into a web page belonging to a second site. Unauthorized image hotlinking from your site increases bandwidth use, even though the site is not being viewed as intended. There are other concerns with image hotlinking, for example copyrights or usage of images in an inappropriate context.
With URL Rewrite Module, it is very easy to prevent image hotlinking. For example the following rewrite rule prevents hotlinking to all images on a web site http://ruslany.net:

  1. <rule name="Prevent image hotlinking">  
  2.   <match url=".*\.(gif|jpg|png)$"/>  
  3.   <conditions>  
  4.     <add input="{HTTP_REFERER}" pattern="^$" negate="true" />  
  5.     <add input="{HTTP_REFERER}" pattern="^http://ruslany\.net/.*$" negate="true" />  
  6.   </conditions>  
  7.   <action type="Rewrite" url="/images/say_no_to_hotlinking.jpg" />  
  8. </rule>  
This rule will rewrite a request for any image file to /images/say_no_to_hotlinking.jpg only if the HTTP Referer header on the request is not empty and is not equal to the site’s domain.

7. Reverse Proxy To Another Site/Server

By using URL Rewrite Module together with Application Request Routing module you can have IIS 7 act as a reverse proxy. For example, you have an intranet web server and you want to expose its content over internet. To enable that you will need to perform the following configuration steps on the server that will act as a proxy:
Step1: Check the “Enable proxy” checkbox located in Application Request Routing feature view is IIS Manager.
Step2: Add the following rule to the web site that will be used to proxy HTTP requests:

  1. <rule name="Proxy">  
  2.   <match url="(.*)" />  
  3.   <action type="Rewrite" url="http://internalserver/{R:1}" />  
  4. </rule>  
Note the http:// prefix in the rewrite rule action. That is what indicates that this request must be proxy’ed, instead of being rewritten. When rule has “Rewrite” action with the URL that contains the protocol prefix, then URL Rewrite Module will not perform its standard URL rewriting logic. Instead it will pass the request to Application Request Routing module, which will proxy that request to the URL specified in the rule.

8. Preserve Protocol Prefix in Reverse Proxy

The rule in previous tip always uses non-secure connection to the internal content server. Even if the request came to the proxy server over HTTPS, the proxy server will pass that request to the content server over HTTP. In many cases this may be exactly what you want to do. But sometimes it may be necessary to preserve the secure connection all the way to the content server. In other words, if client connects to the server over HTTPS, then the proxy should use “https://” prefix when making requests to content server. Similarly, if client connected over HTTP, then proxy should use “http://” connection to content server.
This logic can be easily expressed by this rewrite rule:

  1. <rule name="Proxy">  
  2.   <match url="(.*)" />  
  3.   <conditions>  
  4.     <add input="{CACHE_URL}" pattern="^(https?)://" />  
  5.   </conditions>  
  6.   <action type="Rewrite" url="{C:1}://internalserver/{R:1}" />  
  7. </rule>  

9. Rewrite/Redirect Based on Query String Parameters

When rewriting/redirection decisions are being made by using values extracted from the query string, very often one cannot rely on having the query string parameters always listed in exact same order. So the rewrite rule must be written in such a way so that it can extract the query string parameters independently of their relative order in the query string.
The following rule shows an example of how two different query string parameters are extracted from the query string and then used in the rewritten URL:

  1. <rule name="Query String Rewrite">  
  2.   <match url="page\.asp$" />  
  3.   <conditions>  
  4.     <add input="{QUERY_STRING}" pattern="p1=(\d+)" />  
  5.     <add input="##{C:1}##_{QUERY_STRING}" pattern="##([^#]+)##_.*p2=(\d+)" />  
  6.   </conditions>  
  7.   <action type="rewrite" url="newpage.aspx?param1={C:1}&amp;amp;amp;param2={C:2}" appendQueryString="false"/>  
  8. </rule>  
With this rule, when request is made to page.asp?p2=321&p1=123, it will be rewritten to newpage.aspx?param1=123&param2=321. Parameters p1 and p2 can be in any order in the original query string.

10. Avoid Rewriting of Requests for ASP.NET Web Resources

ASP.NET-based web applications very often make requests to WebResources.axd file to retrieve assembly resources and serve them to the Web browser. There is no such file exists on the server because ASP.NET generates the content dynamically when WebResources.axd is requested. So if you have a URL rewrite rule that does rewriting or redirection only if requested URL does not correspond to a file or a folder on a web server’s file system, that rule may accidentally rewrite requests made to WebResources.axd and thus break your application.
This problem can be easily prevented if you add one extra condition to the rewrite rule:

  1. <rule name="RewriteUserFriendlyURL1" stopProcessing="true">  
  2.   <match url="^([^/]+)/?$" />  
  3.   <conditions>  
  4.     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />  
  5.     <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />  
  6.     <!--  The following condition prevents rule from rewriting requests to .axd files -->  
  7.     <add input="{URL}" negate="true" pattern="\.axd$" />  
  8.   </conditions>  
  9.   <action type="Rewrite" url="article.aspx?p={R:1}" />  
  10. </rule>