Thursday, 19 September 2013

Attach view to button , Extjs

To attach a view ( must be a floating component like window ) to a button , so that on clicking a button results a view to open attached to that button , you can use the following code inside your button click action inside your controller. i.e.

var menu= Ext.create('Main.view.MyView', {
            left: 0,
            padding: 10,
        }).showBy(button);


Apply tool tip to grid cells , Extjs

To apply tool tip to grid cells first create renderer and set metadata.tdAttr to 'data-qtip='"your value "; i.e. as given below :


 renderer: function (value,metadata, record, rowIndex) 

{
              
metadata.tdAttr = 'data-qtip="' + value + '"';

             return value;
}


and that's it :)

Saturday, 14 September 2013

jQuery , printer access ( print area inside a #div )

In order to open the printing dialog into the same page you must follow the following steps:


  • Must include jquery script inside header
  • Create Iframe inside your html body , like this :                                                                                 <iframe id="iframe" width="0" height="0"></iframe>
  • User following lines on click event of any element ( lets say button ): $('iframe').contents().find('body').html($(this).html());                                         window.frames['iframe'].print();


And that's just all.

Friday, 13 September 2013

Remove Application From IIS ( also from application pool , otherwise reconfiguration cause errors)

You must remove application from two places :
One is from tree coming at right side of IIS main window , that's easy one , just right click and remove
Second one is to remove from application pool , for that purpose go to "C:\windows\system32\inetsrv\config" and edit "applicationHost.config" , find your application in it which must be in xml nodes format some thing like this :

<application ...> </application> 

Remove that node containing your application and refresh IIS.
And that's just all what you need:)

Saturday, 7 September 2013

Mocking

Creating objects that simulate the behavior of real objects. For example, " stubbing a database by implementing a simple in memory structure for storing records.

Unit Testing

Characteristics of Unit Test :
  • Fully automated
  • Can be run in any order ( if part of any other test)
  • Runs in memory ( no db access or file , must implement mocking )
  • Consistently returns the same results
  • Runs fast
  • Readable
  • Maintainable
  • Trustworthy

Amazon S3

Storage tor the internet, provides interface for store and retrieve any amount of data any time form anywhere on the web.

Repository Pattern and Unit of work

 Repository Pattern:
Isolate our application from changes in the data store.
Help in automated testing and test driven development ( mocking i.e. in memory colleciton)

Unit of Work:
Maintains the list of objects effected by a business transaction and co-ordinates the writing out of changes and resolve concurrency problems.

Rest Api

REST stands for " Representational State Transfer" , stateless, client-server , cache-able communications protocol ( http protocol is used).

Sencha Touch , Phonegap, cordova and XCode

 Sencha Touch:

High performace HTML5 mobile application framework
Only framework that enables developers to build apps that work on IOS, Android, Blackberry, Windows phone etc.
Sencha CMD: full set of life cycle management features.

Why:
  • Built for speed
  • Built for great experience
  • Built for success
PhoneGap + Apache Cordova :
  • Phonegap is free distribution of apache cordova
  • Phonegap is open source and free software.
  • Framework that allows you to create mobile apps using standardized apis for platform you care about.
XCode:
An IDE, containing suite for software development tools developed by apple for developking software for OSX and IOS ( Mac, iphone, iPad )

JNI ( Java Native Interface ):
Integrating java program to lagacy c/c++ code and embed JVM with your native application.



Scaffolding ( Asp.net mvc )

Quickly generating a basic outline of the software that can be edit and customize easily. Just select the template, modl and DBContext(source) and all actions, views will be generated.

What is Behavior Driven development ( BDD) .net implementation



Behavior Driven Development ( BDD ) :

 It combines requirements and testing into one integrated approach, resulting in improvement understanding by both business and technical team.
“A shipment cannot be created without specifying the recipient address” , BDD is specialized version of test driven development (TDD).
It must :
  • ·         Define a test set for the unit first
  • ·         Implement the unit
  • ·         Finally verify that the implementation of the unit makes the test succeed

To implement BDD we must know about :

  • SpecFlow : BDD library/framework , works on Given, When and Then keywords where Given relates to preconditions, when represents occurrence of an event and Then is testable outcome. Provides facility to write testing scenarios in human language ( DSL , domain specific language ).
  • Coypu:  Provides fast browsing of web applications to access elements i.e. buttons, links , fields and etc on a web page.
  • Resharper : To run unit tests.

Caching ( Asp.net MVC )

Caching in Asp.net MVC applications provides facility to cache the output of controllers and improve your application performance to many times.The output cache enables you to cache the content returned by a controller action.
There are you ways to use output cache in your asp.net mvc applications :
  1. Declare on the top of the action ( or controller which will be applied on all actions inside it )
  2. Create Cache Profile ( define caching section inside web.config of your application)

Declare on top of controller or action:
 You can specify cache for an action or controller by writing this line on the top of it , like this ,

OutputCache(Duration=30, varyByParam="none" , Locaiton=OutputCacheLocationClient, NoStore=true)]


