Thursday, November 27, 2014

Replace default MVC Javascript serializer with Json.Net Serializer

Default javascript serializer in .Net is not the best when it comes to dates. Mvc uses a proprietary date format. To avoid all this and circular reference issues, read the following article to use Json.Net as a the serializer.

http://wingkaiwan.com/2012/12/28/replacing-mvc-javascriptserializer-with-json-net-jsonserializer/ 

Tuesday, December 18, 2012

Defining Javascript class

Robert has a very good article on his blog.

This article shows how to define a class, private, public and static variables.


Monday, March 5, 2012

XSLT development– display XML

While working on a xslt project, got to know about this xslt file which lets you output the xml as is. This is excellent for debugging purposes to see what xml the xslt file gets to work on.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:output method="xml" indent="yes" />

<xsl:template match="/ | @* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

Tuesday, May 31, 2011

Adding more config files by project build type

As people have already noticed that in .Net 4.0 web project, there are multiple versions of Web.config file such as Web.Debug.config and Web.Release.config. Developers can also add more files like this for e.g ConnectionStrings.config can also have ConnectionStrings.Debug.config and ConnectionStrings.Release where Debug and Release are Configuration of a project.

Lets look at the scenario where we would want to add ConnectionStrings file version so it uses the proper config file depending on the project build configuration type.

Step 1 – Add new ConnectionString files to your project

Add 4 configuration file to your project as follows:

- ConnectionStrings.config
- ConnectionStrings.Template.config
- ConnectionStrings.Debug.config
- ConnectionStrings.Release.config

File for debug and release contents will look like following:

<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xdt:Transform="Replace">
  <add name="MyConnectionString" connectionString="Address=[server],1433;Database=[database];UID=[user];PWD=[password];"/>
</connectionStrings>





You can add as many connection strings depending on which build type you want them to be associated with in its respective file. Like ConnectionStrings.Debug.config will contain connection strings to our development environment which we want to use in “Debug” mode.


ConnectionStrings.Release.config will contain connection strings to our production environment when we build the project for “Release”.


For now, file ConectionStrings.Template.config contents don’t have to have any connection strings in it since it’ll be used as a template to create ConnectionString.config file. You can add connection string in this file if they are not specific to a project build type and you always want them to be there. But for now, it’ll be empty like following:


<?xml version="1.0"?>
<!-- connection strings -->
<connectionStrings>
  
</connectionStrings>



Step 2 – Update project file


We are going to add some xml to the project file so Visual Studio build knows how to associate different ConnectionString files together. Also, Visual Studio will show connection string files in a nested tree in solution explorer.


We’ll add some build tasks so Visual Studio uses the proper ConnectionString file depending on the project build type.


Right click on project node in solution explorer and choose unload project option. This allows you to open project xml file and update it. Right click again and choose Edit [Project.csproj]. You’ll notice that xml file for project will appear for edit.


Under /Project/ItemGroup, Add Following:


<Content Include="App_Config\Server\ConnectionStrings.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <None Include="App_Config\Server\ConnectionStrings.Template.config" />
    <None Include="App_Config\Server\ConnectionStrings.Debug.config">
      <DependentUpon>ConnectionStrings.Template.config</DependentUpon>
    </None>
    <None Include="App_Config\Server\ConnectionStrings.Release.config">
      <DependentUpon>ConnectionStrings.Template.config</DependentUpon>
    </None>



This tells visual studio to show debug and release files for connection string nested under ConnectionStrings.Template.config node in solution explorer. Please note that we are assuming that connection string config files are saved under /[ProjectFolder]/App_Config/Server folder.


Next, to the very bottom of project xml file under /Project, below <import> tag(s) add:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />



This lets you use TransformXml task which we’ll use below.


Under this “UsingTask” node add:


<Target Name="ConfigConnectionStrings" Condition="Exists('./App_Config/Server/ConnectionStrings.$(Configuration).config')">
  <Delete Files="./App_Config/Server/ConnectionStrings.config" />
  <TransformXml Source="./App_Config/Server/ConnectionStrings.Template.config" Destination="./App_Config/Server/ConnectionStrings.config" Transform="./App_Config/Server/ConnectionStrings.$(Configuration).config" />
</Target>
<Target Name="BeforeBuild">
  <Copy SourceFiles="./App_Config/Server/ConnectionStrings.Template.config" DestinationFiles="./App_Config/Server/ConnectionStrings.config" />
  <CallTarget Targets="ConfigConnectionStrings" />
</Target>



The above piece tells Visual Studio to delete ConnectionStrings.config file so we always have a new copy created whenever we build the project and there are no read/write issues. Then it instructs the project build to transform the appropriate connection string file based on project build type.


It also adds  “BeforeBuild” target which copies the empty ConnectionStrings.Template.config file as ConnectionStrings.config which we’ll fill based on the project build type.


Right after the copy, it directs the project build to call the ConfigConnectionStrings target which performs the delete of older ConnectionStrings.config copy and does the transformation.


Now once you save your project file and right click on project node in solution explorer, choose “reload project” option to load the project along with all its files in solution explorer.


