Posts

Showing posts from 2012

Android : How to change progress bar color at runtime programmatically?

Image
I faced this problem while creating one of my android applications(in fact, it is my first application :) ). Lets consider we want to create an android application to calculate the commitments progress of a certain category for http://area51.stackexchange.com/ website (note we will display a progress bar with one color red or green for simplicity).

Each time we run this application it calculate the commitment percentage and display a red progress bar if it is less than 50% or green one if it equal or greater than 50%. For learning purpose we will insert the number of total required committed users and the number of committed users and calculate the progress of commitment process.

Now lets write our code. If it is your first android application you can refer to this post to know how to create an android application.


How to create the full layout of this simple application is beyond this post, we will concentrate on the progress bar. The following code snippet is the definition of a …

ASP.Net MVC : Conditional Validation using ValidationAttribute

In ASP.Net MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required, MaxLength, MinLength,...etc.

Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females.

Assume our registration form will contains three fields, name, sex and age, and its model will be as follows
public class RegisterationModel { [Required(ErrorMessage = "*")] public String Name { get; set; } [Required(ErrorMessage = "*")] [Display(Name = "Gender")] public Sex Sex { get; set; } [RequiredIf("Sex", Sex.Male, "enter your age")] public In…

Restrict non-ajax requests using ActionMethodSelectorAttribute

In ASP.Net MVC each coming request is routed to a certain action method inside some controller and with JQuery it became piece of cake to call this action method using ajax. In some scenarios we need to restrict the incoming requests to be ajax request only, fortunately ASP.Net MVC represent a new method to Request object called IsAjaxRequest() that return true if the current request come from ajax call and return false if current request is normal request(typing url in address bar of a browser, click a link to this page,..etc).

We can use that method to deny any request come from ajax call or vise versa.
public class HomeController { public ActionResult Index() { if(Request.IsAjaxRequest()) { //Do something } else { //Do something else } } } As we see if we need to make this check many times in our project, we will rewrite the same if statement for each action we need it be called via ajax only, but is there another way t…

How to create android application?

Image
We have already showed how to prepare your machine to develop your android application now it is the time to check if we prepared our machine successfully and we can write our first android application or not.

We will start learning developing android application by writing a simple application that will display "Hello World" sentence (the most famous example to start learning new tech). Follow the next steps to create your first android application:
Lunch Eclipse and select File > New > Project you will find a list of available projects templates select  android project template then click next, you will see window like this

Application Name : the name of your applications that will be appear on application list of your device(mobile or tablet)
Project Name : the name that will be appear in your eclipse work-space.
Packaeg Name : it will be used as identifier for your application and must be unique across all applications.
Build SDK : specify which sdk version you will…

Fundamental components of android application

This post is a one of some posts about android platform I will write to explore this platform and learn you(and me) developing android applications for mobiles and tablets devices. You don't have to own android mobile to create android application, what is you really need is a tool (Emulator) to test and debug your application.

You can refer to this post  where I showed how to prepare your machine to be able to create your android application. That post was written before releasing Ice Cream Sandwich version (android 4.x) but it does not matter, just you should download the latest version of all tools you have to install.

My reference for writing these posts is Pro Android 4 book.

In this post we will explore the key components of android framework which we must understand before delving into coding process.

View:
views are user interface(UI) elements such as buttons, labels, text fields, or any other UI element. Views also can contain other views. Anything you see is a view.

Acti…

Load partial page in jquery and ASP.Net MVC

In this post I will show you how much ASP.Net MVC and JQuery are making up a dangerous duet and how you can do big tasks in simple way with little efforts. We can take a look at a live example of what we will do in this post. In stackoverflow website specially users page and tags page you will find a text box to search users/tags. the page is loaded with some users info sorted with default setting. if you start to write something in that text box, the users collection will be filtered by the name you entered in ajax manner and ordered alphabetically(ascending).

The issue here is how using the same piece of code that produce the whole page when it be loaded in first time to filter the users when you type some letters in the text box and update just the part that display the users data. Here the magic of ASP.Net MVC and JQuery come to the scene.

Lets start to build our page first then start to filter our users collection. I will not show you how to create new ASP.Net MVC project this i…

Generic CheckBoxList in ASP.Net MVC

In ASP.Net web forms you can easily create a list of check boxes and bind it into a data collection using CheckBoxList control and specify which property will be the text of each check box and which one will be the value of the check box. You even don't need to write it, you can drag it from tools window, drop it into your page and set its properties and style with wizards that Visual studio provide.

But in ASP.Net MVC there is no any server controls like that exists in web forms, all what we have is a helper methods to create HTML tags. In ASP.Net MVC we have two helpers methods for creating a check box, Html.CheckBox and Html.CheckBoxFor that will be rendered as just one check box. If we want to create many check boxes or check boxes list we can call it inside a loop as follows
@foreach (var item in MyCollection) { @Html.CheckBox("checkBoxName", new {value=item.checkBoxValue })@item.CheckBoxText<br /> } Here is a generic extension method for create a check …

Generic Lambda Expression to sort collections of different types

Suppose you have many collections with different types that you want to sort, of course you can do it by OrderBy or OrderByDescending extension methods but you have to specify the order criteria every time you call these methods. If the order criteria is determined in runtime, then you have to build a separate function to each order criteria of each type. To clear what I want to tell you suppose you have two classes, Employee and Department.
public class Employee { public String Name { get; set; } public Int32 Age { get; set; } public DateTime HiringDate { get; set; } } public class Department { public String DepartmentName { get; set; } public String Code { get; set; } } And you want to order the employee collection by one of its properties (Name,Age,or HiringDate) and order department collection by one of its properties.

OrderBy and OrderByDescending methods need Func<TSource,TKey> as selector to compare the collection items and order them. So the issue he…

How to fire RowCommand event of nested GridView?

Image
In ASP.Net you can use a Repeater or GridView controls to simply display any data collection came from any data source(database,XML file,...etc). Sometimes each item of that collection has a property that is another collection and to display it you will use another Repeater or another GridView(nested Repeater or nested GridView).

To edit, delete or to execute a command on any GridView row you use OnRowCommand event to handle it, but what about the commands on the child(nested) GridView rows. In case of nested Repeater you can set the OnItemCommand event of the child Repeater. You can find many articles explain how to do that. The problem which my friend faced is handling the OnRowCommand event of nested GridView. We googled it but we didn't find a lot of article that explain how to handle it, so I write this post to help any one facing the same issue.

Assume we have a set of Inventories, each Inventory have a set of products. To display All inventories with all products of each…

Safe ASP.Net MVC application against cross site attacks - 2

Session Hijacking:
ASP.Net identifies users by session ID cookie which called ASP.Net_SessionId by default, and if we use Forms Authentication, then a second cookie is used called .ASPXAUTH. If an attacker can obtain these cookies, then they can include them in a request to our server and impersonate one of our users. The browser by default preventing the javascript from a site to access cookies of another site. But if the attacker has been able to inject a script into one of our pages, then the browser believes that the script is part of our application and grands access to the session cookies.

We can protect our site by keeping a record of each client IP address when a session starts, we can deny any requests that originate from a different IP. But you should avoid this technique when you deal with the public internet.

We can mark a cookie with the HttpOnly flag, and the browser will hide its existence from javascript but will continue to send it via all HTTP requests. By default AS…

Safe ASP.Net MVC application against cross site attacks - 1

Do you trust user input?!!!!!!!. If your answer is YES, stop reading and do something else. If your answer is NO, I think reading this article may help you to make your site more secure. All user's inputs can be a back door for attacker to attack your site. User's inputs that we will categorize as un-trusted inputs are :
Incoming URLs including Request.QueryString[] valuesForm post data (Request.Form[] values including values from hidden fields and disabled fields)CookiesData in HTTP Headers (such as Request.UserAgent and Request.UrlReferrer). Your site could be attacked by altring the query string, form values, or cookies data. The solution is not to prevent request manipulation but to check that each request is a legal request for the logged-in visitor.

Cross-Site Scripting and HTML Injection:
If an attacker can get our site to return some javascript to our visitors, then the attacker's script can take control of our visitors' browsing session and by this the attac…

5 tips to get started LINQ in C#

1-LINQ is not just for Iteration :
LINQ (Language integrated Query) is not just for queries a collection of objects, but it will be better if you think about it as a data iteration engine. If you called a method that return data of some type that you needed to convert to another datatype before passing it to another method. Assume you have a method A() that return Array of integers and you need to pass this array to method B() that accepts array of string. You should iterate over array items, one by one, to convert it.But with with LINQ you can do that with just one line of code.
Int32[] nums = {23 , 45 , 65 , 23}; String[] numbers = nums.Select(i => i.ToString()).ToArray();
2-Use the var keyword: 

If you are confused about the type of the sequence result of your query and want to get your code to compile use var keyword. Your query will return an IEnumerable sequance of some type but you don't know exactly what is that type so the best choice is using var keyword.

3-Use the Cast…

Design Patterns Series 21 - How to create your own pattern?

By this post we finish our design pattern series. This post gives you a guide for how to build your own pattern in ten easy steps. Just follow along, and you are on the route to fame and fortune.

If you don't see an established design pattern where you think there should be one?. You can create your own design pattern, and you can publicize that pattern, getting it into design pattern repositories around the world.

Remember, design patterns are supposed to make solutions easier. Don't create a design pattern just for the sake of creating a new pattern if it's not going to be helpful. After all, patterns are supposed to be tools, not hindrances.

Pattern Catalog Style :

The best way to start anything is with a guide of some kind, and for design patterns, that guide is the Pattern Catalog Style. There are ten sections in a pattern catalog style :
IntentMotivationApplicabilityStructureParticipantsCollaborationsConsequencesImplementation/Sample CodeKnown UsesRelated Patterns In…

Design Patterns Series 20 - Double Buffer, Recycle Bin, and MVC Patterns

In this post we will explore the last three patterns in our design patterns list, Double Buffer Pattern, Recycle Bin Pattern, and Model/View/Controller (MVC) Pattern.

Double Buffer Pattern :

Double Buffering is used to avoid screen flicker when you are displaying graphics. The idea is that you perfrom your multi-step graphics creation off-screen in a buffer and then flash the results on the screen when they're complete. The process is called Double Buffering because the screen display buffer is one buffer and the buffer in which the images are prepared is the second buffer.

Use a Double Buffer when generating revised datasets for an asynchronous processor. When the new data is complete and self consistent, redirect the asynchronous processor to the alternate buffer.

Recycle Bin Pattern :

If your code uses many objects and the object-creation process is time - and resource - intensive, you might want to use the Recycle Bin Pattern. The idea is that when you're done with an object…

Design Patterns Series 19 - Circular Buffer Pattern

Image
Circular Buffer Pattern :

Circular Buffer is perfect when one part of your code stores data and another part reads that data asynchronously. Makes very efficient use of memory.

A Circular Buffer is a memory allocation scheme where memory is reused when an index, incremented modulo the buffer size, writes over a previously used location. A Circular Buffer makes bounded queue when separate indices are used for inserting and removing data. The queue can be safely shared between threads (or processors) without further synchronization so long as one processor en-queues data and the other de-queues it.

You store data items in the various locations in a ring buffer and keep track of reading and writing operations  by labeling one location the Head and one the Tail.

When you store an item in the Circular Buffer you store the item at the tail location, and the tail advances to the next location.
When you read an item, you read the item at the current head location, and the head advances to th…

Design Patterns Series 18 - More Design Patterns

This Post will discover more than one design pattern. They are all good patterns, but some are not used these days. And some are just plain hard to implement, like the Interpreter Pattern.

Abstract Factory Pattern :

The Abstract Factory Pattern describes a factory of factories, or, more properly thought of, an abstract specification for an actual object factory. Here's the problem: sometimes you might need more than one factory to create objects of a similar nature.

An Abstract Factory is usually implemented as an abstract class that real, concrete factories extend. That unifies what the concrete factories do, while allowing leeway to fit differing requirements.

The Abstract Factory Pattern should "provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Prototype Pattern :

The Prototype Pattern says that when it takes a lot of resources, or a lot of code, to create an object, you should consider simply copying…

Design Patterns Series 17 - Mediator Pattern

The Mediator Pattern :

The Mediator Pattern supports coordination between objects. it makes the coupling looser by having all objects report state changes to the mediator and take commands from the mediator.

When you use a mediator, you are encapsulating the interaction between objects. Each object no longer has to know in detail how to interact with the other objects. The coupling between objects goes from tight and brittle to loose and agile.

You can use the Mediator Pattern to "define an object that encapsulate how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."

The  Mediator Pattern should your first choice as a possible solution any time you have a set of objects that are tightly coupled. If every one of a series of objects has to know the internal details of the other objects, and maintaining those relationships becomes a problem, think of the