Wednesday, May 22, 2013

Basic Ajax request

If we have to create an application that uses Ajax to dynamically get and manage data in an MVC 3 project we have to create a controller action that will deal with the Ajax request and an Ajax call at the user interface level which will call the action and manage the output. To implement this we first need to write down the following controller action.

Controller: 

public class HomeController : Controller
{
                public ActionResult TestAjax(string input)
{
List<string> output = new List<string>(){"a","b","c"};
output.Add(input);
       return Json(output, JsonRequestBehavior.AllowGet);
}
}

This is just like a normal controller action which takes input in the form of a string (called input), appends it to the list ‘output’ and returns the result as a JSon object (instead of a view which typical controllers return).
After this we need to write the following jQuery code to call this action and manage its result.
 

jQuery:

$(document).ready(function () {
   
    $(".link").click(function () {       
        $.ajax({
            type: "GET",
            url: "/Home/TestAjax",
            data: {input: "d"},
            dataType: "json",
            success: function(data) {
                alert(data);
            }
        });

    });
});

In the code above we have a javascript function that is executed whenever we click the control with class "link". This function creates a GET request to the url “…/Home/TestAjax” (which you might have noticed are the names of the controller and action we created above) and passes "d" to the actions’ input parameter “input”. The controller then creates a list containing "a,b,c" and appends the input parameter "d" to it and returns the final string i.e "a,b,c,d" as a JSon object. Once the controller successfully returns this output, the javascript function in the “success” parameter is executed, which gets the output provided by the action in its own variable “data” and shows it as an alert as shown below:




And that is it, a simple Ajax call made.

P.S: You might have noticed that this code is added to the document.ready function. This is done because if we don’t place it there we would have to specifically add it to the control’s onclick event.

Monday, March 18, 2013

Preview web.config transforms

If we have a solution that gets deployed onto a test environment before going live we will have different connection strings for each environment and various other settings that change from one environment to another.  In such cases, while deploying our solution to different environments we would have to change our web.config files to match each environment.


Let's suppose we have got the following connection string in our web.config file:

<add name="mainDB" connectionString="con1" providerName=" EntityClient" />

which, during deployment to the test environment changes to this:

<add name="mainDB" connectionString="conb" providerName=" EntityClient" />


To do this, we can maintain multiple web.config files for each environment and manually copy paste them during deployment or create a web.config transformation file which will automatically do it for us, saving us from maintaining multiple web.config files. 

To create a web.config transformation file we need to go to Build -> Configuration Manager. Once there we need to open the dropdown labelled "Active solution configuration" and click "< New...>". After this we need to follow the steps to create a new configuration. Once created, you will notice that the Web.config file will have a new file listed under it called web.[environment_name].config (Where environment_name is the name you just specified).

This new file is the web.config transformation file for your specified environment. Once we have created this file all we need to do is write down the differences between the existing and transformed web.config file in a proper syntax and everything is sorted during deployment. (To learn more about this syntax you can visit this page.)
 

As an example we can use the following syntax to transform the connection strings discussed above:

<add name="mainDB" connectionString="conb" providerName=" EntityClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />

The above line says: look for a web.config key whose attribute “name” is "mainDB"  and set all its attributes to the new value(s) listed. So the connection string becomes “conb” and the provider name becomes “ EntityClient” (if we had provided a different provider name here, that would have overridden the existing value).

Once this is all done, we need to test whether the transformation works fine. One way of doing it is to go through the entire build process and check the web.config file that comes out of it. Another way of doing this is to put the existing web.config file and the transformation web.config file onto a dodgy server and test the output (there are many freeware online tools available to do this).






Alternatively, you can download a visual studio extension called Slow Cheetah which will make it as easy as two clicks to see your transformed file.

This extension adds a new option when you right click on a web.config transformation file called "Preview Transform" (as shown above).

Once you click "Preview Transform" you are provided with a very easy interface which shows you both files side by side and that’s it, job done no need to build/deploy your solution or post your data onto dodgy servers.




Sunday, September 23, 2012

Oracle: Insert row with unique Id

If we have a table called “employee” containing two columns “id” and “name” and we want to write a query that could be reused to add a new row to the table, we could use the following:

Insert into employee (id, name) values ((select max(id) +1 from employee), ‘name_of_employee’)

This is a very simple solution, however the problem here is that if we have two servers trying to run this query at the same time, things could become a bit messy (in case if the same id value is returned to both these servers).

A clean solution for this is to use a trigger and a sequence. The theory behind this is that we have a sequence that goes through each row of a table and returns the first available value of id. We could then create a trigger that will run when an insert statement is executed with a null id value. This trigger will use the sequence to get the first available id and assign it to the new row being added.

Because this would all be happening at the database level, we will not have to worry about multiple servers (application servers) trying to add a new row to the database (which is usually in a separate database server).