Step 3 – Add external ConnectionString file reference to web.config


To keep connection strings outside of the web.config file, we have to add the following line under /configuration node.


 <connectionStrings configSource="App_Config\Server\ConnectionStrings.config" />



Step 4 – Excluding ConnectionStrings.config file from project


Last but not least, we have to exclude ConnectionStrings.config file from the project list in solution explorer so it can be deleted/created by project build. Since we are using svn at work, we have to do an additional step to ignore the file from svn. If you are using AnkhSvn Visual Studio plug-in, you can right click on ConnectionStrings.config file and go to Subversion > Ignore > Ignore File (ConnectionStrings.config) option.


That’s it folks, now when you build the project, you’ll see a new copy of ConnectionStrings.config file created with your connection strings based on your project build type.

Friday, September 24, 2010

Message Queue using cloud computing – Azure and Amazon

Recently I was involved in an assignment which involved using messagequeue. We ended up implementing both Amazon and Azure as Queue providers. With libraries available for both of them, its very easy to integrate both in application.

Amazon Web Services

Amazon provides SDK for many platforms such as Java, PHP, Python, Ruby and .Net. SDK makes it very easy to incorporate any cloud computing service in your application.

Three simple Steps to incorporate Amazon Queue in .Net apps:

  1. Download the SDK
  2. Reference AWSSDK.dll in your project
  3. Write code (Found the SDK samples to be very helpful and easy to understand)

Windows Azure

Just like Amazon, Azure provides SDKs for Java and .Net. I liked Amazons approach that they give you the code samples with SDK. Azure does give you some code samples but they don’t include samples for Queue and not for every services which it provides. To get all the samples, you can get them from here (Make sure to download samples which are marked as Additional C# Samples)

Same with Azure, simple steps to incorporate

  1. Download the SDK from here .
  2. Reference  Microsoft.WindowsAzure.StorageClient.dll in your project
  3. Write code

One thing I noticed is that Queue names has to be in a certain format else you’ll get an exception response. Naming conventions are found here.

Enjoy Cloud computing!

Monday, September 13, 2010

Remove Navbar from Blogspot

Was wondering if it’s possible to remove the Navbar and have found a video post which describes all you need to do. The css update which you need in your HTML is as follows:

   1: #navbar-iframe{
   2:     display: none !important; /*nav bar*/
   3: }

Video post link: http://blogger-templates.blogspot.com/2005/01/remove-navbar.html

Wednesday, September 8, 2010

Using windows authentication for WCF service in .Net 4.0

A friend of mine was building a WCF service with windows authentication and ran into a couple issues. He found the solution and posted the solution at http://stackoverflow.com/questions/1367653/wcf-service-windows-authentication

Tuesday, September 7, 2010

Default Namespace project property difference between C# and VB.Net

If you right click on a project in Visual Studio (2010), under application tab there is a property called Default namespace. Both C# and VB.Net treat it differently.

In VB.Net, by specifying default namespace project property, it is default root namespace of your library if you don't specify any for your class which is really what it should do I think. For instance, if you had a following class in file MyClass.vb and it had no namespace defined and your default namespace in project setting was set to MyApplication, you will access this class as MyApplication.MyClass.

   1: Class MyClass
   2:     Public Function MyMethod()
   3:         ' Do something
   4:     End Function
   5: End Class

In C#, default namespace property is only used as a namespace template name when you create new files. It does not effect the root namespace of your library (dll). For instance, If default namespace was set to MyApplication with following class then your class will end up in no namespace. To access your class in other projects, you just have to type MyClass which is not the solution one would want to keep, since all classes from this library will end up in default namespace (no namespace).



   1: class MyClass
   2: {
   3:     public void MyMethod()
   4:     {
   5:         // Do something
   6:     }
   7: }

Monday, September 6, 2010

Dependency Injection – Unity IoC Container

Had been looking around on the web to pick one of the dependency injection container and came across video from David Hayden. Its a great video for quick start and shows a lot of features of Unity.

You can watch the video at: http://www.pnpguidance.net/Screencast/UnityDependencyInjectionIoCScreencast.aspx

Wednesday, September 1, 2010

Using Fiddler to test WCF Post methods

By default, WCF only allows JSON and XML for post data. It'll not allow callers to post data using html forms unless mime type application/x-www-form-urlencoded is supported.

In order to post data, json or xml, view the service /help page which gives you the exact format. This message template can be used as fiddler Request Body under Request Builder Tab.

When mime type application/x-www-form-urlencoded is enabled from wcf service. past the query string in Request Body

For e.g. if your html link was like http://www.mysite.com/index.html?param1=1&param2=2&param3=3

In Fiddler Request Builder
- Set Method to Post
- url as http://www.mysite.com/index.html
- Request Header
    User-Agent: Fiddler
    content-type: application/x-www-form-urlencoded
- Request Body
    param1=1&param2=2&param3=3

Also if an object was excepted on wcf side, for instance following service contract
getData(Person p)

Where p is

