Tuesday, July 15, 2014

Generating dynamic html using Angular.js

Carrying on from my last post angular can also be used to generate dynamic content as I learnt from one of the online tutorials I found.
To do that you need to use the following code:

<script type="text/javascript">
   
    function User(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

        this.getFullName = function() {
            return this.firstName + " " + this.lastName;
        };
    }

    function UserController($scope) {
        $scope.userList = [
            new User("Misbah", "ul Haq"),
            new User("Mohammad", "Irfan"),
            new User("Saeed", "Ajmal")
        ];
    }
</script>

This code will create a class called User with properties firstName and lastName and a function called getFullName. I have then created an angular controller that contains a list of User.
In the html code below I will use a foreach loop (or angular’s take on c#’s foreach) and generate dynamic html to show the data extracted from angular’s controller.

<div ng-app>
    <div ng-controller="UserController">
        <p><b>Players</b></p>
        <div ng-repeat="user in userList">
            <a>{{user.getFullName()}}</a>
        </div>
    </div>
</div>

The code is pretty self-explanatory although if you do have questions you can refer to my last post which will help you understand angular’s keywords better.

Basic Angular.js application

To create an Angular.js application you first need to add the relevant reference as shown below:

<script src="http://code.angularjs.org/1.0.5/angular.js"></script>

Following this you can add a basic angular controller as shown below (note $scope is an angular keyword):

<script type="text/javascript">

    function ControllerName($scope) {
        $scope.Name = 'England';
    }

</script>

In the html section of this page you can use the following code to display data from the angular controller:

<div ng-app>
    <div ng-controller="ControllerName">
        <input type=text ng-model="Name" />
        <br />
        <p>{{Name}}</p>
    </div>
</div>


The keywords used in the example above are explained as follows:

ng-app: Defines the scope of angular’s application. Any angular specific code outside this div will not be handled by angular
ng-controller: Defines the scope of the controller ControllerName. Within this div we can work with variables defined within ControllerName as if they are local variables
ng-model: Defines which variable will the text box bind with
{{Name}}: Displays the value of variable Name


On this page if we enter anything new in the text box, it will automatically change the value of variable Name which will automatically update the value of {{Name}} shown below.

Saturday, December 7, 2013

Migrate an MVC 3 site to Umbraco

To migrate an MVC 3 website to Umbraco we first need to download Umbraco CMS which can be downloaded here

Once downloaded you will have a file called: UmbracoCms.6.1.6.zip

All contents of this file need to be copied into your website folder (all except the folders “App_Code” and “Bin”)

After this you need to open the website in Visual Studio

In Visual Studio you need to drag and drop all these newly copied files into the Solution Explorer so they are linked to the main solution

Following this, you need to open Package Manager Console and type the following: Install-Package UmbracoCms.Core –Version 6.1.6 and press Enter which should start a package installation

Once this completes, open UmbracoSettings.config and update the default rendering engine to Mvc as shown below:

<defaultRenderingEngine>Mvc</defaultRenderingEngine>

Now you need to create an empty database for Umbraco

Once the database is created you need to build the solution and run it

This should take you to the umbraco configuration wizard

Once you go through all the steps of this wizard your new Umbraco backed website should be configured with the new database you just created (it will ask about that database during the wizard)

There is a small change required at this point to make the solution work. You need to inherit all your controllers from the SurfaceController class (Umbraco.Web.Mvc.SurfaceController) as shown below:

public class HomeController : SurfaceController

This should complete your migration.

In order to open the website you need to know how the controllers will be routed by umbraco. They are routed in the following way:

/umbraco/surface/{controllername}/{action}/{id}


A noteworthy migration problem

During this migration I came across a very tricky problem. If you get the following error when adding a new controller:



You just need to delete the following reference and the error will be gone:

Our.Umbraco.uGoLive.47x.dll

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).

Monday, October 17, 2011

CSS for beginners

If we want to style any control in an html page (by control I mean textboxes, labels and all other html elements that can be displayed in an html page), we can easily do it using the style property. For example if we have the following heading:

<h2> Heading </h2>

And we wish to change its colour to green and make it italic, we can easily do so using the style property as shown below:

<h2 style="color: green; font-style: italic;"> Heading </h2>

