Pages

Search

Thursday, January 10, 2013

Render Partial and Render Action



This sounds slight hard to understand in the begin to differentiate the actual usage.
However, we are sure that the request goes to the controller – action, which in turn returns a action result (Could be View Result, Partial Result, etc…)
Picking up the “RenderAction” method, it is responsible for invoking a controller – action, passing the route value dictionary if required.
Finally the controller, will return a view processing the request and passing the required model object to the view.


In case of “RenderPartial”, it invokes a partial view which may or may not accept a model object.
So in case of “RenderPartial”, it is actually passing an object but representing its view via partial view.

Where as in case of “RenderAction”, might be required to pass route dictionary values but the actual called controller is responsible for invoking the right view passing the model object.
At last, the view is rendered but matters if it done using controller (render action) or using partial view (render partial) passing model object.

Below is a sample code example, demonstrating the use of render partial view and render action.
Sample :
Application is to display list of projects and users.
User details screen shall display user details and also the list of projects and project info to which the user is attached.
Project details screen shall display project info.

Since displaying the project info is common in project and user details screen, project info can be rendered as a user control.
Again Displaying project info control would expect a project name to render, hence there should be a action which accepts project name and returns a project info object to the view.
Beside this, might be I would like to display user name in a different manner like (Mr. User), etc.. for which I would go for partial view which expects the name and it would represent as Mr. [Name].
In this case it is not required to go for action but can invoke the view directly passing the name.

Controller Code :
  public ActionResult Projects()
        {

            if (ProjectsList == null)
                ProjectsList = ProjectUserRepository.GetProjects();
            return View(ProjectsList);
        }

        public ActionResult Users()
        {
            return View(ProjectUserRepository.GetUsers());
        }

        public ActionResult Project(string ProjectName)
        {
            return PartialView(ProjectsList.SingleOrDefault(p => p.ProjectName.Equals(ProjectName)));
        }

        public ActionResult User(string UserName)
        {
            UserModel user = ProjectUserRepository.GetUsers().SingleOrDefault(u => u.UserName.Equals(UserName));
            user.Projects = ProjectsList.Where(p => p.Users.Count(u => u.UserName.Equals(UserName)) > 0).ToList();
            return View(user);
        }


User Info :
@model SampleSite.Models.UserModel

@{
    ViewBag.Title = "User";
}

<h2>User</h2>

<fieldset>
    <legend>UserModel</legend>
    @{
        Html.RenderPartial("_UserInfo", Model);
    }
    <div class="display-label">
        @Html.DisplayNameFor(model => model.UserName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.UserName)
    </div>

    <div class="display-label">
        @Html.DisplayNameFor(model => model.FirstName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FirstName)
    </div>

    <div class="display-label">
        @Html.DisplayNameFor(model => model.LastName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.LastName)
    </div>
    @foreach (var prj in Model.Projects)
    {
        Html.RenderAction("Project", new { ProjectName = prj.ProjectName });
    }
</fieldset>
<p>
    @Html.ActionLink("Back to List", "Users")
</p>

Project Info :
@model SampleSite.Models.ProjectModel

@{
    ViewBag.Title = "Project";
}

<h2>Project</h2>

<fieldset>
    <legend>ProjectModel</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.ProjectName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.ProjectName)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Back to List", "Projects")
</p>

User Info Partial View :
@model SampleSite.Models.UserModel
   <div class="display-field">
        Mr. @Html.DisplayFor(model => model.UserName)
    </div>








Wednesday, January 2, 2013

Parallelism, Concurrency & Asynchrony


Concurrency is multi-tasking, sharing the CPU cycles. This is CPU bound, which means if there is more than a single task which are running concurrently a time slicing happens with the CPU time cycles to execute each of those tasks. Concurrency is achieved by creating threads which are assigned to thread pool.
Parallelism is the way if utilizing the multi core feature. If the core processors are more than one (dual core, or quard core, etc..), then the tasks can be assigned to different core processors. Here time slicing is not in picture, since each processor works on its respective task assigned.

Asynchrony is subset of Concurrency, which means Concurrency is a type of Asynchrony. As said Concurrency is achieved, creating threads for each task whereas Asynchrony will not lead to creation of new threads. Asynchrony works on the same thread, but will not block the thread for the asynchronous operations. To achieve this with in the same thread, callbacks are performed to the main thread when the asynchronous operation is completed.
Asynchrony concept is brought in .NET 4.5 CTP, using Async – Await (Asynchrony Pattern).

Tuesday, January 1, 2013

Data Flow – TPL