class Person
{
    [DataMember]
    public string name;
    [DataMember]
    public string age;
}

Request Header will be the same as above but Request Body will be like:
Person.name=John Smith&Person.age=25

As a best practice, keep your Request Body case sensitive to avoid any issues.

Tuesday, August 31, 2010

Efficient SQL Profiling

 

When you have to run SQL Profiler to view activity, if database server is used by multiple people or accounts which you want to view, there could be a lot of activity going on the server. It gets very confusing or near impossible to find out which sql statements or profiler activity you should look at.

The best way to view activity initiated by you is to use a Hostname filter.

You can even create a template so you don't have to create a filter every time you want to run sql profiler.

1. Open SQL Server Profiler
2. Create New Template (Base it on Standard template)
  SQL Profile - New Template
3. Click on Column Filter in Event Selection Tab and Define Hostname Like as your machine name. Make sure to check show all columns
 SQL Profiler - Step2
4. Save Template
Once template is saved. You can create a new trace using the template you just created with Hostname filter.
SQL Profiler - Step3

Upon running the trace, you'll see traces originated only from your machine.

Happy tracing!

Friday, August 20, 2010

DateAdd : reusable Javascript function

 

While looking for a Javascript equivalent of DataAdd VB or SQL method, I came across this function which is working flawlessly. Please visit the forum post to view it directly and also as follow:

   1: function DateAdd(timeU,byMany,dateObj) {
   2:     var millisecond=1;
   3:     var second=millisecond*1000;
   4:     var minute=second*60;
   5:     var hour=minute*60;
   6:     var day=hour*24;
   7:     var year=day*365;
   8:  
   9:     var newDate;
  10:     var dVal=dateObj.valueOf();
  11:     switch(timeU) {
  12:         case "ms": newDate=new Date(dVal+millisecond*byMany); break;
  13:         case "s": newDate=new Date(dVal+second*byMany); break;
  14:         case "mi": newDate=new Date(dVal+minute*byMany); break;
  15:         case "h": newDate=new Date(dVal+hour*byMany); break;
  16:         case "d": newDate=new Date(dVal+day*byMany); break;
  17:         case "y": newDate=new Date(dVal+year*byMany); break;
  18:     }
  19:     return newDate;
  20: }

Tuesday, August 10, 2010

Using a Stored Procedure in Entity Framework 4

If you have worked with LINQ and added stored procedures to it, it would seem obvious to be able to it the same way in Entity framework.

In LINQ all you had to do is to drag the stored procedure from your Server Explorer respective data connection on your model diagram.

In entity framework 4, there are few steps and they are different.

1. On your entity diagram in visual studio, right click and choose Update Model from database.

2. Add your stored procedure from the wizard. What it does, it adds the proc to your diagram. Its not visible in .Net code yet.
If you go to Model Browser > {EntityModel}.Store > Stored Procedures, it should be visible in there now

3. Right click, Add > Function Import. Complete this according to your requirement, name of the proc you want to see in .Net, which stored proc it maps to and what is the collection it returns etc.

After step 3 you can access access the proc using an instance of context.

For more visual representation of the steps, please visit WebLog of Ken Cox

Wednesday, August 4, 2010

Extracting tags from xhtml content

There are two ways of doing it. One is the dirty way, using Mid function in VB.Net or IndexOf string method but the more appropriate way would be to use regular expressions.

Following code will get you title using regular expression
Regex regex = new Regex("<title>(?<title>.*?)</title>", RegexOptions.IgnoreCase);
Match titleMatch = regex.Match(html);
string title = titleMatch.Groups["title"].Value;
Following code will get you meta tag My_Meta

Regex regex = new Regex("<META +NAME=\"(?<name>My_Meta*?)\" +CONTENT=\"(?<content>.*?)\" */?>", RegexOptions.IgnoreCase);
Match metaMatch = regex.Match(html);

title = metaMatch.Groups["content"].Value;

Thursday, July 15, 2010

Saving objects using Entity framework

TableClass tableObject = new TableClass();
tableObject.property1 = "Hello";
tableObject.proeprty2 = "World";

// NOTE: make sure to use the same instance of entityContextObject which was used to populate the tableObject (e.g. updating back to database)
entityContextObject.AddToTableClass(tableObject);
entityContextObject.SaveChanges();

Minimize Outlook 2007/2010 to tray

Very easy fix but it should be a default I think. Anyways in 2 easy steps:

1. Click on outlook icon in Notification area (Beside the clock in task bar)
2. Choose Hide when minimized

How to minimize MSN Messenger to the system tray in Windows 7

Not sure why Microsoft has changed the behavior in Windows 7 but its annoying that it takes up two programs in task bar when its running. Follow the link below to see the solution.

Link: http://windows7center.com/tutorials/how-to-minimize-msn-messenger-to-the-system-tray-in-windows-7/

Monday, June 28, 2010

Wednesday, April 14, 2010

Wednesday, March 31, 2010

outputting all attributes except one in xsl

In order to avoid outputting one attribute among all the attributes of a tag, following xpath can be used