You can set the Location property to any one of the following values:
· Any
· Client
· Downstream
· Server
· None
· ServerAndClient

Creating Cache Profile:

Define profile inside of system.web section of your web.config like this :


<caching>
<outputCacheSettings>
    <outputCacheProfiles>
        <add name="myCache" duration="3600" varyByParam="none"/>
    </outputCacheProfiles>
</outputCacheSettings>
</caching>
 
And you can then use this profile like that :
 
        [OutputCache(CacheProfile="myCache")]
        public string Index()
        {
            return DateTime.Now.ToString("T");
        }
 
In both of above cases "varyByParam" is a very important parameter , this actually enables us to create different cache versions of the same view ( request ) , for example on the basis of user id we are differentiating out views , so in that case we can set varyByParam to id so that different versions of cache are available for different users accordingly , very dynamic and easy solution.
For further reading you can go to : "http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs".

Memcached , 3rd party distributed cache management system

Memcached is basically key-value pair storage , provides cache facility from out side of your application. You just need to store your string , object etc by assigning it a unique value and whenever you want your value just call it from its unique key , best solution for multi-tire large applications dealing with thousands of records every single call , my using 3rd party cache like Memcached we can reduce database calls and store intermediate results into out separate cache management system.To use memcached you need to download memcached dot net library for your application to include and memcached manager to provide storage services for your application to use.

Persistence ( in reference to databases usage in programming )

 When we go through with persistence we have these most important topics to know about.

  •  MySql
  • SqlServer
  • MySql Work bench 
  • Query optimization
  • No sql
 MY SQL WORKBENCH

Mysql workbench has three very important portions
  1. SQL Development
  2. Data Modeling : Complete visual design and modeling
  3. Database Administration : GUI to start stop server, User accounts, Manage configuration files
Query Optemization

  • Why 
          - Large databases
          - Complex queries to reterieve data
          - More chances of table lock and data corruption
  •  How
          - Understanding of how database is executing our queries i.e.EXPLAIN keyword
            is used to see the query plan ( in Mysql).
          - Retrieve as little data as possible  ( do not use select * )
          - Store intermediate results i.e.User index, server tuning, an aggregate table,
            vertical partitioning ( partition the table by column decreases the amount of data
            to be process ),Horizontal partitioning ( partition the table by data value),
            De-normalization ( avoid joins).





NO SQL :
  • Non relational databases
  • Designed for distributed data stores to store large scale of data ( google, facebook )
  • No fixed schema, scale horizontally
  • Properties
            Stands for not only SQL
            No declarative query language
            No predefined schema
            Key value pair storage,column store,document store,graph store
            Unstructured and unpredictable data
            High performance , high availability and scalability

  • CAP Theory
          1)  'C' for  Consistency : After each operation all users must see the same data.
          2) 'A' for Availability : No down time.
          3) 'P' for  Partition tolerance : System must continues to function even
           communication among the servers is unreliable.
         4) not possible to provide all 3 at same time, all available databases of the time are
            providing   the 2 of 3 above described i.e.
             I- CA
            II- CP
           III- AP

  •  Data storage formats
         - Key-value pairs ( Cassandra )
         - Document ( MongoDB)
         - XML format ( BaseX)
         - Graph format ( Neo4j)
 
  • Disadvantages
         - No standards
         - Limited query capabilities

Sunday, 1 September 2013

Asp.net MVC4 database migrations with Entity Framework

Hi all , in this post I am going to talk about database migrations and how you can use it in your project and why should you use that feature. In Asp.net MVC Code first approach we use to create our model ( entities and their associations ) first and define our context class which contains the list of these entities implementing DBContext class. So when we change our code for any entity add or update case and run the application then an error screen comes which says your model is been updated , which means that to get rid of this error we must have to delete our old database and run our application again which will create new database for us with updated tables and what if we have thousands of records and we have any change in our model then ?
In order to escape from this database deletion and creation process again and again we use database migrations.
Yes this is the way a developer can update its models without effecting the database data , actually migration works on context , it just picks all changes and create migration file and update changes on single command. To take advantage of migrations you just need to know about 3 commands :