There are components named as “Data Flow Components” in .NET 4.5 which enables the capability of in process message passing for coarse grained and pipelining tasks.
Data Flow components are used to build the channel or pipes, through which messages are passed to process further.
Below are few default data flow components introduced and a sample code follows.
1)      Action Block
2)      Buffer Block
3)      Transform Block
4)      TransformManyBlock
5)      BatchBlock
6)      JoinBlock
7)      BatchedJoinBlock
8)      WriteOnceBlock
9)      BroadCast Block

//action block
                var actionBlock = new ActionBlock<int>((a) =>
                    {
                        Console.WriteLine("Message recieved : {0}", a);
                    });
                IObserver<Int32> observer = actionBlock.AsObserver();
                observer.OnNext(10000);
                Task<bool> wait = actionBlock.SendAsync(100);
                actionBlock.Post(10);


                //buffer block
                var bufferBlock = new BufferBlock<int>();
                IObservable<int> bObservable = bufferBlock.AsObservable<int>();
                IObserver<int> bObserver = bufferBlock.AsObserver<int>();

                //linking currnet buffer to an another buffer block
                var bufferBlock2 = new BufferBlock<int>();
                bufferBlock.LinkTo(bufferBlock2, new DataflowLinkOptions() { Append = true });
                bObservable.Subscribe(bObserver);
                bObserver.OnNext(20);
                bufferBlock.Post<int>(200);
                int a1 = 0;
                bool b1 = bufferBlock.TryReceive(out a1);
                bool b2 = bufferBlock.TryReceive(out a1);

                bool b11 = bufferBlock2.TryReceive(out a1);
                bool b21 = bufferBlock2.TryReceive(out a1);


                //broad cast block
                var broadCast = new BroadcastBlock<int>((a) => a + 10);
                //linking current broadcast block to a buffer block
                broadCast.LinkTo(bufferBlock2);
                broadCast.Post(10);
                broadCast.Post(20);
                Int32 bd1 = broadCast.Receive<int>();
                broadCast.Post(30);
                broadCast.Post(40);
                bd1 = broadCast.Receive<int>();

                //write once block
                var writeOnceBlock = new WriteOnceBlock<int>((a) => a + 100);
                writeOnceBlock.Post(400);
                Int32 wr1 = writeOnceBlock.Receive();
                writeOnceBlock.Post(200);
                wr1 = writeOnceBlock.Receive();
                writeOnceBlock.Post(500);
                wr1 = writeOnceBlock.Receive();

                //transform block
                var transformBlock = new TransformBlock<float, float>((a) => a);
                transformBlock.Post(180f);
                float f1 = transformBlock.Receive();
                transformBlock.Post(280f);
                float f2 = transformBlock.Receive();

                //transform many block
                var transformmanyBlock = new TransformManyBlock<int, int>(a => Enumerable.Range(0, a).ToList());
                transformmanyBlock.Post(100);
                Int32 b3 = 0;
                while (transformmanyBlock.TryReceive(out b3))
                {
                    Console.WriteLine(b3);
                }

                //batch block
                var batchBlock = new BatchBlock<int>(1000);
                Enumerable.Repeat<int>(5, 100)
                    .ToList()
                    .ForEach(i => batchBlock.Post(i));
                batchBlock.Post(1);
                Task<int[]> batchData = batchBlock.ReceiveAsync();

                //join block
                var joinBlock = new JoinBlock<int, int, int>();
                joinBlock.Target1.Post(1);
                joinBlock.Target2.Post(2);
                joinBlock.Target3.Post(3);
                joinBlock.Target1.Post(4);
                joinBlock.Target2.Post(5);
                joinBlock.Target3.Post(6);
                Tuple<int, int, int> tup1 = joinBlock.Receive();

                //batched join block
                var bacthedJoinBlock = new BatchedJoinBlock<int, int, int>(2);
                bacthedJoinBlock.Target1.Post(1);
                bacthedJoinBlock.Target2.Post(2);
                bacthedJoinBlock.Target3.Post(3);
                bacthedJoinBlock.Target1.Post(4);
                bacthedJoinBlock.Target2.Post(5);
                bacthedJoinBlock.Target3.Post(6);
                Tuple<IList<Int32>, IList<Int32>, IList<Int32>> tup2 = bacthedJoinBlock.Receive();
Beside the provided default data flow blocks, custom data blocks can also be implemented.

Monday, December 31, 2012

Async – Await



