Ehsan Ghanbari

Experience, DotNet, Solutions

Explicit interface in C#

You have used millions of times, but you maybe don’t know what they call it (I just saw it and I didn't know too). Suppose these two interfaces with a member Called WithDraw():

 

  1.  public interface IBankingA
  2.     {
  3.         void WithDraw();
  4.     }
  5.  
  6.     public interface IBankingB
  7.     {
  8.         void WithDraw();
  9.     }

Now If you want to implement the members of these two interfaces in a class, you should tell the compiler that I'm implementing the members of both interfaces as they have same name by typing the interface name before the method name like this:

  1.  public class Baking :IBankingA, IBankingB
  2.     {
  3.         void IBankingA.WithDraw()
  4.         {
  5.             throw new NotImplementedException();
  6.         }
  7.  
  8.         void IBankingB.WithDraw()
  9.         {
  10.             throw new NotImplementedException();
  11.         }
  12.     }

That's it!



Introducing book: Pro Asp.net 4.5 in C#

About two years ago, I read some chapters of Pro asp.net 3.5 (it was the second edition of the book). I remember that I didn't dig in some chapter like lifecycle and Context, Modules, Handlers, Caching, Managing paths, Configurations, …  but now as I really need to know what's exactly going on the behind of asp.net I've decided to read this book in detail. In my opinion it's necessary to every asp.net developer as it really convers more about asp.net and it's frameworks. 

This book is in my books queue and will start reading of this book soon. I think the most important part of the book is part2 as it discusses on basics of asp.net, core architecture of the framework. although readers could jump over this part as it's for guys who want to know the main scenario behind asp.net

 

Pro asp.net

 

This is the definition of Apress about the book:

Pro ASP.NET 4.5 in C# is the most complete reference to ASP.NET that you will find. This comprehensively revised fifth edition will teach you everything you need to know in order to create well-designed ASP.NET websites. Beginning with core concepts the book progresses steadily through key professional skills. You'll be shown how to query databases in detail, consider the myriad applications of XML, and step through all the considerations you need to be aware of when securing your site from intruders. Finally, you'll consider advanced topics such as using client-side validation, jQuery and Ajax.



How to turn off the caches in asp.net MVC

I've written about different kinds of caching in asp.net MVC here, I just wanted to turn off some specific caches in my project and found a way to do that, you can do that by overriding OnResultExecuting:

  1. public class TurnOffCache : ActionFilterAttribute
  2. {
  3.     public override void OnResultExecuting(ResultExecutingContext filterContext)
  4.     {
  5.         filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
  6.         filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
  7.         filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
  8.         filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  9.         filterContext.HttpContext.Response.Cache.SetNoStore();
  10.     }
  11. }

and then simply register this page in global.asax like this:

  1.   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  2.     {
  3.         filters.Add(new TurnOffCache());
  4.     }

Notice that this will remove all of the caches in your application. but in some cases you just want to remove the cache of an action , in these cases you can simply make the NoStroe property as true in caching:

  1. [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
  2. public ActionResult AnAction()
  3. {
  4.     return View();
  5. }

this could be useful When you cache a controller and just want to disable the cache for an action, cheers!



Why brackets are required for try/catch in C# ?

Have you ever think about that!? You don’t need to put bracket statement of if/else condition if your statement is not multiline. Needless to say, if you want to put if/else condition with just one line statement, it would be something like this:

  1.             if (a == b)
  2.                 Console.WriteLine("");
  3.             else
  4.                 Console.WriteLine("");

 

And if you have multiline statement for your if/else condition:

  1.            if (a == b)
  2.             {
  3.                 Console.ReadKey();
  4.                 Console.WriteLine("");
  5.             }
  6.             else if (a != b)
  7.             {
  8.                 Console.ReadKey();
  9.                 Console.WriteLine("");
  10.                 Console.WriteLine("");
  11.             }

 

Right? So let's dig in deeper, if you have nested if/else like this:

  1.    if (a == b)
  2.             {
  3.                 if (b < a)
  4.                 {
  5.                     Console.ReadKey();
  6.                     Console.WriteLine("");
  7.                   
  8.                     if (b < a + c)
  9.                         Console.WriteLine("");
  10.                     else
  11.                         Console.WriteLine("");
  12.                 }
  13.                 else
  14.                 {
  15.                     Console.Read();
  16.                     Console.WriteLine("");
  17.                 }
  18.             }
  19.             else
  20.             {
  21.                 Console.ReadKey();
  22.                 Console.WriteLine("");
  23.             }

 

That wouldn't make any difference because in C#, there is no any else without if and also there is totally one else for every if! It means that compiler will look for your if and will assign the next else to it, if you have bracket or not.

But in try/catch you can have multiple catches for a try and a try without any catch is impossible (because you should catch what have you tried!), take a look at this:

  1.            try
  2.             {
  3.                 if (a == b)
  4.                     Console.WriteLine();
  5.             }
  6.             catch (ArgumentException argumentException)
  7.             {
  8.                 Console.WriteLine(argumentException.Message);
  9.             }
  10.             catch (Exception exception)
  11.             {
  12.                 Console.WriteLine(exception.Message);
  13.             }

 

Now imagine this try/catch without any brackets (although it's a compile error!)

  1.           try   
  2.                 if (a == b)
  3.                     Console.WriteLine();
  4.            
  5.             catch (ArgumentException argumentException)    
  6.                 Console.WriteLine(argumentException.Message);
  7.        
  8.            catch (Exception exception)
  9.                 Console.WriteLine(exception.Message);
  10.            

 

Now, if you put another try/catch (bracket less) in this try , what will happen?       

  1.             try   
  2.                 if (a == b)
  3.                     Console.WriteLine();
  4.             try   
  5.                 if (b== c)
  6.                     Console.WriteLine();
  7.            
  8.             catch (ArgumentException argumentException)    
  9.                 Console.WriteLine(argumentException.Message);
  10.  
  11.             catch (ArgumentException argumentException)    
  12.                 Console.WriteLine(argumentException.Message);
  13.        
  14.             catch (Exception exception)
  15.                 Console.WriteLine(exception.Message);
  16.  

 

Which one of the above catches is for the first try? And which one of them is for the second try?? As every try has at least one catch so we have two try with three catch, witch one of them has two catches!??

That's why that it's impossible to have a bracket less try/catch because the compiler only detects them by bracket to determine that which catche is for which try, take another complex nested example:

  1.            try
  2.             {
  3.                 try
  4.                 {
  5.                     try
  6.                     {
  7.                         if (a == b)
  8.                             Console.WriteLine("");
  9.                     }
  10.                     catch (Exception exception)
  11.                     {
  12.                         try
  13.                         {
  14.                             //try something
  15.                         }
  16.                         catch (Exception exception2)
  17.                         {
  18.                             Console.Write(exception2.Message);
  19.                         }
  20.                         Console.WriteLine(exception.Message);
  21.                     }
  22.                 }
  23.                 catch (Exception e)
  24.                 {
  25.                     Console.Write(e.Message);
  26.                 }
  27.               
  28.             }
  29.             catch (ArgumentException argumentException)
  30.             {
  31.                 Console.WriteLine(argumentException.Message);
  32.             }
  33.             catch (Exception exception)
  34.             {
  35.                 try
  36.                 {
  37.                     //try somthing
  38.                 }
  39.                 catch (Exception ee)
  40.                 {
  41.                     Console.WriteLine(ee.Message);
  42.                 }
  43.                 Console.WriteLine(exception.Message);
  44.             }

 

I have market that catches of every try and Compiler will detect the catches only by bracket scopes, got it!? hope it be useful…

 

 



Attribute routing with asp.net MVC5

Until the latest version of asp.net (asp.net mvc4), routing was handling by Convention-based routing to matches a URI to an Action in a separate class (RouteConfig) registered in global.asax. but in asp.net MVC5  you can use attribute routing. It means you can use attribute to set routes to your actions. It's too easy getting started with attribute routing, you just need to refer RouteConfing.cs in App_Start folder and add  routes.MapMvcAttributeRoutes(); in RegisterRoutes:

  1.  public class RouteConfig
  2.     {
  3.         public static void RegisterRoutes(RouteCollection routes)
  4.         {
  5.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  6.             routes.MapMvcAttributeRoutes();
  7.             routes.MapRoute(
  8.                 name: "Default",
  9.                 url: "{controller}/{action}/{id}",
  10.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  11.             );
  12.         }
  13.     }

 

 

Now you should define attribute for your actions, create a simple Data class and some fake data:

  1.    public class SampleController : Controller
  2.     {
  3.        private List<Data> _datas = new List<Data>()
  4.         {
  5.             new Data {Id = 1, Name = "Ehsan"},
  6.             new Data {Id = 2, Name = "Micheal"},
  7.             new Data {Id = 3, Name = "Elizabeth"},
  8.             new Data {Id = 4, Name = "Sia"},
  9.             new Data {Id = 5, Name = "Behzad"},
  10.             new Data {Id = 6, Name = "Emrah"},
  11.             new Data {Id = 7, Name = "Anahita"}
  12.         };
  13.  
  14.       public ActionResult List()
  15.         {
  16.             var data = _datas;
  17.             return View(data);
  18.         }
  19.  
  20. }
  21.   public class Data
  22.     {
  23.         public int Id { get; set; }
  24.         public string Name { get; set; }
  25.     }
  26.  

Now run the application an navigate to List action of Sample Controller:

 

opps!

 

oops!  Remember that you told MVC to use attribute routing, so you should add the attribute routing to List action:

  1.         [Route("Sample/List/{Id?}")]
  2.         public ActionResult List()
  3.         {
  4.             var data = _datas;
  5.             return View(data);
  6.         }

 

Now it's ok to get a list of data in list view. to completing our sample add this piece of code in List view to be able to call other actions:

  1. @model List<AttributeRouting.Controllers.Data>
  2. @{
  3.     ViewBag.Title = "List";
  4. }
  5.  
  6. @foreach (var item in Model)
  7. {
  8.     @Html.ActionLink(item.Name, "Data", "Sample", new { id = item.Id }, null)
  9.     <br>
  10. }

 

Now add the Data action with Id parameter:

  1.         [Route("Sample/{Id?}")]
  2.         public ActionResult Data(int id)
  3.         {
  4.             var data = _datas.Select(c => c.Id == id);
  5.             return View();
  6.         }

 

If you call this action, Url should be is something like this:   http://localhost:54524/Sample/1

Now add another Data action with a different signature:

  1.        [Route("Sample/{Id}/{name?}")]
  2.         public ActionResult Data(int id, string name)
  3.         {
  4.             return View();
  5.         }

 

As you can see the name is in routing but it's optional, if you add another ActionLink in List view: 

  1. @foreach (var item2 in Model)
  2. {
  3.     @Html.ActionLink(item2.Name, "Data", "Sample", new { id = item2.Id, name = item2.Name }, null)
  4.     <br />
  5. }

 you can render the second Data action, and it would be something like this in browser:  http://localhost:54524/Sample/1/Ehsan

 

Create another action:

  1.         [Route("Sample/BlahBlah/{Id}")]
  2.         public ActionResult Another(int id)
  3.         {
  4.             return View();
  5.         }

 

And the related link in list view:

  1. @foreach (var item3 in Model)
  2. {
  3.     @Html.ActionLink(item3.Name, "Another", "Sample", new { id = item3.Id }, null)
  4.     <br />
  5. }   

 

Now if you navigate to the action, it would be :  http://localhost:54524/Sample/BlahBlah/1

By the way, you don't need to repeat the controller name in every action, you can use  [RoutePrefix("Sample")] for your controller to be available for all actions:

  1.     [RoutePrefix("Sample")]
  2.     public class SampleController : Controller
  3.     {
  4.          …
  5.     }

 

Cheers!



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?