Thursday, June 18, 2015

ServiceConfiguration transformation

ServiceConfiguration transformation:

This will help us to build the package immediately. You just need to add different configuration files, and give different values.

Add following sections in cloud solution ccproj
<ServiceConfiguration Include="ServiceConfiguration.production.cscfg" />
<ServiceDefinition Include="ServiceDefinition.csdef" />
<ServiceConfiguration Include="ServiceConfiguration.Dev.cscfg" />
<ServiceConfiguration Include="ServiceConfiguration.Int.cscfg" />
<ServiceConfiguration Include="ServiceConfiguration.Staging.cscfg" />
<ServiceConfiguration Include="ServiceConfiguration.Local.cscfg" />
<ServiceConfiguration Include="ServiceConfiguration.Cloud.cscfg" />


<PropertyGroup Condition=" '$(Configuration)' == 'Dev' ">
<PropertyGroup Condition=" '$(Configuration)' == 'Int' ">
<PropertyGroup Condition=" '$(Configuration)' == 'Staging' ">
<PropertyGroup Condition=" '$(Configuration)' == 'Production' ">

<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets" />
<EnvironmentDefinition Include="ServiceDefinition.Debug.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Production.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Int.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Local.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Dev.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Cloud.csdef">
<EnvironmentDefinition Include="ServiceDefinition.Staging.csdef">
<None Include="@(EnvironmentDefinition)" />
<Target Name="ValidateServiceFiles" Inputs="@(EnvironmentDefinition);@(EnvironmentDefinition->'%(BaseConfiguration)')" Outputs="@(EnvironmentDefinition->'%(Identity).transformed.csdef')">
<Message Text="ValidateServiceFiles: Transforming %(EnvironmentDefinition.BaseConfiguration) to %(EnvironmentDefinition.Identity).tmp via %(EnvironmentDefinition.Identity)" Importance="High" />
<TransformXml Source="%(EnvironmentDefinition.BaseConfiguration)" Transform="%(EnvironmentDefinition.Identity)" Destination="%(EnvironmentDefinition.Identity).tmp" />
<Message Text="ValidateServiceFiles: Transformation complete; starting validation" Importance="High" />
<ValidateServiceFiles ServiceDefinitionFile="%(EnvironmentDefinition.Identity).tmp" ServiceConfigurationFile="ServiceConfiguration.$(Configuration).cscfg" />
<Message Text="ValidateServiceFiles: Validation complete; renaming temporary file" Importance="High" />
<Move SourceFiles="%(EnvironmentDefinition.Identity).tmp" DestinationFiles="%(EnvironmentDefinition.Identity).transformed.csdef" />
<Target Name="MoveTransformedEnvironmentConfigurationXml" AfterTargets="AfterPackageComputeService">
<Copy SourceFiles="ServiceDefinition.$(Configuration).csdef.transformed.csdef" DestinationFiles="$(OutDir)ServiceDefinition.csdef" />

<Target Name="PublishVirtualApplicationsBeforeCSPack" BeforeTargets="CorePublish;CsPackForDevFabric" Condition="'$(PackageForComputeEmulator)' == 'true' Or '$(IsExecutingPublishTarget)' == 'true' ">
<Message Text="Start - PublishVirtualApplicationsBeforeCSPack" />
<PropertyGroup Condition=" '$(PublishDestinationPath)'=='' and '$(BuildingInsideVisualStudio)'=='true' ">
<!-- When Visual Studio build -->
<PropertyGroup Condition=" '$(PublishDestinationPath)'=='' ">
<!-- When TFS build -->
<Message Text="Publishing '%(VirtualApp.Identity)' to '$(PublishDestinationPath)%(VirtualApp.PhysicalDirectory)'" />
<MSBuild Projects="%(VirtualApp.Identity)" ContinueOnError="false" Targets="PublishToFileSystem" Properties="Configuration=$(Configuration);PublishDestination=$(PublishDestinationPath)%(VirtualApp.PhysicalDirectory);AutoParameterizationWebConfigConnectionStrings=False" />
<!-- Delete files excluded from packaging; take care not to delete xml files unless there is a matching dll -->
<CreateItem Include="$(PublishDestinationPath)%(VirtualApp.PhysicalDirectory)\**\*.dll">
<Output ItemName="DllFiles" TaskParameter="Include" />
<FilesToDelete Include="@(DllFiles -> '%(RootDir)%(Directory)%(Filename).pdb')" />
<FilesToDelete Include="@(DllFiles -> '%(RootDir)%(Directory)%(Filename).xml')" />
<Message Text="Files excluded from packaging '@(FilesToDelete)'" />
<Delete Files="@(FilesToDelete)" />
<Message Text="End - PublishVirtualApplicationsBeforeCSPack" />

Happy Coding!!

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.

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

Source :

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

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.

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.


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.

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.


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.

<%@ 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>");

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:
<%: Model.Content %>

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:

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:

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

Happy Coding!!