A new asynchronous programming model introduced in C# 5.0. The programming style using (Async Await) would be as similar as like synchronous programming with slight code changes.
There are other asynchronous programming methods before such as like
1)      APM (Asynchronous Programming Model) – Begin Invoke, End Invoke…
2)      EAP (Event Asynchronous Pattern) – Event is raised after the completion of Asynchronous function.
3)      TAP (Task Asynchronous Pattern) – Using Task library that helps to build a wrapper (task) on the actual function. The status of the task can be fetched from the task object.

The next model is using Async – Await introduced in C# 5.0.
Below is a sample code, with traditional synchronous and latest asynchronous methods,
Synchronous
Function which would take some time (5 seconds) and returns a number.
  private Int32 GetNumber()
        {
            Thread.Sleep(5000);
            return 10;
        }
Asynchronous using Async Await.


        private async Task<Int32> GetNumber()
        {
            //statements are executed in synchronous manner, as long as there is
            //no await statement
            int a = 10;

            //when there is an await statment, which means compiler will understand that
            //it has to wait for the result, but since the method is marked as async hence it returns the
            //control to the calling method without blocking
            return await Task.Run(() =>
                 {
                     Thread.Sleep(5000);
                     return 10;
                 });

            //when the above task is completed, it would run  the next statements again in synchronous manner as long
            //as there is no await statement.
            a = 20;
        }

Caller :
  private async void button1_Click(object sender, EventArgs e)
        {
            Int32 result = await GetNumber();
 }

The similar async – await can be used for the delegate methods which are invoked by the task library.
Below is an example, declaring async delegate methods in a task.

Task<Int32> result1 =  Task.Run(async () =>
                    {
                        await Task.Delay(5000);
                        return 10;
             });

Note :
1)      To enable async- await – asynchronous behavior, the method should be declared as async.
2)      Method declared as async, may or may not have a await statement.
3)      If there is no await statement in a sync method, compiler executes like a synchronous method.
4)      To have a await statement, method should be declared as async .
5)      A async method always returns Task or Task<T> or can be void.

Why should a async method return type always have to be Task or Task<T> or void.

When a async method is invoked, compiler would expect that there could be a piece of code which needs to be asynchronous.
Hence when there is a await statement which might be in the middle of the code block with in the method, compiler will execute from there as a separate till the end of the code block.

Creating a task for this is because, since it has to run asynchronously it will goto the caller when an await statement is identified.
So to monitor the code execution from await statement, the return task handle would help to do.
If it is not required to bother about the further execution which would happen hence not required to handle return type and hence can be void.

Monday, December 17, 2012

4G Network Specifications

4G Network is although still under development, the basis for the upgrade from 3G to 4G service began in the 21 century, companies began to introduce new technologies. New standards such as WiMax and Long Term Evolution (LTE) was listed as 4G, but there is some debate about its status.
4G Specifications

Network for 4G are oriented to the high quality of service and speed of data transfer. The priorities of this standard has better reception with less data discarded, and faster exchange of information. The International Telecommunication Union (ITU), the body that oversees the standards for wireless networks, has stated that major improvements multimedia messaging services, including video services, requires the approval of a new generation.

4G required speed data transmission rates of at least 100 megabits per second, while a user is moving at high speed, such as in a train and one gigabit per second data in a fixed position. ITU also requires rapid transfer between networks without interruption or loss of signal. The phone also has a 4G network using the Internet Protocol (IP) for the transmission of data in transit, rather than a traditional phone.
Trend towards 4G

Several working groups have been established to contribute to the development of 4G networks. The initial development of this technology include WiMax, which is a faster version of data transfer in Wi-Fi ® networks. LTE is a new technology that improves over 3G, but it is not fully compatible with the requirements of the ITU standard for data transmission.

Both were branded as 4G networks, but led to some confusion and disagreement. Since both methods use IP packets, and showed significant improvement compared with the 3G standard, ITU 4G approved labeling. This is related to WiMax and LTE developers to advance to meet official standards for 4G, which has continued to do so.
Update 3G to 4G

The implementation of the 3G network in the world took almost a decade. The ITU expects 4G network was launched in the world market in a more efficient and timely. Improvements between 2G and 3G substantial improvements necessary hardware for mobile devices, while many companies have developed smart phones used for 3G networks to be compatible with the new 4G standard. However, concerns about the stability and security somewhat reduced development ", as service providers to ensure that they want to protect customer information.
4G network before the first

The first wireless networks, called 1G, was founded in 1980. 2G was introduced in the 1990s to allow multiple transmissions to occur communication. The basis of 3G technology was introduced in late 1990 and has been implemented in most of the world in the 21st century. Although the 3G network was the first to give multimedia applications, 4G promises to bring this technology base and expand significantly.