An implementation of the given theory can be as follows:

  • A sequence is created that returns the first available id.
  • A trigger is created that runs whenever a new row is being added with a null id, replacing it with what the sequence returns.
  • A code that uses the following insert statement: insert into employee (id, name) values (null, ‘name_of_employee’).

To create a simple sequence we could use the following code:

Create sequence NAME_OF_SEQUENCE
Minvalue 1
Maxvalue 999999999
Increment by 1
Start with 1
Nocache
Noorder
Nocycle

To create the trigger discussed above, we could use the following sql:

Create or replace Trigger NAME_OF_TRIGGER
Before insert On NAME_OF_TABLE
For each row
Declare

Begin
If :new.ID is null then
Select NAME_OF_SEQUENCE.nextval
Into :new.ID
From dual
End if;
END;

And that's it, a nice clean solution giving a unique id to new rows.

PS: This solution will not reassign the id values of deleted rows, so every time the sequence runs, it starts from where it last ended and not from 1.

Wednesday, March 28, 2012

Atom feeds using .NET's built in functionality

We can create RSS 2.0 and Atom 1.0 feeds in .NET using the Syndication feed class as shown below. In this example we will generate Atom 1.0 feeds (you could also do some minor tweaks to this code and generate RSS 2.0 feeds).

For clarification, we will create a feed called “News” containing a single item called “Article1”.



public XmlElement TestFeed()
{
var feed = new SyndicationFeed();
       feed.Title = new TextSyndicationContent("News");
       feed.Id = "123";   
feed.LastUpdatedTime = DateTime.Now;

       SyndicationItem item = new SyndicationItem();
       item.Id = "1";
       item.Title = new TextSyndicationContent("Article1");
       item.LastUpdatedTime = DateTime.Now;

       item.Authors.Add(new SyndicationPerson(null, "Author-Name", null));
       item.Content = new TextSyndicationContent("The entire article comes here");
       item.Links.Add(new SyndicationLink(new Uri("http://www.news.com/etc")));
        
       List<SyndicationItem> items = new List<SyndicationItem>();
       items.Add(item);

       feed.Items = items;

       XmlDocument document = new XmlDocument();
       XmlWriter writer = document.CreateNavigator().AppendChild();
       Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);
       atomFormatter.WriteTo(writer);
       writer.Close();

       return document.DocumentElement;        
}

According to Atom 1.0 feeds standard, the only compulsory fields in an item (“Article1” in this case) are “id”, “title”, and “updated”, the rest are optional. They have been added just to clear some ambiguities regarding the addition of url and author name in a syndication class. 

For more information about Atom 1.0 feeds standard you could visit this page.

Thursday, February 16, 2012

Omniture Site Catalyst Overview

Omniture Site catalyst is a web analytics solution that gives us a summarised overview of customer behaviours on our site.

It is implemented through javascript code executed by the browser while rendering the page. This code gathers all relevant information and sends it to Omniture’s site catalyst servers as a request for a 1×1 pixel transparent image.

Implementing Site Catalyst

Site catalyst implementation involves adding the following two components to a website:
  • Adding/hosting a javascript file to the solution (this file can be taken from Omniture once an account for website tracking is created there)
  • Injecting some javascript code in every page that needs to be tracked.

A sample javascript code which is injected in each tracked page is shown below (taken from www.webmetric.org).

Note: In this code, the values we give to each of the variables such as pageName, server, channel etc. is the customer information we will be collecting. For example we can give a different pageName value to each page and get individual page traffic for each of our pages.

<!-- SiteCatalyst code version: H.17.
Copyright 1997-2008 Omniture, Inc. More info available at
http://www.omniture.com -->

<script language="JavaScript" type="text/javascript" src="http://INSERT-
DOMAIN-AND-PATH-TO-CODE-HERE/s_code.js"></script>

<script language="JavaScript" type="text/javascript">
<!--
/* You may give each page an identifying name, server, and channel on
the next lines. */
s.pageName=""
s.server=""
s.channel=""
s.pageType=""
s.prop1=""
s.prop2=""
s.prop3=""
s.prop4=""
s.prop5=""
/* Conversion Variables */
s.campaign=""
s.state=""
s.zip=""
s.events=""
s.products=""
s.purchaseID=""
s.eVar1=""
s.eVar2=""
s.eVar3=""
s.eVar4=""
s.eVar5=""

/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code=s.t();if(s_code)document.write(s_code)//--></script>
<script language="JavaScript" type="text/javascript"><!--
if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!
-'+'-')
//--></script><noscript><a href="http://www.omniture.com" title="Web
Analytics"><img
src="http://devgundersen.112.2O7.net/b/ss/devgundersen/1/H.17--NS/0"
height="1" width="1" border="0" alt="" /></a></noscript><!--/DO NOT REMOVE/-->

