Archive for the ‘Frameworks’ Category

How to write custom action manager for ASP.NET MVC or explenation of how things works there

1. ActionResult it’s acctually the return of standart ASP.NET MVC controller. ActionResult is used to return presentation (view, html, other kinds of presentation) of result returned by action method and write it to ControllerContext response.

    Existing implementations of AcctionResult :

        a) ContentResult : writes to output returned value (converted to string using the toString method of the value).

        b) EmptyResult : writes nothind to output.

        c) HttpUnauthorizedResult : set’s the response code to unauthorized. Writes nothing to output.

        d) JsonResult : serialize returned result to JSON and writes serialized object to Response stream.

        e) RedirectResult : basically redirects a user to another page.

        f) RedirectToRouteResult : redirects to anothere page using routing engine. Example :

            public ActionResult Create(int? categoryId)

            {

                return

                    new RedirectToRouteResult(

                        new RouteValueDictionary(new {controller = “Home”, action = “List”, categoryId = new int?()}));

            }

        g) ViewResultBase : Base class for a result which renders a view. Contains the method FindView which should be overided return ViewEngineResult (?what is ViewEngineResult? explein a bit). There are two existing         specifications :

            I) PartialViewResult : is used to return PartialView

            II) ViewResult : used to return View

            Both of implementation are using strange behaviour. They are calling a method from ViewResultBase class, which is implementation of IViewEngine as well.

    Cool stuff isn’t it?

    Create your own ActionResult – nice example : http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

2. ActionResult can cont

 

3. ControllerBase class is basically to be used if you whant you controllers to support following tasks

    ? how ControllerBase is creating? How the ControllerContext is getting there? Because it’s really interesting to have it in your controller method execution process (is it?)

        public ControllerContext ControllerContext { get; set; }

public TempDataDictionary TempData { get; set; }

public IValueProvider ValueProvider { get; set; }

public ViewDataDictionary ViewData { get; set; }

 

4. Possible implementations of MVC Engine :

    a) Create new ActionResult (ExtActionResult) which will contains exact information about html page to be used, and Mode (possible modes are: List, Single). This one is to be used with Wicket-like style of developing a wicket-style framework.

    b) Result of method execution can be not just a HTML page, but also – it can be preconfigured ExtJS control with a data returned from a method. ? Should be this case specified by some annotatation on method or special attribute in HTML template?

 

NOTES :

        Section 4:

                    1) Search for a View algorithm :

                        a) Look for a HTML page which corresponds to exact Method which is called from controller

                        b) Look for a HTML page which represents the type which is returned by method. (Can contains 2 presentations : Single and List) If List<?> is returned and List html-template doesnt exists engine should use Single-item template for every returned item.

Advertisements

CheckboxSelectionModel in ExtJS grid

I’ve tried to use CheckboxSelectionModel on grid, and there are no examples in documents for. It’s not clear in documentation. Ok, so you should create CheckboxSelectionModel object before it’s passing to grid as selModel, because you should specify it in columns config property. So there is example by the steps.

  1. Create CheckboxSelectionModel:
var sm = new Ext.grid.CheckboxSelectionModel();
  1. Include created object in columns list:
columns:[

sm,


{….. rest of your columns …..}

]

  1. Provide selectionModel object as current selection model for grid. You should provide selModel property in config options:
selMode: sm

Result:


StackTrace in .net difference for Debug and Release compilation modes

Today I’ve tried to build new version of our DataLayer – Diego. Unsuccessfully L But I have discovered some interesting stuff around StackFrames in .net I’ve build sample project. In debug mode .net gives access to full stack trace. And in release mode we have just information about method that makes call and called method. There is test project to check it :

using System;

using System.Collections.Generic;

using System.Text;

using System.Diagnostics;

using System.Reflection;

namespace Tester

{


class Program

{


static void Main(string[] args)

{
Child r = new
Child();

r.runit(“hello”, 4);

}

}


class
Base

{


public
void Execute()

{


StackTrace trace = new
StackTrace();


StackFrame[] frames = trace.GetFrames();


Console.WriteLine(“Frames count : {0}”, trace.FrameCount);


foreach (StackFrame frame in frames)

{

processFrame(frame);

}

}


private
void processFrame(StackFrame frame)

{


MethodBase method = frame.GetMethod();


ParameterInfo[] parameters = method.GetParameters();


Console.WriteLine();


Console.WriteLine(“\tMethod name:\t{0}”, method.Name);


foreach (ParameterInfo param in parameters)

{


Console.WriteLine(“\tParameter name : \t{0}”, param.Name);

}

}

}


class
Child : Base

{


public
void runit(string name, int count)

{

Execute();

}

}

}

And there we have result for Debug mode:

Frames count : 3

Method name: Execute

Method name: runit

Parameter name : name

Parameter name : count

Method name: Main

Parameter name : args

Results for Release mode:

Frames count : 2

Method name: Execute

Method name: Main

Parameter name : args

Try to parse XML (similar to Integer.TryParse).

I’ve facing following problem during my current project. We have a lot of automation here. We have plug-ins architecture inside. Plug-ins are simple classes which inherits our special interface off-course. But main issue for plug-in is to persist his status. It’s possible with properties. So plug-ins are classes with properties which are processed automatically. Under processing I’m talking about setting/getting values and storing in our system. But plug-in can contains not just properties with simple types but complex types as well. Here complex type is some class which can easily be serialized/deserialized to/from XML. So we should be able to store complex types in properties. BTW: all values are storing as strings in our system. If can’t then I’m trying to convert value to a type of property. During conversation I’m checking if the passed value can be deserialized to complex type if yes – then it’s deserialized and value successfully set. If not I’m looking for a converter if no converter found I’m trying to set value directly.

    So my actual problem is that I can’t check that string can be parsed by XML processor. For example if we have in the string special symbols it can’t be processed. So I need to do try … catch to handle errors during deserialization. So I’m wondering why haven’t Microsoft add TryParse method to XML processor.

