Tuesday, April 28, 2015

Azure : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Problem: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.


Solution:
In azure, while running the project in temporary folder it creates your azure project and its related files. some dll names are large so in result whole path is large and which results in above error.

There are 2 solutions to solve this issue:

Solution 1:
Step 1: Open .ccproj project
Step 2: Under PropertyGroup Add following line
           <ServiceOutputDirectory>C:\azuretmp\</ServiceOutputDirectory>

Source : http://govada.blogspot.in/2011/12/windows-azure-package-build-error.html


Solution 2:
Step 1: Right click on "My Computer" -> Select Properties
Step 2: Click on "Remote Setting" -> Select Advanced -> Select Environment variables -> Click on "New" -> Add Variable name as "_CSRUN_STATE_DIRECTORY"
and Add Variable value as whatever you want. ex: C:\A -> click on save
Source: http://blogs.msdn.com/b/jnak/archive/2010/01/14/windows-azure-path-too-long.aspx

Happy Coding !! 

Friday, April 24, 2015

The underlying connection was closed: An unexpected error occurred on a receive.System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

I get following error while working with REST API and i do following code change to resolve this issue.

Error:
The underlying connection was closed: An unexpected error occurred on a receive.System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

To resolve above error add following properties to webrequest object
HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
            webRequest.KeepAlive = false;            webRequest.ProtocolVersion=HttpVersion.Version10;

Happy Coding !!  

Friday, April 10, 2015

JSON to Dataset conversion

Sometimes we need to convert json to dataset in that case following code snippet will help us.

Code snippet :

public DataSet ConvertJsonToDataSet(string jsonString)
        {
                XmlDocument xd = new XmlDocument();
                jsonString = "{ \"myrootNode\": {" + jsonString.Trim().TrimStart('{').TrimEnd('}') + "} }";
                xd = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString);
                DataSet ds = new DataSet();
                ds.ReadXml(new XmlNodeReader(xd));
                return ds;
          }

Happy Coding !!

Tuesday, March 31, 2015

Filename convenventions while uploading files.

Issue:

When you attempt to create, save, or rename a file, folder, or shortcut, you may receive one of the following error messages:
A filename cannot contain any of the following characters:\ / : * ? " < > | or This filename is not valid

Resolution :
To create, save, or rename a file, folder, or shortcut, use a valid character, dont use following charachters:
 \ / : * ? " < > |
Characters that are valid for naming files, folders, or shortcuts include any combination of letters (A-Z) and numbers (0-9),
plus the following special characters:
   ^   Accent circumflex (caret)
   &   Ampersand
   '   Apostrophe (single quotation mark)
   @   At sign
   {   Brace left
   }   Brace right
   [   Bracket opening
   ]   Bracket closing
   ,   Comma
   $   Dollar sign
   =   Equal sign
   !   Exclamation point
   -   Hyphen
   #   Number sign
   (   Parenthesis opening
   )   Parenthesis closing
   %   Percent
   .   Period
   +   Plus
   ~   Tilde
   _   Underscore


Happy Coding !! 

Encode Web Output for ASP.NET code that generates HTML using some input

If ASP.NET code that generates HTML using some input, we need to evaluate appropriate action for application.
Encoding output methods:

  •    Encode HTML output.
  •    Encode URL output.
  •    Filter user input.


Encode HTML Output:


If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the HttpUtility.HtmlEncode method as shown in the following code example.
Do this if the text came from user input, a database, or a local file.
 
    Response.Write(HttpUtility.HtmlEncode(Request.Form["stringvalue"]));


Encode URL Output:


If you return URL strings that contain input to the client, use the HttpUtility.
UrlEncode method to encode these URL strings as shown in the following code example.

    Response.Write(HttpUtility.UrlEncode(urlString));

Filter User Input:


If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page.
If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept.
A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).
To safely allow restricted HTML input Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
Encode the string input with the HtmlEncode method.
Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.

e.g.
<%@ Page Language="C#" ValidateRequest="false"%>
StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(htmlInputTxt.Text));
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
Response.Write(sb.ToString());

New <%: %> Code Nugget Syntax:

