tag:blogger.com,1999:blog-10752693432476469892024-03-13T08:50:04.060-07:00C# Magazinevar blog=CSharp.CreateMagazine();Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.comBlogger8125tag:blogger.com,1999:blog-1075269343247646989.post-75169526656234046302009-09-27T03:25:00.000-07:002009-09-28T22:28:51.022-07:00How to change event hanlders at run timeOne of the challenges when using event handlers at run time , in my opinion , is that we can't manage previously registered event handlers very easily . I mean we don't know who else is listening to the same event.<br /><br />Suppose we have two combo boxes and a list box.We want to let the user select a category in first combo box and select an object in second combo box and see a list of related information of that object in the list box.<br /><br />User selects Music category from category combo box.<br />User selects "Abby Road" from objects comb box.<br />A list of album information is shown to him.<br /><br />Here's the source:<br /><br /><pre class="coloredcode"><span class="kwd">private void</span> CategorySelected(<span class="kwd">object</span> sender,EventArgs e)<br />{<br /><span class="kwd">if</span>(<br />((Categroy)_categoryComboBox.SelectedItem).Type==<br />CategroyType.Music<br />)<br />{<br />_itemComboBox.DataSource=_application.GetMusicAlbums();<br />}<br />}<br /><br /><span class="kwd">private void</span> ItemSelected(<span class="kwd">object</span> sender,EventArgs e)<br />{<br /><br /><span class="kwd">if</span>(_itemComboBox.SelectedItem <span class="kwd">is</span> MusicAlbum)<br />{<br />_list.DataSource=<br />_application.<br />GetMusicAlbumAdditionalInfo<br />((MusicAlbum)_itemComboBox.SelectedItem);<br />}<br />}<br /></pre><br /><br />Well it's working but it's not very nice. As you can see we should write a lot of "if" to handle different kind of categories and objects.<br />OK we could change the event handler instead of using if.<br />Suppose that we have registered some event handlers in a dictionary then we can write :<br /><br /><pre class="coloredcode">_itemComboBox.SelectedItemChanged+=<br />_eventhandlersRegistry[selectedCategory.Type];</pre><br /><br /><br />But we have a little problem : what if there's already a category selected ? so we should first remove last SelectedItemChanged event handler then we have to write:<br /><br /><pre class="coloredcode">_itemComboBox.SelectedItemChanged-=<br />_lastSelectedItemChangedEventHandler<br />_itemComboBox.SelectedItemChanged+=<br />_eventhandlersRegistry[selectedCategory.Type];<br />_lastSelectedItemChangedEventHandler=<br />_eventhandlersRegistry[selectedCategory.Type];</pre><br /><br />To solve this kind of scenario , I recently use a solution that I'd like to share with you:<br />I use a nested EventHandler delegate therefore there's no need to change the event handler of actual event .Here's what I do:<br />I have an event handler delegate declared as :<br /><br /><pre class="coloredcode"><span class="kwd">private</span> EventHandler _nestedSelectedItemChangedEventHandler</pre><br /><br /><br />Then I have this general event handler for the actual event :<br /><br /><pre class="coloredcode">_itemComboBox.SeletedItemChanged+=<br /> GeneralItemChangedEventHandler;</pre><br /><br /><br />When the category is changed I place a new delegate in my nested event handler like this:<br /><br /><pre class="coloredcode">_nestedSelectedItemChangedEventHandler=<br />_registeredEventHandlers[_selectedCategory.Type];<br /></pre><br /><br />and GeneralItemChangedEventHandler will call nested event handler as follows:<br /><br /><pre class="coloredcode"><span class="kwd">private void</span> GeneralItemChangedEventHandler (<span class="kwd">object</span> sender,EventArgs e)<br />{<br /><span class="kwd">if</span>(_nestedSelectedItemChangedEventHandler!=<span class="kwd">null</span>)<br />_nestedSelectedItemChangedEventHandler(sender,e);<br />}<br /></pre><br /><br /><br />This approach can be used if you are implementing a strategy pattern so that you want to change the behavior by changing the state of your object and there's always a single event handler involved to handle an event.Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-37593979986319438672009-09-21T21:00:00.000-07:002009-09-21T22:44:02.621-07:00Using generic methods to avoid boxing-unboxingEvery time we convert a value type (int,decimal,double,etc) to a reference type (to an object to be specific) a boxing occurs (As MSDN define it , it means to put a value type inside heap) and if we convert an object to an int , an unboxing occurs. <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx">Here</a>'s an article on MSDN that describes it all.<br />I'm working on this method that gets a DataRow ,a FieldName and a default value and returns row[fieldname] value (if value is null or DBNull it returns the default value)<br />My first vesrion of this method is something like this:<br /><br /><pre class="coloredcode"><span class="kwd">public static string</span> GetFieldValue<br />(DataRow row,<span class="kwd"><br />string</span> fieldname,<br /><span class="kwd">string</span> defaultvalue)<br />{<br />var <span class="kwd">value</span>=row[fieldname];<br /><span class="kwd">if</span>(<span class="kwd">value</span>==<span class="kwd">null</span> || <span class="kwd">value</span>==DBNull.Value)<br /><br /><span class="kwd">return</span> defaultvalue;<br /><span class="kwd">return value</span>;<br />}</pre><br /><br /><br />Later ,I want to write an overload for this method to work with int values I write something like this:<br /><br /><pre class="coloredcode"><span class="kwd">public static int</span> GetFieldValue<br />(DataRow row,<br /><span class="kwd">string</span> fieldname,<br /><span class="kwd">int</span> defaultvalue)<br />{<br />var <span class="kwd">value</span>=row[fieldname];<br /><span class="kwd">if</span>(<span class="kwd">value</span>==<span class="kwd">null</span> || <span class="kwd">value</span>==DBNull.Value)<br /><br /><span class="kwd">return</span> defaultvalue;<br /><span class="kwd">return</span> (<span class="kwd">int</span>)<span class="kwd">value</span>;<br />}</pre><br /><br /><br />OK an unboxing is happening here and I can't do anything about it.<br />I think to myself here we have a sign of <a href="http://www.blogger.com/en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> violation .I can have a single method as a base,something like this:<br /><br /><pre class="coloredcode"><span class="kwd">public static object</span> GetFieldValue<br />(DataRow row,<span class="kwd"><br />string</span> fieldname,<br /><span class="kwd">object</span> fieldvalue)<br />{<br />var <span class="kwd">value</span>=row[fieldname];<br /><span class="kwd">if</span>(<span class="kwd">value</span>==<span class="kwd">null</span> || <span class="kwd">value</span>==DBNull.Value)<br /><span class="kwd">return</span> defaultvalue;<br /><span class="kwd">return value</span>;<br />}</pre>Then I can rewrite the int version like this:<br /><br /><pre class="coloredcode"><span class="kwd">public static int</span> GetFieldValue<br />(DataRow row,<br /><span class="kwd">string</span> fieldname,<br /><span class="kwd">int</span> defaultvalue)<br />{<br /><span class="kwd">return</span> (<span class="kwd">int</span>)GetFieldValue(row,fieldname,(<span class="kwd">object</span>) defaultvalue);<br />}</pre>But wait a second, I can see a boxing here which is not necessary but how can I get rid of it?<br />One solution that comes to my mind is to change my base method to a generic method:<br /><span class="kwd"><span style="font-family:monospace;"><br /></span>public static</span> T GetFieldValue<<span class="gen">T</span>><br /><pre class="coloredcode">(DataRow row,<br /><span class="kwd">string</span> fieldname,<br />T defaultValue)<br />{<br />var <span class="kwd">value</span>=row[fieldname];<br /><span class="kwd">if</span>(<span class="kwd">value</span>==<span class="kwd">null</span> || <span class="kwd">value</span>==DBNull.Value)<br /><span class="kwd">return</span> defaultvalue;<br /><span class="kwd">return</span> (T)<span class="kwd">value</span>;<br />}</pre><br /><br /><br />Again if T is a value type an unboxing will occur but there's no boxing and I can rewrite the int version as :<br /><br /><pre class="coloredcode"><span class="kwd">public static int</span> GetFieldValue<br />(DataRow row,<br /><span class="kwd">string</span> fieldname,<br /><span class="kwd">int</span> defaultvalue)<br />{<br /><span class="kwd">return</span> GetFieldValue<<span class="kwd">int</span>>(row,fieldname, defaultvalue);<br />}<br /></pre><br />I wrote a test that ran each method for 1,000,000 times and it turns out that the omitted boxing impact is very small.(418 ms for object version vs. 358 ms for generic version)Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-60854960888924280802009-09-19T05:33:00.000-07:002009-09-19T08:11:14.439-07:00A Custom linq query builderIn my opinion one the most interesting features of Linq is <a href="http://msdn.microsoft.com/en-us/library/bb882636.aspx">Expression Trees</a>.They let us build structured queries over IQueryable<t> type.<br />IQueryable<t> ,as its name implies, is an interface that let us build a query over a provided object of type T.Although IQueryable and expression trees are mostly used in Linq to sql but since every IEnumerable<t> can be converted to an IQueryable object (using System.Linq.AsQueryable method) these great tools are available to every kind of Linq (linq to Xml and linq to objects for example).<br />When we build an expression tree over an IQueryable object , the expression itself won't be executed until we really want to get the data.<br />For example if we write the following code:<br />(DataSource is an IQueryable<post> object)<br /><br /><pre class="coloredcode">var result=DataSource.Where(post=>post.Title.IndexOf(<span class="st">"Linq"</span>)>0);<br /><br /></pre><br /><br /><br />result is yet another IQueryable<post> that you can query again :<br /><br /><pre class="coloredcode">result=result.Where(post=>post.CreationDate><span class="kwd">new</span> DateTime(2009,1,1));<br /><br /></pre><br /><br /><br />Now if we've added all we wanted to our query we can execute it either by converting the result to an ICollection (a List or an array for example) or by executing GetEnumrator method ( usually by using a for each loop).<br /><br />Based on this introduction I designed a custom query builder that facilitate querying an object using collected search arguments (in a windows /web form for example)<br /><br />Here's the scenario that I had in mind :<br />There's a web/win form that lets a user fill-in some information about what he wants to see.<br />Consider a blog application , a user can search post based on their titles and/or their creation date.Therefore a QueryPostArgs object is created and populated using the information provided by user.<br />Then this object is passed to a QueryBuilder to build a query from it.Query builder contains some register query methods and when is asked to build the query it will use them to build the final query.<br />Enough talking let write some code :<br /><br />To collect and transfer the arguments information we have an AbstractQueryArgs class.<br /><br /><pre class="coloredcode"><span class="kwd">public abstract class</span> AbstractQueryArgs<<span class="gen">t</span>> <span class="kwd">where</span> T :<span class="kwd">class</span><br />{<br />}<br /><br /></pre><br /><br /><br />To build queries over a post object we then derived from it and create a PostQueryArgs class.<br /><br /><pre class="coloredcode"><span class="kwd">public class</span> PostQueryArgs : AbstractQueryArgs<<span class="gen">post</span>><br />{<br /> <span class="kwd">public</span> PostQueryArgs()<br /> {<br /> CreationDateFrom = DateTime.MinValue;<br /> CreationDateTo = DateTime.MaxValue;<br /> }<br /> <span class="kwd">public string</span> Title { <span class="kwd">get</span>; <span class="kwd">set</span>; }<br /> <span class="kwd">public</span> DateTime CreationDateFrom { <span class="kwd">get</span>; <span class="kwd">set</span>; }<br /> <span class="kwd">public</span> DateTime CreationDateTo { <span class="kwd">get</span>; <span class="kwd">set</span>; }<br /> <span class="kwd">public string</span>[] Tags { <span class="kwd">get</span>; <span class="kwd">set</span>; }<br />}<br /><br /></pre><br /><br />To build query using an AbstractQueryArgs we have an AbstractQueryBuilder like this:<br /><br /><pre class="coloredcode"><span class="kwd">public abstract class</span> AbstractQueryBuilder<<span class="gen">t,tsearchargs</span>> <span class="kwd"><br />where</span> T :<span class="kwd">class where</span> TSearchArgs :AbstractQueryArgs<<span class="gen">t</span>><br />{<br /> <span class="kwd">protected delegate</span> IQueryable<<span class="gen">t</span>><br /> QueryMethodDelegate<br /> (IQueryable<<span class="gen">t</span>> queryable,TSearchArgs searchArgs);<br /><br /> <span class="kwd">public</span> IQueryable<<span class="gen">t</span>> DataSource { <span class="kwd">get</span>; <span class="kwd">private set</span>; }<br /> <span class="kwd">private readonly</span> List<QueryMethodDelegate><br /> _queryMethodDelegates = <span class="kwd">new</span> List<QueryMethodDelegate>();<br /><br /><br /> <span class="kwd">protected</span> AbstractQueryBuilder(IQueryable<<span class="gen">t</span>> dataSource)<br /> {<br /> DataSource = dataSource;<br /> }<br /><br /><br /> <span class="kwd">protected void</span> AddQueryMethod(QueryMethodDelegate queryMethodDelegate)<br /> {<br /> _queryMethodDelegates.Add(queryMethodDelegate);<br /> }<br /> <span class="kwd">public</span> IQueryable<<span class="gen">t</span>> Build(TSearchArgs searchArgs)<br /> {<br /> var queryable = DataSource<br /> <span class="kwd">foreach</span> (var queryMethodDelegate <span class="kwd">in</span> _queryMethodDelegates)<br /> {<br /> queryable=queryMethodDelegate(queryable,searchArgs);<br /> }<br /><br /> <span class="kwd">return</span> queryable;<br /> }<br />}<br /><br /></pre><br /><br />It allow us to build custom query builders for any T class.As you can see it gets an </post></post></t></t></t>IQueryable <t><t><t><post><post> as its data source via constructor.Then we can add some query methods to a list of query methods . A query method is any method that gets an IQueryable and a query arguments object and returns an IQueryable (It somehow a visitor method that visits an IQueryable object and do something on it based on provided query arguments and return it back ) To define a query method a protected delegate is defined.Every class that is derived from this abstract class can add its custom query methods to the query methods list using AddQueryMethod protected method.<br />Finally there's this Build method that build an IQueryable object using the provided datasource and passing it to each query method.As you can see this method is also returning an IQueryable<t> object that lets us to perform any further queries over it if necessary.<br /><br />Now we can create our custom query builder for our post object as follows:<br /><br /><pre class="coloredcode"><span class="kwd">public class</span> PostQueryBuilder:AbstractQueryBuilder<<span class="gen">post,postqueryargs</span>><br />{<br /> <span class="kwd">public</span> PostQueryBuilder(IQueryable<<span class="gen">post</span>> dataSource) : <span class="kwd">base</span>(dataSource)<br /> {<br /> AddQueryMethod(AddTitleExpression);<br /> AddQueryMethod(AddCreationDateExpression);<br /> AddQueryMethod(ContainsAllTags);<br /> }<br /><br /> <span class="kwd">private static</span> IQueryable<<span class="gen">post</span>><br /> ContainsAllTags(IQueryable<<span class="gen">post</span>> queryable , PostQueryArgs queryArgs)<br /> {<br /> <span class="kwd">if</span> (queryArgs.Tags == <span class="kwd">null</span> || queryArgs.Tags.Length == 0) <span class="kwd">return</span> queryable;<br /> <span class="kwd">return</span> queryable.Where<br /> (x => x.Tags.Intersect(queryArgs.Tags).Count() == queryArgs.Tags.Length);<br /> }<br /><br /> <span class="kwd">private static</span> IQueryable<<span class="gen">post</span>><br /> AddTitleExpression(IQueryable<<span class="gen">post</span>> queryable,PostQueryArgs queryArgs)<br /> {<br /> <span class="kwd">return string</span>.IsNullOrEmpty(queryArgs.Title) ? queryable :<br /> queryable.Where(x=>x.Title.IndexOf(queryArgs.Title)!=0);<br /> }<br /><br /> <span class="kwd">private static</span> IQueryable<<span class="gen">post</span>><br /> AddCreationDateExpression(IQueryable<<span class="gen">post</span>> queryable,<br /> PostQueryArgs queryArgs)<br /> {<br /> <br /> <span class="kwd">return</span> queryable.Where(<br /> x => x.CreationDate >= queryArgs.CreationDateFrom &&<br /> x.CreationDate <= queryArgs.CreationDateTo); } </pre><br /><br />As you can see this class add three query methods to query methods list.One for title,one for creation date and one for tags.<br /><br />Now that we have created these classes , all we need to do to build a query on a post datasource is like this:<br /><br /><pre class="coloredcode">var posts=<span class="kwd">new</span> []{_post1,_post2,_post3};<br />var queryBuilder=<span class="kwd">new</span> PostQueryBuilder(posts);<br /><br />var queryArgs=<span class="kwd">new</span> PostQueryArgs{Title=<span class="st">"Intro"</span>,Tags=<span class="kwd">new</span> []{<span class="st">"C#"</span>,<span class="st">"Linq"</span>}};<br />var query=queryBuilder.Buid(queryArgs);<br /><br /></pre><br /><br /><br />Then we have a IQeryable<post> object that when we try to enumerate it , post objects with "Intro" in their title and containing "C#" and "Linq" tags will be returned.<br /><br />P.S. I have upload the source code in codeproject site you can fint it <a href="http://www.codeproject.com/Articles/42488/A-Custom-linq-query-builder.aspx">here</a>.<br /></post></t></post></post></t></t></t>Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com1tag:blogger.com,1999:blog-1075269343247646989.post-61622810714849941412009-09-14T21:18:00.000-07:002009-09-14T23:42:19.235-07:00Intercepting NHibernateOne of the greatest things about NHibernate ,that I like so much, is that you can customize it very easily.<br />Most of the times you can work with <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO</a> but if you want to do some custom stuffs when an object is going to be worked upon via NHibernate you can implement NHibernate.ILifeCycle (NHibernate.Classic.ILifeCycle in NHibernate 2) interface that has some OnXXX methods that let you add your functionality when something is going to happen.Using this mechanism you can customize the persistence behavior of individual objects but what if you have a pattern that applies to large amount of objects in your application?<br /><br />To make it clear let's consider this scenario :<br />You want to add a feature to a set of implemented objects to keep who has created them and who changed them for the last time.<br />Since there might be so many places where these common information should be set in the code it could be a hard task to change the code.Here's where NHibernate.IInterceptor comes to play.IInterceptor provides some methods that let you intercept session actions.<br />Enough talking let's write some code for above scenario:<br /><br />First I create an IUserActivity interface :<br /><br /><pre class="coloredcode"><span class="kwd">public interface</span> IUserActivity<br />{<br />User CreatedBy{<span class="kwd">get</span>;<span class="kwd">set</span>}<br />User LastUpdatedBy{<span class="kwd">get</span>;<span class="kwd">set</span>;}<br />}</pre><br /><br /><br />Now all the objects that want to save their user activity should implement this interface (and these properties should be defined in database and in mapping files)<br /><br />Then I create an Interceptor that implements NHibernate.IInterceptor :<br />(Since I'm going to change the state of objects before saving/updating them I only need to implement OnSave method and to notify NHibernate that other methods are not implemented simply we return the method default value of its return type.)<br /><br /><pre class="coloredcode"><span class="kwd">public class</span> NHInterceptor:IInterceptor<br />{<br />.....<br /><br /><span class="kwd">public void</span> OnSave(<span class="kwd">object</span> entity,<span class="kwd">object</span> id,<span class="kwd">object</span>[] state,<span class="kwd"><br />string</span>[] propertyNames,IType[] types )<br />{<br />var userActivity=entity <span class="kwd">as</span> IUserActivity;<br /><br /><span class="kwd">if</span>(userActivity==<span class="kwd">null</span>) <span class="kwd">return</span>;<br /><span class="cmt">//I use an IoC container to get the AuthenticationProvider that<br />//provides user information.</span><br />var authenticationProvider=<br />ObjectRepository.Resolve<<span class="gen">AutenticationProvider</span>>();<br /><span class="kwd">if</span>(userActivity.CreatedBy==<span class="kwd">null</span>) <span class="cmt">// this object is not created yet</span><br /><br />{<br />userActivity.CreatedBy=authenticationProvider.CurrentUser;<br />}<br />userActivity.LastUpdatedBy=authenticationProvider.CurrentUser;<br />}<br />.....<br />}</pre><br /><br />As you can see you can easily change the state of your objects before saving them using an interceptor.<br /><br />Other arguments of OnSave methods hold new information for entity.State array has the values ,propertyNames array has the name of properties and types array has types of properties.<br /><br />To intercept a session simply open a session providing an interceptor:<br /><br /><pre class='coloredcode'>var session=SessionFactory.OpenSession(<span class='kwd'>new</span> NHInterceptor());</pre>Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-51639144947355061592009-09-14T04:08:00.000-07:002009-09-14T13:05:11.857-07:00Try Finally PatternThis kind of coding style seems to be very common:<br /><br /><pre class="coloredcode"><span class="kwd">public void</span> DoSomething(<span class="kwd">string</span> filename)<br />{<br />var file=File.OpenText(filename);<br /><span class="kwd">if</span>(! some_condition)<br />{<br />file.Close();<br />file.Dispose();<br /><span class="kwd">return</span>;<br />}<br /><span class="cmt">//Do some other stuff</span><br />file.Close();<br />file.Dispose();<br />}</pre><div style="text-align: justify;">The problem here (as you can see) is that we are repeating some lines that<br />should be executed either everything is ok or if something is wrong.<br />(A violation of <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>)<br /></div><br />We can refactor this code like this:<br /><pre class="coloredcode"><span class="kwd">public void</span> DoSomething(<span class="kwd">string</span> filename)<br />{<br /><span class="kwd">try</span><br />{<br />var file=File.OpenText(filename);<br /><span class="kwd">if</span>(! some_condition)<br />{<br /><span class="kwd">return</span>;<br />}<br /><span class="cmt">//Do some other stuff</span><br /><br />}<br /><span class="kwd">finally</span><br />{<br />file.Close();<br />file.Dispose();<br />}<br />}<br /><br />Now no matter what will happen in our try block , finally block<br />will always run.<br /><br />In this particular case since we are using an IDisposable class<br />(FileStream)we can make our code even more readable and<br />maintainable like this:<br /><br /><pre class="coloredcode"><span class="kwd">public void</span> DoSomething(<span class="kwd">string</span> filename)<br />{<br /><br /><span class="kwd">using</span>(var file=File.OpenText(filename))<br />{<br /> <span class="kwd">try</span><br /> {<br /> <span class="kwd">if</span>(! some_condition) <span class="kwd">return</span>;<br /> <span class="cmt">//Do some other stuff</span><br /><br /> }<br /> <span class="kwd">finally</span><br /> {<br /> <span class="kwd">if</span>(file!=<span class="kwd">null</span>)file.Close();<br /> }<br />}<br /><br />}<br /><br /></pre><br /><br /></pre>Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-30456999239508508722009-09-13T22:48:00.000-07:002009-09-14T00:30:35.216-07:00Permission Granted<div style="text-align: justify;">If you are working on a real world project chances are so high that authentication (who can access the system) and authorization (what he has permission to do)are among its non-functional requirements.<br />Authentication is somehow straight forward . There are a lot of approaches and patterns we can stick to but when it comes to authorization it's not that simple. The problem is people can have permission to perform an action globally or to perform it on some objects so whenever we want to check if somebody can do something we should check 1.the action and if necessary 2.the object that is acted upon.<br />Checking the action itself can be done by hard coding the action names in regarding methods so that every time a method is called it says if you want to run me you should have a XXXX permission but checking objects can't be hard coded and should be retrieved in run time therefore we should have a way to tell our program where to find the object.<br /><br />Here's a solution that we are using on our projects and I'd like to share it with you:<br /><span style="font-weight: bold;">Database:</span><br />We keep these information in a table:<br /></div><ul style="text-align: justify;"><li>Source (Who granted this permission)</li><li>Target(To whom this permission is granted)</li><li>Action(What action is granted)</li><li>Context(the action is granted on this context ,it can be a global definition or a type of an object or id of an object)</li><li>Type (if it's granted or denied )</li></ul><div style="text-align: justify;"><span style="font-weight: bold;">Domain Model:</span><br />in our<span style="font-weight: bold;"> </span>domain model we have this PermissionAttribute to mark a method so that whenever we want to run it ,its permission should be checked.<br /><br />for example if there a AddFolder method and user should have a AddFolder permission we write it as follows:<br /><br /><pre class="coloredcode">[Permission(Action=<span class="st">"AddFolder"</span>,Context=<span class="st">"Folder"</span>)]<br /><span class="kwd">public void</span> AddFolder(Folder folder)<br />{<br /><br />}</pre>Then we know that every user who wants to run this method should have an "AddFolder" permission on Folder context but what if we want to check if he can add a folder to a specific folder here's what we do :<br /><pre class="coloredcode">[Permission(Action=<span class="st">"AddFolder"</span>,Context=<span class="st">"Folder"</span>)]<br />[Permission(Action=<span class="st">"AddFolder"</span><br />,ContextLookup=<span class="st">"folder.ParentFolder.Id"</span>)]<br /><span class="kwd">public void</span> AddFolder(Folder folder)<br />{<br /><br />}<br /><br /></pre><div style="text-align: justify;">It says that not only user should have a permission to AddFolder generally but also<br />should have a AddFolder permission on ParentFolder.<br /></div><pre class="coloredcode"><br /></pre><div style="text-align: justify;"><span style="font-weight: bold;">How it works :</span><br /></div><pre class="coloredcode"></pre><div style="text-align: justify;">Finally we have this security checker interceptor in place that runs before a method<br />is called and check to see if there's a permissoin attribute has set and<br />if there's a ContextLookup is available it gets object information query over<br />granted permissions and throws an exception if permission is not granted or is denied.<br /></div><pre class="coloredcode"></pre><br />Well that's all folks :)<br /><br /></div>Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-81888924580134373032009-09-04T09:09:00.000-07:002009-09-15T01:51:13.920-07:00Playing with fluent interfacesA while ago I was reviewing one of our projects code and I noticed that it was very complicated and I had a hard time understanding what was going on and I was one of the senior developers of the team.I thought to myself maybe we could have a more readable approach in coding so that it would be easier to understand what is the intention of the code.<br /><br />I think that using DSLs can help us to improve readability of our codes.As Martin Fowler teaches us in his brilliant <a href="http://martinfowler.com/dslwip/">book </a>about DSL there are mainly two kind of DSLs internal and external and there's this concept of "fluent interface" that let us implement a kind of internal DSL.<br /><br />Since I'm working with C# 3.0 and as far as I know C# is not a DSL friendly language I think using this fluent interface concept can be a good candidate to improve our code and have some useful DSLs in place.But how?<br /><br />Suppose that we have a Login method in our domain that lets us to authenticate a user using a login name and a password,Something like this:<br /><br />UsersDomain.Login(username,password);<br /><br />Actually every method like this is an action/command executing on a specific domain.Then we can have our domain specific language as follows:<br /><br />On Domain Do Action With Patameters<br /><br />And here's a C# example of the same:<br /><br />userDomain.Login().With((action)=>{action.Username=username;<br />action.Password=password;}).Do();<br /><br />I know this seems very verbose in comparison with our traditional version but if we have thousands lines of code combining different domains and logic declaring everything in the latter way should help us understand the code better.<br /><br />Let me show you a better example:<br /><br />Suppose we have a mailing application that lets a client to send an email and here's our traditional approach to implement it:<br /><br />var mail=new Mail();<br />mail.From=fromAddress;<br />mail.To=toAddress;<br />mail.Header=header;<br />mail.Body=body;<br />mail.Send();<br /><br />And here's the same using a fluent interface:<br />mail.Send().From(fromAddress).To(toAddress).Header(header).Body(body).Do();<br /><br />I would like to know what you think of this approach.Please let me knowNimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0tag:blogger.com,1999:blog-1075269343247646989.post-79439106796709699472007-08-16T03:17:00.000-07:002007-08-19T08:29:03.912-07:00Hello World!Hi everyone!<br />This blog (as its name shows) is a place dedicated to C# programming.<br />As a developer\programmer for about 10 years working with Visual Basic 6.0,VB.Net and C# ,I always wish to have a place in web that I can share my experiments with others.<br />Now I'm working to make that wish come true and here's where I decided to start.<br /><span style="font-weight: bold;"><br />What is C#?</span><br />C# is a programming language that let us to write some instructions and compile them to Microsoft.Net IL(intermediate language) that can be executed using Microsoft.Net framework on every machine that has MS.Net framework installed.<br /><br /><span style="font-weight: bold;">How to write C# programs?</span><br />To begin writing C# codes, you can download <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&displaylang=en">Microsoft.Net framework 2.0</a> from Microsoft site.<br />Then you can write you program using a text editor (e.g. NotePad) and compile it using a tool called "csc.exe"(see Hello world section below.)<br />You can also use <a href="http://msdn2.microsoft.com/en-us/vstudio/default.aspx">Microsoft Visual Studio IDE</a>(integrated development environment)to write and to compile your programs.<br />There's also an open source IDE for developing C# programs called <a href="http://www.icsharpcode.net/OpenSource/SD/">SharpDevelop</a>.<br /><br /><span style="font-weight: bold;">Hello world!</span><br />"Hello world" is a traditional program that provides a quick start for a programming language.You can find "Hello world!" programs written in almost all programming languages <a href="http://roesler-ac.de/wolfram/hello.htm"><span style="font-weight: bold;">here.</span></a>This program sends a simple Hello world message to an output device (usally the screen).<br />If you'd like to write a "Hello world!" program in C# you can write the following code in a text editor and save it (From now on,I will write programming codes in <span style="font-style: italic;">italic</span> style.)<br /><br /><span style="font-style: italic;font-size:100%;" >public class MyClass<br />{<br /> public static void Main()<br /> {<br /> System.Console.WriteLine("Hello World!");<br /> System.Console.ReadLine();<br /> }<br />}<br /></span><br />then you can compile it using csc tool and you will get an exe file.<br />if you have installed .Net framework 2.0 you can find csc under<br />%SystemRoot%\Microsoft.NET\Framework\v2.0.50727 folder.<br />To use csc it is recommended to put it in your windows path so you can run it from any folder on your computer.<br />You can run csc /? to see its help screen.<br />To compile your program you can type the following in a dos command window (HelloWorld.txt is the file that you've created in previous step):<br />csc HelloWorld.txt<br /><br />This will create a HelloWorld.exe.<br />If you execute the file you will get a hello world message on your screen.<br /><br />I will explain the code in next post.<br /><script src="http://www.google-analytics.com/urchin.js" type="text/javascript"><br /></script><br /><script type="text/javascript"><br />_uacct = "UA-2445009-1";<br />urchinTracker();<br /></script>Nimahttp://www.blogger.com/profile/06366912742825943305noreply@blogger.com0