May 10th, 2012 by Emad Mokhtar

ASP.NET Expression is written inline surrounded with <% %> in other words you will write them with your markup in .ASPX files for specific task, for example if want to access a connection string there an expression for that

  1. <%$ ConnectionStrings:DefaultConnection %>

Let’s lists all ASP.NET Expression and it’s task:

  1. Directive Expression <%@ .. %> 
    • It’s used in Web Forms .ASPX files or User Control .ASCX files to set settings, for example the Page directive where you can declare Title, Master Page, Language, etc….
      <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPNETExpressions._Default" %>

  2. Data-Binding Expression <%# .. %>
    • Create binding between server control with data source when calling DataBind() method, most of the time you’ll see this expression inside Data Bound Controls like GridView and DetailView.
      <asp:TextBox runat="server" ID="txtFirstName"  Text="<%# Eval("FirstName") %>"/>

  3. Expression Builder <%$ .. %>

    • This expression is used to set controls properties that located in configuration files Web.Config such as AppSettings, ConnectionStrings, or Resources
    • It’s syntax is <%$ Expression Prefix: Expression Value %>
      <%$ ConnectionStrings:DefaultConnection %>

  4. Server-side Comment Expression <%– .. –%>

    • It’s to comment a block of code so that it’ll not rendered or executed inside the page.
      <%– This is a comment –%>

  5. Displaying Expression <%= .. %> 
  • It’s the simplest way to display one piece of information such as Integer or String inside the page, it’ll be converted to Response.Write().
    <%= DateTime.UtcNow.ToString("dd/MM/yyyy") %>

      Tip:

      Every time you’ll see <% look at the next character:

      • If it @ then it’s Directive Expression.
      • If it = then it’s Displaying Expression.
      • If it # then it’s Data-Binding Expression.
      • If it — then it’s Comment.
      • If it $ then it’s Expression Builder.

      Note:

      If you make incorrect syntax inside these expression, Exception will be thrown.

      Read the rest of this entry »

      Tags: ,
      Posted in asp.net | No Comments »
      May 3rd, 2012 by Emad Mokhtar

      asp.net

      ASP.NET Page Lifecycle is very important piece of knowledge every ASP.NET developer must know, and unfortunately some of ASP.NET developer out there don’t know and they think it’s not important to know.

      Let’s dig in and let’s examine ASP.NET Lifecycle but in short list and description:

      1. PreInit():
        • In this event all Controls created and Initialized with their default values. You can create dynamic Controls here. You can set theme programmatically here
      2. OnInit():
        • In this event you can read the Controls properties the were set in Design Mode and can not read values changed by user.
      3. LoadViewState():
        • This event fires only if the page is posted back “IsPostback == true;” and here View State data where are stored in hidden form fields get de-serialized and loads all controls View State data.
      4. LoadPostBackData():
        • This event only fires when Page is posted back and Controls which implement IPostBackDataHandler interface get loaded with values from HTTP POST data.
      5. Page_Load():
        • This event is well known among ASP.NET developers and here Page gets loaded and after it all Load() events of Page Controls fired.
      6. Control Event Handlers:
        • These are basically event handlers like Button click event handler “Button1_Click()” which fires after Page_Load() event.
      7. PreRender():
        • This event is fired for each page child controls and her you can change controls values.
      8. SaveViewState():
        • In this event Controls View State saved in Page hidden fields.
      9. Render():
        • Here all Controls get rendered or every Page Controls Render method is called.
      10. Unload():
        • Here we can have Page and Controls clean up operations. This event the Page and its Controls are rendered.

      Notes:

      1. ASP.NET Lifecycle will be called ever time there a request for the page.
      2. HTTP POST data has only one value per control, that’s why Control like Textbox can gets value from HTTP Post but Control like DropDownList can not gets data from HTTP Post it can gets data from View State.
      3. Init() and Unload() events are fired from outside to inside controls, fro example: user control Init() event will be fired before Page_Init() event

      Reference: ASP.NET Page Lifecycle on MSDN

      Tags:
      Posted in asp.net | 1 Comment »
      April 26th, 2012 by Emad Mokhtar

      U-Turn

      Technology U-Turn is a terminology I invented that means when a technology leave the direction and take a new one then get back to the old one, actually I invented this term when I realized till now there are two technologies did this, I don’t know if there are more or not but nowadays these two technologies are in the top of tech news.

      ASP.NET:

      In the past web developers were using Classic ASP till Microsoft released ASP.NET to help Windows Forms developers to develop Web Application with the same look and feel, then create the code behind approach where you will write the server-side code instead on inline script like in Classic ASP, but PHP still using the same approach by using inline scripting. Microsoft make the U-Turn and back to inline scripting in ASP.NET MVC especially in Razor view engine. in PHP you have the full control over HTML like in ASP.NET MVC.

      PHP stuck with the same direction of inline scripting and keep enhance its technology, but Microsoft change the direction to ASP.NET and guess what back again after enhance the inline scripting from ASPX view engine then Razor view engine.

      NoSQL:

      In the past data was stored in files/documents without any relations and normalization, then the relational database design start to be used by wide rang of folks till now actually the most popular database design is relational database to prevent duplications, more access speed, less capacity consuming; and now the world is making the U-Turn to NoSQL approach and back to use files/documents to store data, Mega companies like Google, Twitter, Facebook, and Microsoft is start to enhance the way of storing data in files/documents and start to use the feature provided by the Hard Drives file system, there are many of NoSQL engines released like RavenDB, Cassandra, Amazon SimpleDB, MongoDB, and CouchDB.

      The Question:

      Why Microsoft change its direction and released ASP.NET then after many years it discovered that it didn’t apply the Web Development in the right way and it was just helping the developers to create Web Applications with event oriented design rather than MVC design which become popular especially after Ruby on Rails aka RoR (RoR was invented to get rid of repeating the same task over and over again when developing with ASP.NET) get on surface? Why’s Microsoft didn’t stick with the direction and try to develop and enhance it and that what it’s doing nowadays?

      The same question to NoSQL the world, Why do we get back to document oriented database after spend years in relational databases? Why didn’t we stick with the direction and start to develop and enhance the way we are storing data inside the documents and that what NoSQL world are doing?

      April 6th, 2012 by Emad Mokhtar

      loser-2.ashx

      I keeping asking myself one question and wondering Why are we in Middle East industry losers? Why when we are trying to enter the industry with good quality product we totally fail? Why are we always consumers? What is the problem? For god sake what is wrong?
      I’ve start to draw a picture of what is the problem, but this picture is not a complete one. Please readers do not get me wrong I’m not writing this post to criticize, no I’m writing this post to identify the problem and I always believe the first step to solve a problem is to admit there is a problem.
      The picture is we are directing our power, money, and resources in wrong way, hmmm interesting How? Stockholders/Employer think when they reduce number of resources they will increase the profit and they do not consider the quality of the product, they are creating the product with minimum number of resource and budget and this will produce low quality and cheap product; in other word they are profit focus.

      The Illustration:

      To elaborate the idea I will take Cars Industry as example to illustrate the problem, in car industry there are standard processes to be done in order to get the normal quality car like, collect raw material, designing, and assembly. let’s take one of them which is Designing and make comparison between what will be done in Middle East and other part of the world where they take care of the quality of the product let’s say Asian.

      Designing

      To design a new car model takes from three to five years, designers predict What are people love to ride after three years? What will be public taste after three years? designer start drawing the model with help of computer equipment to help the designer experts to check if this design will be accepted in public, after the design pass this step here comes the aerodynamic engineers to review aerodynamics flow, to do feasibility tests, and crash tests. This what will be done in high quality focus industry, but in Middle East what will be done is just think about how to produce a car with minimum cost and maximum profit regardless the quality, lifetime, and the design; all what we need is hit and run sales, sale the car to the costumer, get the money, and we all done mission accomplished.

      Conclusion:

      Unfortunately if you look at the software industry in Middle East you will find this what is happening, I hope and dream about change the industry and the way of thinking to get this industry more better and solve this problem.

      I want a Silicon Valley in Middle Ease, I want Microsoft, Google, IBM, JetBrains, RedGate, Telerik, DevExpress,…..etc. Middle Ease Edition, I want this bar to get higher in Middle East.

      March 15th, 2012 by Emad Mokhtar

      Intresting tweet

      I saw very interesting tweet from Glenn Block @gblock and this remind me with something I read in The Clean Coder book from Uncle Bob Martin, which talks about professional developer and what to do to be a professional. Uncle Bob describe the professional developer takes the responsibility of his mistakes, it’s true because if he take this responsibility, he’ll learn from his mistakes and learn how he made it in first place, so he can avoid it next time, even if he make this mistake again he knows how to solve it quick and clean.

      Personally I learn like this and it’s teach you the lesson very well.

      Dear readers please give me your feedback/opinion about this subject.

      Tags: ,
      Posted in Coding | No Comments »
      March 10th, 2012 by Emad Mokhtar

      pict0554

      Today I was having a flight from Egypt, Cairo International Airport to Kuwait International Airport and when the airplane was almost reach Kuwait the pilot keep flying in circles and never enter the Kuwaiti boards and fly to the Arabian Gulf for 15 minutes we are wondering Why is he flying in all direction but not the one to Kuwait?

      This situation give me a sight for How your customer will feel when you haven’t or stop giving him/her information about the software. s/he’ll keep wondering what is he doing to my product? Is it done? Is it won’t be done?  and sometimes his/her mind will go to the opposite direction of what you are doing.

      Finally we found that there is a sandstorm at Kuwait International Airport and the visibility is zero and we can’t land, so we changed our direction to Dubai Airport to land there and what for the sandstorm to stop so we can get back. None of us thing in this.

      The part above I wrote while I’m sitting on floor beside the power socket to charge my laptop s I can write these thoughts and here I’m from another date and time after one week from this journey sitting on my couch continue writing this post, as I felt and saw the final result of what the airline did to us, after suffering from lack of information and even if we got it we get it too late, after we landed at the destination everyone forgive the airline because it deliver what we want, we want to get home have some rest in our bed, we want to get home whatever it takes and this what the airline did but with so mistakes but after it did it we become a happy customers.

      The bottom line: keep communicate with your customers and tell them what you’re doing even if it’s not the best way to do it or what you’re facing right now, and remember what the customer want is the most important goal you must get it whatever whenever however.

      February 15th, 2012 by Emad Mokhtar

      I faced this when developing SSRS report when user put period from 1/2/2012 to 31/12/2012. note this date in “dd/MM/yyyy” format, when passing these two dates to DateDiff() SQL function the result will be 10 months.

      DATEDIFF(month, '2/1/2012', '12/31/2012') 

      SNAG-0006

      This result is wrong for us but for SQL Server it’s correct because we still in December, but as human we consider this is the end of December, to solve this issue I wrote this SQL Statement:

      CASE
          WHEN DATEPART(day, '12/31/2012')BETWEEN 30 AND 31 THEN DATEDIFF(month, '2/1/2012', '12/31/2012') + 1
          ELSE DATEDIFF(month, '2/1/2012', '12/31/2012')
      END as DateDiff

      SNAG-0007

      Happy coding folks Winking smile

      February 11th, 2012 by Emad Mokhtar

      As a geek you tried at least one time to edit your Windows registry, and sometimes what you did break your Windows or Application, then you start to figure out what I did to roll it back to normal.

      To save your Windows and Applications you can backup your Windows Registry with jus few simple steps, No need for application to did so, it’s so ease too have an application do it.

      Dude, Show me the steps:

      First, we will open registry editor by press on  Windows Key + R to open Run Dialog –> write “regedit” without quotes and press Ok

      SNAG-0001

      Second, Registry Editor will be open, go to File—>Export

      SNAG-0003

      Third, Save as dialog will open, browse to the folder where you want to backup you Registry to, give it a meaningful name  and save it, and you’re done.

      SNAG-0005

      How to restore the backup?

      Open Registry Editor and just import the backup file.

      February 2nd, 2012 by Emad Mokhtar

      I always asked myself, how can I show a neat notification and call it from Page code behind? I want to call this notification after doing something in code behind, for example notify user that “Record Inserted Successfully” and this notification looks like the one on Twitter and Stackoverflow. I found jQuery plug-in called jNotify has what I want from the notification, and ASP.NET has the Method “ClientScriptManager.RegisterStartupScript Method” to add Script to page on runtime, so why not combine 2 together and create a helper method  plus make it extension method for Page.

      Helper Method:

      This is the most important part, here where the 2 part I mentioned above.

      using System.Web.UI;
      
      namespace jQueryNotification.Helper
      {
          public static class NotificationHelper
          {
              /// <summary>
              /// Shows the successful notification.
              /// </summary>
              /// <param name="page">The page.</param>
              /// <param name="message">The message.</param>
              public static void ShowSuccessfulNotification(this Page page, string message)
              {
                  page.ClientScript.RegisterStartupScript(page.GetType(), "notificationScript",
                                                          "<script type='text/javascript'>  $(document).ready(function () { $.jnotify('" +
                                                          message + "'); });</script>");
              }
          }
      }

      jNotify Script and Style:

      In order to use the helper method you need to add jQuery script and jNotify script and style

      <link href="Styles/jquery.jnotify.css" rel="stylesheet" type="text/css" />
      <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
      <script src="Scripts/jquery.jnotify.js" type="text/javascript"></script>

      Page Code Behind:

      ASPX:

      <asp:Button ID="btnSuccess" runat="server" Text="Successful Notification" onclick="btnSuccess_Click" />

      CS:

      Note: Make sure you add the helper method class reference to page’s code behind

      using System;
      using jQueryNotification.Helper;
      
      namespace jQueryNotification
      {
          public partial class Default : System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
      
              }
      
              protected void btnSuccess_Click(object sender, EventArgs e)
              {
                  this.ShowSuccessfulNotification("Success Notification");
              }
          }
      }

      Screenshots:

      SNAG-0031

      SNAG-0029

      SNAG-0030

      Project File:

      I uploaded a project include the notification helper methods I’m using in my projects, I’ve added 6 Methods:

      1. Successful Notification:
        1. Normal.
        2. Delayed
      2. Warning Notification:
        1. Normal.
        2. Delayed.
      3. Error Notification:
        1. Normal.
        2. Delayed.

      I hope these helper methods will help you in your ASP.NET projects, happy and productive coding everyone Winking smile

      On GitHub: https://github.com/EmadMokhtar/jQuery-Notification

      January 1st, 2012 by Emad Mokhtar

      If you want to add AJAX effect to ASP.NET webforms  full postbacks, add this meta tags to your page, or even better add it the your master page.

      <meta content="blendTrans(Duration=0.2)" http-equiv="Page-Enter" /></meta>
      <meta content="blendTrans(Duration=0.2)" http-equiv="Page-Exit" /></meta>

       

      This effect will remove the blinking  effect from ASP.NET pages, and they call it fajax aka the fake alternative to AJAX