1)  First step is open your project in Visual studio , go to Tools->Library Package Manager->Package Manager Console and click it , this will open a console with "PM> " as initials. Now first select the project which contains the context class as default project in this console. Then install or update EntityFramework package into your project with these commands :

  1. PM>Install-Package EntityFramework Or
  2. PM>Update-Package EntityFramework
After that enable migrations in your selected project with this command :
  • PM>Enable-Migrations
2) Now your setup is ready for starting the migrations, Enabling migrations will create Migrations folder into your project with Configuration.cs class and all future migrations will be automatically added into this folder.
Now update your models and run add migration command :
  • PM> Add-Migration "any name"
This command will create .cs file into migrations folder automatically, in which you can see your changes.

3) Last and final step is updating database with following command :
  • PM> Update-Database
That is how you can get benefit from database migrations in just 3 commands , this is very basic stuff you can have for you migrations , further advance skills will come from experience.Thanks


Saturday, 31 August 2013

Free Rich Text Editor for Asp.net MVC apps, simple 2 steps to use

Today I just make a search for free text editors for asp.net mvc applications and I find TinyMCE there ( http://www.tinymce.com ) , very useful , effective and powerful , I am just using its jquery package to maintain all editing on client side which actually maintained by itself , we just have its final raw html for storage to database and show as @Html.Raw(Content from database), its very simple two steps process :

1) Just run this command in visual studio package manager console

     Install-Package TinyMCE.MVC.JQuery
This will install all necessary files and plugins your application needed and will create a view in shared folder which will be used as an editor ( partial view ) where you will call this editor functionality.

2) Second thing is write following Annotation on the top of model property to which you want to open in editor while creating or editing , e.g lets say you have Blog model which have title and body properties  and it is obious you will want to open Body in editor while creating or updating entity, so use this annotation on the top of that property like this  :

 [UIHint("tinymce_jquery_full"), AllowHtml]
        public string Body { get; set; }



And that's all, you are ready to go and use your rich editor to write your text with style.


For more detailed tutorial go to : http://www.tugberkugurlu.com/archive/tinymce-html-text-editior-and-asp-net-mvc-setting-it-up-has-become-easy-with-nuget.

Just make sure one thing that your _layout.cshtml has included jquery library as this tool is built in javascript and run on the top of it. So Enjoy :)

Sunday, 18 August 2013

Insert custom object to Forms Authentication cookie to Identify user at each request

Forms authentication is a way that we use to login in our systems in asp.net mvc , it creates cookie on user side and user remains logged in until cookie expires , normally we use :


Where " User.Identity.IsAuthenticated " checks whether is there any user exists who is currently logged in the system and "User.Identity.Name" gives the user name ( usually email ) which we give in login form during login process , but what if we want some thing more that just an email address like , if someone wants to send his/her name,age,address or any other information or property to the server with each request from client side , because if we achieve that then we don't have to worry about what are the roles allowed to current user , what is his name , his id or anything , because in that case we don't have need to make database requests to get user information each time.
To achieve this we have "FormsAuthenticationTicket" object , we can provides your custom data in it , and we then add this object into our forms authentication cookie , and that's how custom information remains stick with each request. i.e.


where UserInfo is custom object containing user information, we add it as string , have to serialize this object to convert to object and vise versa.
We can use above described method while login process like this :

  FormsAuthenticationTicket ticket = UserAuthenticationTicketBuilder.CreateAuthenticationTicket(customer);

  SetTicket(HttpContext.Current, ticket);

Where customer is your object you wants to store in cookie , and setTicket( ) may be defined as :

 private void SetTicket(HttpContext httpContext, FormsAuthenticationTicket ticket)
        {
            var user = new User(ticket);
            if (!ticket.Expired)
            {
                string ticketval = this.Encrypt(ticket);
                string[] userRoles = user.RoleName;
                httpContext.User = new GenericPrincipal(user, userRoles);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketval) {        Expires= DateTime.Now.Add(FormsAuthentication.Timeout); };
                cookie.Domain = "";
                httpContext.Response.Cookies.Add(cookie);
                httpContext.Response.AddHeader(FormsAuthentication.FormsCookieName, ticketval);
            }
            else
            {
                httpContext.Response.Headers.Set(FormsAuthentication.FormsCookieName, null);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, null) { Expires = DateTime.Now.AddSeconds(-1) };
                httpContext.Response.Cookies.Add(cookie);
            }

        }


And User class which is accepting ticket must be implementing IIdentity and should get data out of ticket.

And finally implement this in your Global.ascx file :

 public override void Init()
        {
            this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
            base.Init();
        }

        void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            SetCookie();


        }

and in SetCookie() , create user object , add to request header cookie in the form of FormAuthentication cookie , the above Init() method will be called each and every time when request goes to the server and so your user object to.