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.