<!-- End SiteCatalyst code version: H.17. -->

Thursday, December 22, 2011

Database connectivity using Entity Framework

Entity framework is a new concept which allows developers to code against a conceptual model (which we create ourselves) rather than coding directly against a relational schema (database). This means that developers can take a slice out of the database cake and eat it rather than having to worry about eating the whole cake as a single piece. To taste this cake, its best to create a simple application that uses entity framework to connect with a database. The following guide will help you do exactly that.

Create a new application (in this example I will be using an MVC3 application) and name it DatabaseProject. Go to the solution explorer and do the following: 

·         right click “Models”,
·         “Add ›”,
·         “New item”,
·         click “data” in the left hand tab then select “ADO.Net entity data model” and click “Add” (this will open a wizard)
·         In the wizard, click “Generate from database” and click next.

You can create a new database connection by clicking on “New connection”. It will start another wizard which will ask you for database related information (which sometimes includes the IP address of server hosting the database) and username/password. Once you have entered this information, click “Ok”.

You will now return to the original wizard where at the bottom you will have a ticked checkbox labelled “Save entity connection settings in web.config as:”. Under this label there will be a default name of “DecisionCentreEntities”. Change this is to NameofConnection for simplification. 

After changing the name click “Next”.

This will retrieve the list of all tables in the database with a checkbox next to each table. Check/tick the tables that you want in your model (or the tables that will be accessed by your code). After this, click “Finish” to exit the wizard. 

You can now see a diagram of selected tables on a white surface which should look like this (I only ticked one table but you can tick as many as you want). This is your data model:




·         In this diagram right click on the white surface and click “Add code generation item”.
·         Click “Code” in the left hand tab then select “ADO.NET Entity Object Generator” and click Add.
·         Build the project. 

Our data model is ready to use.

Go to the controller (or any other class) and run queries on the database tables using the data model you just created.

Add the following using statement on the top “using DatabaseProject.Models”.

In a simple example we will run a query (we will be using a Linq query as an example) which returns all rows from the table “customers”.

using(var db = new NameofConnection())
{
object obj = (from r in db. customers select r).ToList();
}

This code will perform the query “select * from customers” and return the result. The result will then be converted into a list which will be copied on to the object “obj”.

In another example we will run a query which will add a new row to the table “customers”.

using(var db = new NameofConnection())
{
db. customers.AddObject(row);
       db.SaveChanges();
}

With this we have now successfully tasted the cake and can use similar codes to perform other functions with our database.

Monday, October 31, 2011

RSS

RSS or Really Simple Syndication is a format used to organise content which can then be published or sent to different data consumers. For simplicity we will assume our content to be an article. When converting our article into RSS 2.0 format (which is what we will focus on) we have to create an XML file (XML version 1.0) and add certain elements to it. Once this is done, our document is ready.

There are two main components of an RSS file, the channel and item. To understand these components we have to consider an example of a newspaper. It has several articles, some grouped under the sports section, some grouped under finance section and so on.

The RSS feed which publishes these news articles will have a channel named sports and each sport article will be an item under this channel and we will have a similar channel for finance and all other sections.

With this scenario in mind, lets create our very own RSS feed to publish articles. In the example below we will be publishing two articles under the sports section and one under finance by a magazine called Magazine100. This is how our overall RSS feed would look like:

<rss version="2.0">

<channel>                         
<title>Sports</title>
<link>http://www.magazine100.com/sports</link>
<description>Sports news by magazine100</description>

<item>                
<title>cricket updates</title>
<description>Here you can paste the entire article</description>                           
</item>

<item>                
<title>football updates</title>
<description>Here you can paste the entire article</description>                           
</item>              

</channel>

<channel>         
<title>Finance</title>
<link>http://www.magazine100.com/finance</link>
<description>Finance news by magazine100</description>
               
<item>                
<title>wall street updates</title>
<description>Here you can paste the entire article</description>                           
</item>

</channel>

</rss>

As you can see at the top level we have <rss version="2.0">. This is a mandatory attribute that specifies the version that this document conforms to.

We then have a channel which is described by the tags <title>, <link> and <description>. These tags are mandatory for each channel, however if we feel the need to describe our channel further, there are several additional tags that we can use. You can get a list of these tags from here.

After channel, we have an item tag which uses <title> and <description> to publish the content of an article. For an item, it is mandatory to have at least one of these two fields (title and description), and similar to a channel, an item can also be further described using optional tags. You can get a list of these tags from here.

The problem with an item is that you do not have a tag to attach pictures. However this can be done if we use the following html within the content of the "description" tag:

<img src="[location of image]" alt="[alternate text]" title="[title of image]" />.

This code will place the image within the content of our article and solve our biggest headache (at least for me it was).