With ASP.NET 4 we are introducing a new code expression syntax (<%:  %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so.  This eliminates the need to explicitly HTML encode content like we did in the example above.  Instead, you can just write the more concise code below to accomplish the exact same thing:
e.g.
<div>
<%: Model.Content %>
</div>


Happy Coding !! 

Defending Against XML Bombs

Using System.Xml.XmlDocument/XmlDataDocument LoadXml() method is potentially unsafe, replace with the Load().The easiest way to defend against all types of XML entity attacks is to simply disable altogether the use of inline DTD schemas in your XML parsing objects.

In .NET Framework versions 3.5 and earlier, DTD parsing behavior is controlled by the Boolean ProhibitDtd property found in the System.Xml.XmlTextReader and System.Xml.XmlReaderSettings classes. Set this value to true to disable inline DTDs completely:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = true;
XmlReader reader = XmlReader.Create(xmlstream, settings);
The default value of ProhibitDtd in XmlReaderSettings is true, but the default value of ProhibitDtd in XmlTextReader is false, which means that you have to explicitly set it to true to disable inline DTDs.
In .NET Framework version 4.0 DTD parsing behavior has been changed. The ProhibitDtd property has been deprecated in favor of the new DtdProcessing property. You can set this property to Prohibit (the default value) to cause the runtime to throw an exception if a <!DOCTYPE> element is present in the XML:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(xmlstream, settings);


Happy Coding!! 

AES 256 bits Encryption & Decryption

To Encrypt or decrypt value using AES algorithm use following functions. Following are generalize function which you can use it directly into your project.

1. Encryption:


        /// <summary>
        /// encrypt string using AES algo
        /// </summary>
        /// <param name="data">data string to encrypt</param>
        /// <returns>encrypted string</returns>
        public static string GetEncryptedDataAES(string data)
        {
            AesManaged aesManaged = new AesManaged();
            UTF8Encoding utf8 = new UTF8Encoding();
            aesManaged.Key = utf8.GetBytes("<Encrypttionkey>");
            aesManaged.IV = utf8.GetBytes("<initializationvectorKey>");
            // Encrypt the string to an array of bytes.
            byte[] encrypted = EncryptStringToBytesAES(data, aesManaged.Key, aesManaged.IV);
            data = Convert.ToBase64String(encrypted);
            data = HttpContext.Current.Server.UrlEncode(data);
            return data;
        }
        /// <summary>
        ///  encrypt string to byte using AES algo
        /// </summary>
        /// <param name="plainText">sring to encrypt</param>
        /// <param name="Key"> encrypt key</param>
        /// <param name="IV">Initialization vector</param>
        /// <returns>byte array of encrypt string</returns>
        static byte[] EncryptStringToBytesAES(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            // Declare the AesManaged object
            // used to encrypt the data.
            AesManaged aesAlg = null;
            try
            {
                // Create a AesManaged object
                // with the specified key and IV.
                aesAlg = new AesManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
            }
            finally
            {
                // Clear the AesManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }

------------------------------------------------------------------------------------------------------------------------------

2. Decryption:


        /// <summary>
        /// decrypt the encrypted string using AES
        /// </summary>
        /// <param name="data">string to decrypt</param>
        /// <returns>decrypted string </returns>
        public static string GetDecryptedDataAES(string data)
        {
            byte[] dataBytes = Convert.FromBase64String(data);
            AesManaged aesManaged = new AesManaged();
            UTF8Encoding utf8 = new UTF8Encoding();
            aesManaged.Key = utf8.GetBytes("<Encrypttionkey>");
            aesManaged.IV = utf8.GetBytes("<initializationvectorKey>");
            data = DecryptStringFromBytesAES(dataBytes, aesManaged.Key, aesManaged.IV);
            return data;
        }
     
        /// <summary>
        /// decrypt encrypted string from byte using AES algo
        /// </summary>
        /// <param name="cipherText">byte array to decrypt</param>
        /// <param name="Key"> encrypt key</param>
        /// <param name="IV">Initialization vector</param>
        /// <returns>decrypted string </returns>
        private static string DecryptStringFromBytesAES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            AesManaged aesAlg = null;
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;
            try
            {
                // Create a AesManaged object
                // with the specified key and IV.
                aesAlg = new AesManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the AesManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return plaintext;
        }

Happy Coding