Similarly, we can use a range of properties to stylize any control we want. However, this is not a very good programming practise. If we want to stylise our controls in a way that makes our styles more re-useable, we need to do it in the following way:

On top of the page we need to write the following code to make a style class with any name we want (in this example I have used the name MyHeading).

<style>
        .MyHeading
        {
            color: Green;  
            font-style: italic;
        }
</style>

Then in our html we can write the following code:

<h2 class="MyHeading"> Heading </h2>

With this code we will be achieving exactly the same result as above with the added benefit of code re-use in other places such as:

<p class="Myheading">This is a paragraph</p>

In this approach, we are using a style class to style our page. This can be a good approach to style a page; however we can go one step further by using a cascading style sheet.

Cascading style sheets (or CSS) allow us to create a “.css” file containing many style classes. This css file can then be attached with any webpage giving it access to all its style classes.

 To attach a css file to an html page, we need to write the following line on top of the webpage (above its html code):

<link rel="Stylesheet" type="text/css" href="/Location/File.css" />

In the css file, we need to write the following code to create a style class:

.MyHeading
{
      color: Green;  
      font-style: italic;
}

After this, we can use any class from the css file to style the controls of our page. The benefit of using this approach is that css files allow us to use the same style sheet throughout our website, and ensure a consistent layout across all pages, thus allowing maximum code re-use.

Tuesday, October 11, 2011

Returning XML from MVC Controller Action

To return xml from a mvc controller action we can use the following code:

public XmlElement name_of_function()
{
      XmlDocument Feed = new XmlDocument();
      XmlWriter Write = Feed.CreateNavigator().AppendChild();

      Write.WriteStartDocument();
      Write.WriteStartElement("head");
      Write.WriteElementString("name_of_tag", "value");
      Write.WriteEndElement();
      Write.WriteEndDocument();

      Write.Flush();
      Write.Close()

      return Feed.DocumentElement;
}

Monday, September 5, 2011

Using ASP.NET Webform in an MVC controller

In ASP.NET MVC we use controller actions to call views using the following code:

public ActionResult NameOfView()
{
return View();
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View(ViewModel);
}

Through this code, the view "NameOfView", placed in the folder "Views", will be displayed (in the second instance the view model will be passed to it as an input parameter).
However if we want to work with an ASP.NET view which is NOT in the folder "Views" but is instead located at "Abc/Def/page.aspx", we can change our controller slightly to accommodate this view. To do this, we can use the following code:

public ActionResult NameOfView()
{
return View("~Abc/Def/page.aspx");
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View("~Abc/Def/page.aspx", ViewModel);
}

Adding jQuery to an MVC view

To add jQuery code in an MVC view, we need to write its code in the head section of the view. The example below shows simple jQuery code written in an MVC view.

<head>
<script type="text/javascript">
$(document).ready(function ()
{

// here we can write any javascript code that will be executed as soon as the page loads  

// If we have a dropdown in our page, named as "xyz", and need to write code that executes when it's value is changed to "1", we could do the following:

$('#xyz').change(function ()
{
if ($('#xyz').val() == "1")
{

// over here we can write code that will execute when the value "1" is selected in the dropdown "xyz"

}
else if ($('#xyz').val() == "2")
{


// over here we can write code that will execute when the value "2" is selected in the dropdown "xyz"                

}

});
});
</script>

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

</head>

Sunday, July 31, 2011

MVC Multiple Post buttons in one page

Anyone who has worked in MVC knows how clicking a post button will submit the page, and invoke the action method. It can get a bit annoying if you want to do different things based on different buttons being clicked. However, thanks to html there is a way around it.


To do this, we have to figure out which button was clicked. This can be done in the following way:

Make two buttons with the same “name” but different “value”
e.g

<input type="submit" id="GetResults" name="SubmitButton" value="Apply" />
<input type="submit" id="UpdateResults" name="SubmitButton" value="Inform" />

In the controller action, add the following input parameter (string SubmitButton)
Inside the controller action, the value of the variable “SubmitButton” will either be “Apply” or “Inform” depending upon which submit button was clicked.

After this, a simple “if” condition such as the one given below will do the job:

If(SubmitButton == "Apply")
{
                Do this
}
Else if (SubmitButton == "Inform")
{
                Do that
}