ExtJS – changing title for form fields dynamically – failed :( or “How can I prepare build from official ExtJS sorces

Couple of days ago I’ve tried to change title for form field for the form dynamically. And have faced problems. It looks like label element doesn’t contain ID-property. I’ve found standard template for all form-fields in ExtJS forms. So standart template is looking like:


<div class=”x-form-item {5}”>  <label for=”{0}” style=”{2}“>{1}{4}</label>
  <div class=”x-form-element” id=”x-form-el-{0}”
       style=”{3}“>
  </div>
</div>
<div class=”x-form-clear-left”>
</div>

But it’s easy to fix this issue. For example – you can travel via DOM to the label element and change innerHTML property of the element. But for was more interesting to understand how can I do build from the sources of ExtJS. And I’ve found that there is very interesting standard for build systems for such projects which is used (I guess so) by the ExtJS developers. So the name of the build – system is JSBuilder and it can be found here –http://code.google.com/p/js-builder/ It’s built using .net. It’s easy to use this system – you should open description file for the project (*.jsb). You can find build file for the ExtJS by the path: %ExtDirectory%/source/ext.jsb. After file was opened you should select modules you want to build and specify output directories.

Let’s back to our issue with label. For me I’ve changed standard template in %ExtDirectory%/source/widgets/form/Layout.js in function OnRender
in Ext.form.Layout class. So new template for me now looks like :


<div class=”x-form-item {5}”>
  <label id=”x-form-label-{0}” for=”{0}” style=”{2}“>
   {1}{4}</label>
  <div class=”x-form-element” id=”x-form-el-{0}” style=”{3}“>
  </div>
</div>
<div class=”x-form-clear-left”>
</div>

Here you can notice that I’ve add id property for the label. So now I can change innerHTML property of the label when it’s needed. Parameter #0 from the stack is ID for the rendered object. So after updates in source code I can easily update fieldLabel text:

Ext.get(‘x-form-label-‘ + currentField.id).innerHTML = “new title”;

Good luck 😉

Let me introduce Hublo … Part 1. Diego.

Hublo is modern framework for developing multi tier extensible web-oriented (2.0) applications. (part 1).

In most cases multi tier application needs to have database. And everybody knows that good database design is a 25% of application. But have you think before about the information duplication which we have in code. Hublo should decrease duplication of a code.

Let me introduce our data layer – Diego. Many thanks to the Roman Pavlyuk for the idea of using refactoring as the data layer base instead of generated typed datasets. Some few words about my point on how data layer should look.

There was a lot of discussions about pros and cons on storing SQL queries on database server in stored procedures. My point is to store every SQL query on database. There are many causes : SQL queries should be easy accessed by the database administrator (who probably will need to improve performance of an application) ; SQL queries should be edited easily without compilation. And main point (as for me) is that a lot of work is about data checking/reading/moving/updating and data is stored on the database, so isn’t it better to have one call to one stored procedure to have everything done faster and easier. I saw peoples who retrieving the data from the database, and then iterate that data inside a loop and so on. Isn’t it faster to have one SQL query with a join.

Ok, now let’s go ahead with Diego. So, let’s imagine that we have a lot of methods wrapped in stored procedures. Now we need to call that procedures and handle response. About the response : in most cases in response we will have some entities of the system. Let’s imagine that we have procedure spPortalUpdate with all necessary parameters to update the our entity “Portal” and return of the procedure is updated portal instance. So, how is it looking now? On c# you will write some code like this :

SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = “spPortalUpdate”;
command.Parameters.AddWithValue(“@ID”, ID);
command.Parameters.AddWithValue(“@PublicURL”, PublicURL);
command.Parameters.AddWithValue(“@Name”, Name);
command.Parameters.AddWithValue(“@Description”, Description);
command.Parameters.AddWithValue(“@UserName”, UserName);
SqlDataReader reader = command.ExecuteReader();
Portal portal = Factory.CreatePortal(reader);

It’s looks as classic way for me. And our idea is to have stored procedures described as classes. So we have following description :

class spPortalUpdate : FacadeRequest
{
public Parameter<Portal> portal;
public Row<Portal> ReturnedPortal = null;
}

As you can understand from the code – type of field named Parameter contains parametes description for stored procedure. And Row type is used to hold returns of the procedure. Let’s discuss format of procedure. When system is dealing with Diego procedures should have specialized output format. When procedure should return a result it should return name of field for Diego class and return actual data in the next row. So first row here is called “HEADER” and secodn “DATA”. In spPortalUpdate we have following section for header and data :

select ‘ReturnedPortal’

select * from vwPortal where ID = @ID

As you can see header is “ReturnedPortal”. So system will look for a field named “Portal” in the class and then will try to deserialize date to specified data type (Portal here).

Parameter can hold complex types and simple types. If we are passing complex type – it will parse passed type and every property of the type will be passed as parameter. Of course it’s possible to handle parameters passing, I will discuss that feature in the next article. And if simple type (integer, string and so on) passed – system will pass to stored procedure parameter directly with a name of field.