Asp.net with Muhanad YOUNIS

TDD Masterclass By Roy Osherove

Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of "The Art of Unit Testing" (http://www.artofunittesting.com/), a leading tdd & unit testing book; he maintains a blog at http://iserializable.com (which amoung other things has critiqued tests written by Microsoft for asp.net MVC - check out the testreviews category) and has recently been on the Scott Hanselman podcast (http://bit.ly/psgYO) where he educated Scott on best practices in Unit Testing techniques. For a further insight into Roy's style, be sure to also check out Roy's talk at the recent Norwegian Developer's Conference (http://bit.ly/NuJVa). 

Full Details here: http://bbits.co.uk/tddmasterclass

bbits are holding a raffle for a free ticket for the event. To be eligible to win the ticket (worth £2395!) you MUST paste this text, including all links, into your blog and email Ian@bbits.co.uk with the url to the blog entry.  The draw will be made on September 1st and the winner informed by email and on bbits.co.uk/blog

Posted: Aug 25 2009, 08:36 AM by mohi88 | with no comments
Filed under: ,
Nobody Hates Software More Than Software Developers

I know that i did not write a tiny word since a long time!. all that because we have a new member on our family and i have to give her more attention. During my standby time i had some time to read some books and developers blogs.I red a very nice post by Jeff Atwood and want to share it with you Nobody Hates Software More Than Software Developers.

Posted: Jul 23 2009, 09:11 AM by mohi88 | with no comments
Filed under:
“What’s the biggest challenge with task estimates?”

Read this article from Eric Brechner about task estimation

I would estimate 

I believe it will help ;)

Global Timer (Background Timer)

Updated on 01.19.2009

Why do you need a Global Timer ?
There are many reason that you might want to use a global timer for, like pulling data from you database on time periods to prevent user from displaying empty data. I used the global timer to get signed up  online users data ( like online user count, cities and assigned rules).

there are 3 types of timer class in ASP.NET;

Here i will not discus the deference between the above timer class (you may check the links and read msdn about them)but I'll show how to use System.Threading.Timer to create a background timer.

the time that I’ll create in this article will be created once and will keep working as long as my web application keep working. If the application stopped for any reason the timer will start again with the application restart.

First of all create a class that will star Threading.Timer, make sure to create the timer starter method as Static method because we’ll call that method from Global.asax applicathin start method. Make the class as below;

Add using System.Threading; as reference;

   1:  public class TimerStarter
   2:  {
   3:      private static Timer threadingTimer;
   4:   
   5:      public static void StartTimer()
   6:      {
   7:          if (null == threadingTimer)
   8:          {
   9:              threadingTimer = new Timer(new TimerCallback(CheckData),
                                           HttpContext.Current, 0, 600000);
  10:          }
  11:      }
  12:      private static void CheckData(object sender)
  13:      {
  14:          //ToDo check Data
  15:      }
  16:  }

Now Let me explain the code above; I declared a threadingTimer but did not initialize it. The main method here is StartTimer; Its a static method. The method checks if the threadingTimer Object is null or not. If its the first time that the method is called the threadingTimer will be null and will be created. line 9 creates and sets the timer object. TimerCallback is the delegate that will be called within timer intervals, here I call CheckData Method. CheckData method must be overloaded to match TimerCallback delegate. HttpContext.Curent is the object that will be used by the callback method; if you do not need any extra information for your method you can pass it as null. the 0 (zero) force the threadingtimer to call CheckData method as soon as the timer is created. You may set any milliseconds you want the timer to wait and call CheckData method. 600000 tells the timer to call CheckData method every 10 min. Call your timer from Global.asax as below;

   1:      void Application_Start(object sender, EventArgs e) 
   2:      {
   3:          TimerStarter.StartTimer();
   4:      }

 

UPDATE : When your background thread throw and exception the working process will shout down! and IIS will recycle and start again so be careful.

 

That is all!

You may use System.Timers.Timer in a deferent way to achieve the same goal. Check MSDN for more details.

Hope this Helps

ScriptManager and MasterPage PageMethods !

I know that this subject has been asked many times therefore i would like to summarize it and give a small tutorial about how to do it.

I had some PageMethods on a default page which calls some web methods on code behind of the page. Before 1 week we decided to change the old structure of the project UI to use MasterPage. MaterPage triggered many problems with it, one of these problems that MasterPage does not support JS PageMethods! because MasterPage does not inherit from Web.UI.Page therefore you can not call PageMethods (its not a page!) – you can not call pagemethods on usercontrols too – so handle this problem and call your methods you can try this tutorial;

  • Create a MasterPage and add a ScriptManager on page.
  • On ScriptManager add the folowings
       1:  <asp:ScriptManager ID="ScriptManager" runat="server"
                   EnableScriptGlobalization="true"
       2:          LoadScriptsBeforeUI="true" 
    EnableScriptLocalization="true"
    EnablePageMethods="true">
       3:         <Scripts>
       4:              <asp:ScriptReference 
    Path="~/Javascript/MasterPageWSJS.js" />
       5:          </Scripts>
       6:          <Services>
       7:              <asp:ServiceReference 
                           Path="~/WebServices/MasterPageWS.asmx" />
       8:          </Services>
       9:      </asp:ScriptManager>

        Here we have 2 important sections
                   - Scritps which includes our JS file location
                   - Sevices which includes our Webservices location
       Here to be mentioned that EnablePageMethods attribute means nothing on MasterPages!.

  • Add a javascript file to the project ( here its  MasterPageWSJS.js)
       1:  function CallService() {
       2:  //CallFromMasterJS() is the name of the service method
       3:            MasterPageWS.CallFromMasterJS();
       4:    }

  • Add a Webservice file to the project (here it is MasterPageWS.asmx)
       1:  <%@ WebService Language="C#" Class="MasterPageWS" %>
       2:   
       3:  using System;
       4:  using System.Web;
       5:  using System.Web.Services;
       6:  using System.Web.Services.Protocols;
       7:  using System.Web.Script.Services;
       8:   
       9:  [WebService(Namespace = "http://tempuri.org/")]
      10:  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
      11:  [ScriptService]
      12:  public class MasterPageWS : System.Web.Services.WebService
      13:  {
      14:   
      15:      [WebMethod(EnableSession = true)]
      16:      public void CallFromMasterJS()
      17:      {
      18:   // todo: write the needed codes
      19:      }
      20:  }

      

Here some important notes about the service:

- decorate the service class with [ScriptService]

- Decorate your methods with [WebMethod] add if you want to use

session variables with it decorate it with

[WebMethod(EnableSession = true)] because webservices are

stateless by default

  • at the end add this code lines to your MasterPage codebehind:
       1:  if(!IsPostBack)
       2:  {
       3:  // masterBody is the ID of the masterpage body html tag       
            HtmlGenericControl body =
          (HtmlGenericControl)Page.Master.FindControl("masterBody");
       4:          body.Attributes.Add("onunload", "CallService();");
       5:  }

That is all !. when you start your page and refresh it the master page will unloaded and that will fire the event onunload on the page body which will call the JS and from there the web service will be called.

Hope this helps

this tutorial based on Calling Web Services from Client Script in ASP.NET AJAX


Publish Server Performance Monitors with MsChart

In this article I'll try to show you how to to use MsChart Controls with ajax update panel to publish your server performance counter variables.

Be sure to install these packages before your start;

MsChart Controls are free and new, I used to use owc 11 and later versions to achieve needed works on projects.

After you install these packages goon and create a new website in your visual studio. On vs2008 toolbox you’ll find some new controls which installed with MsChart package. You’ll find chart control under data tab. First add a ajax script manager and an update panel to your page. Inside the update panel drop a timer and set its interval to 3000 milliseconds (3 seconds). Drag and drop a chart control for toolbox to your update panel content section. You will have a chart section looks like below;

<asp:Chart ID="Chart2" runat="server">
        <Series>
            <asp:Series Name="Series1">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1">
            </asp:ChartArea>
        </ChartAreas>
</asp:Chart>

Here you can see that the chart control have got to main section Series and ChartArea, I’ll not discus these two section widely; you may have more information about chart control and its section from Microsoft Chart Controls for .NET Framework Documentation. the series section is related with graph it self and the chartarea section is related with chart area that will hold hold the drawn graph. In my project I configured chart section as below;

<asp:Chart ID="Chart1" runat="server" Height="592px" Width="412px"
ImageUrl="~/TempImages/ChartPic_#SEQ(300,3)"

BackColor="#D3DFF0" BorderLineStyle="Solid"
BackGradientEndColor="White" BackGradientType="TopBottom"
BorderlineColor="DarkGray" EnableViewState="true"
BackImageTransparentColor="White"
BackSecondaryColor="White" BorderlineDashStyle="Solid">

 

Do not change ImageUrl location!.

for Series;

<Series>
     <asp:Series Name="MySeries" XValueType="Double" ChartType="Spline"
BorderColor="180, 26, 59, 105"
YValueType="Double" BorderWidth="2" 
ShadowColor="254, 0, 0, 0" 
ShadowOffset="1"
 ChartArea="MyChartArea">
                            <Points>
                                <asp:DataPoint XValue="0" YValues="0" />
                            </Points>
                        </asp:Series>
  <asp:Series XValueType="Double"
 Name="Exceps Thrown"
 ChartType="Spline" 
BorderColor="180, 26, 59, 105"
YValueType="Double" 
BorderWidth="2" 
ShadowColor="254, 0, 0, 0" ShadowOffset="1"
ChartArea="Default" IsVisibleInLegend="true">
    <Points>
          <asp:DataPoint XValue="0" YValues="0" />
    </Points>
  </asp:Series>
</Series>

Here I used 2 series which mean that I’ll have to graphs in my chart. You can see that I used two different  chartareas that is because I’ll use two chart areas on the same chart control.There many charttypes that you can select depending on your project demands, in my example it choose Spline. Beside that I added a Points section which will give the graph a starting position ( in static chart and charts with out code behind you can add many datapoints to draw the graph needed).

and for Chart Area;

 <ChartAreas>
    <asp:ChartArea Name="Default" BorderColor="64, 64, 64, 64" 
BorderDashStyle="Solid"
     BackSecondaryColor="White" BackColor="64, 165, 191, 228" 
ShadowColor="Transparent"
     BackGradientStyle="TopBottom" Area3DStyle-Enable3D="true" 
Area3DStyle-PointDepth="1000"
      Area3DStyle-PointGapDepth="200" AlignmentOrientation="Horizontal">
          <Position Y="5" Height="50" Width="94" X="0"></Position>
                <AxisY LineColor="64, 64, 64, 64">
                     <MajorGrid LineColor="64, 64, 64, 64"></MajorGrid>

<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold">
</
LabelStyle>

                            </AxisY>

<AxisX LineColor="64, 64, 64, 64"
IsMarginVisible="False" Maximum="100" Minimum="0"

                                IsStartedFromZero="False">
                                <MajorGrid LineColor="64, 64, 64, 64">
</
MajorGrid>
                                <LabelStyle Font="Trebuchet MS, 8.25pt, 
style=Bold"
></LabelStyle>
                            </AxisX>
                        </asp:ChartArea>
   <asp:ChartArea Name="MyChartArea" BorderColor="64, 64, 64, 64" 
BorderDashStyle="Solid"
       BackSecondaryColor="White" BackColor="64, 165, 191, 228" 
ShadowColor
="Transparent"
       BackGradientStyle="TopBottom" Area3DStyle-Enable3D="true" 
Area3DStyle-PointDepth="1000"
       Area3DStyle-PointGapDepth="200" AlignmentOrientation="Horizontal">
              <Position Y="50" Height="45" Width="94" X="0"></Position>
                 <Area3DStyle Enable3D="true" PointDepth="1000"
PointGapDepth="200" />
                     <AxisY LineColor="64, 64, 64, 64">
                        <MajorGrid LineColor="64, 64, 64, 64"></MajorGrid>
                                <LabelStyle Font="Trebuchet MS, 8.25pt, 
style=Bold"
></LabelStyle>
                            </AxisY>
                            <AxisX LineColor="64, 64, 64, 64" 
IsMarginVisible="False" Maximum="100" Minimum="0"
                                IsStartedFromZero="False">
                                <MajorGrid LineColor="64, 64, 64, 64">
</
MajorGrid>
                                <LabelStyle Font="Trebuchet MS, 8.25pt, 
style=Bold"
></LabelStyle>
                            </AxisX>
                        </asp:ChartArea>
                    </ChartAreas>

 

Points of intrest in ChartAreas are Position, AxisX and AxisY section. In position section you give the locations of your chartarea over the chart control it self. Since I have two chartareas I replaced them under each other. AxisX and AxisY are used to configure your graph axes; even if you don’t configure this section you can still use your chart but you’ll have some graphical problems until you data is sent to chart and display start. after all that configuration the chart control will look as below ( you may download the project from the link in the bottom of the article )

   

Now let us go to code behind and see how to send our performance monitors values to chart.

on Timer tick event I replaced 2 methods; the first one will set the performance monitors and the other will fill the chart as below;
(Do not forget to add using System.Web.UI.DataVisualization as a reference)

   1:  protected void Unnamed1_Tick(object sender, EventArgs e)
   2:          {
   3:              StartMonitor();
   4:              ChartCondfig();
   5:           }

for StartMonitor method;

 private void StartMonitor()
        {
 
   pc1 = new PerformanceCounter(".NET CLR Exceptions", "# of Exceps Thrown", 
"_Global_");
  // get the current value
  float dResult1 = pc1.NextValue();
 
  pc2 = new PerformanceCounter("ASP.NET", "Application Restarts", "");
   float dResult2 = pc2.NextValue();
 
  pc3 = new PerformanceCounter("ASP.NET", "Requests Current", "");
 float dResult3 = pc3.NextValue();
 
   pc4 = new PerformanceCounter("ASP.NET", "Requests Queued", "");
   float dResult4 = pc4.NextValue();
 
   pc5 = new PerformanceCounter("ASP.NET", "Worker Process Restarts", "");
   float dResult5 = pc5.NextValue();
 
  pc6 = new PerformanceCounter("ASP.NET", "Request Execution Time", "");
  float dResult6 = pc6.NextValue();
 
   pc10 = new PerformanceCounter("Memory", "Available MBytes", "");
  float dResult10 = pc10.NextValue();
 
        }
 

Here pc1 – 10 are declared on page load. and you can add much performance counter as you want. In this example I selected pc1 and 10 to be shown in the graph.

For ChartCondfig method; (sorry the code is not well formatted)

 
 
   1:  private void ChartCondfig()
   2:          {
   3:              double lastXValue =
   4:           this.Chart1.Series[0].Points[this.Chart1.Series[0]
.Points.Count - 1].XValue + 1;
   5:              this.Chart1.Series[0].Points.AddXY(lastXValue++, 
                  Convert.ToDouble(pc1.NextValue()));
   6:   
   7:              double lastXValue1 = this.Chart1.Series["MySeries"]
       .Points[this.Chart1.Series["MySeries"].Points.Count - 1].XValue + 1;
   8:              this.Chart1.Series[1].Points.AddXY(lastXValue1++, 
Convert.ToDouble(pc10.NextValue()));
   9:   
  10:              // Adjust categorical scale
  11:              double axisMinimum = this.Chart1.Series[0]
                 .Points[0].XValue;
  12:              this.Chart1.ChartAreas[0].AxisX.Minimum = axisMinimum;
  13:              this.Chart1.ChartAreas[0].AxisX.Maximum =
                                         axisMinimum + 100;
  14:   
  15:              this.Chart1.ChartAreas[1].AxisX.Minimum = axisMinimum;
  16:              this.Chart1.ChartAreas[1].AxisX.Maximum =
axisMinimum + 100;
  17:   
  18:              // Remove points from the left chart side if number of 
points exceeds 100.
  19:              while (this.Chart1.Series[0].Points.Count > 100)
  20:              {
  21:                  // Remove series points
  22:                  foreach (Series series in this.Chart1.Series)
  23:                  {
  24:                      series.Points.RemoveAt(0);
  25:                  }
  26:              }
  27:          }

on line 3 a double value named lastXvalue is declared this variable will hold the last point position over the X axes. on line 5 our first series on the chart will add a new point on X axes and Y axes.For X axes ,increasing  lastXvalue variable will be enough and for Y axes point performance monitor current value is given.

   5:  this.Chart1.Series[0].Points.AddXY(lastXValue++, 
       Convert.ToDouble(pc1.NextValue()));

 

Adjusting the categorical scale of the chartarea is important; otherwise win your lastXValue reaches the end of the scale you’ll have a problem, there for on line 16 we tell the chart to extend the scale. From line 19 to 26 I removed the points from series after the left side of the chart exceeds 100.

If you are debugging your project you well receive no exception but on runtime a small exception will rise; your application will look for a folder named TempImageFiles; goon and create this folder on the location shown in the exception and your application will run.

When you run the project you’ll have your chart as below;

To make with example work on your server and other computers you need to install the Download the free Microsoft Chart Controls package.

That's all. In this article I tried to explain how to use MsChart to publish you server performance monitoring values. You can change and play around with charttypes and do many other nice works with that.

Download the sample project from here

For more information about MsChart you can check these links;

This article is based on Microsoft Chart Controls Web Samples project ajax section.

MIX09 10K Smart Coding Challenge

For Smart Coding and Smart Coders !

http://2009.visitmix.com/MIXtify/TenKGallery.aspx

Extend Forms Authentication Ticket Depending on Session Time Out

I know that this subject is not new! but last week one of my students asked me about how we can extend client authentication ticket according to session time out. We should do some coding to achieve such a goal.

I’ll suppose that you have a master page or a main page with frames (no frames for master page) step by step let us do the following;

  • Create such a JavaScript inside your main page

<script type="text/javascript">    var timeOut = setInterval("ExtendSessionPopup();", 19 * 60 * 1000)

    function ExtendSessionPopup() {

indow.open('puppoPageUrl,'anycontent','width=455,height=435, status'); }</script>

In the code above we created a small counter to count the session time out time which is 20 min by default. Here I used 19 min because I’ll give the popup 1 min to count done.

  • Create a popup page that will tell the client that his session will expire within 1 min and ask him/her if he/she want to extend it. But 2 buttons on the popup, one to extend the session and the other to close session. On page load do this

    protected void Page_Load(object sender, EventArgs e)
        {
              if (!Page.IsPostBack)
            {
                StringBuilder st = new StringBuilder();
                st.Append("<script type=\"text/javascript\">");
                st.Append("setTimeout(\"ClosePopup();\", 60 * 1000);");
                st.Append("function ClosePopup()");
                    st.Append("{window.opener.parent.location = \"Login.aspx\";window.close();}");
               st.Append("</script>");

               Response.Write(st);
            }
        }

you may use a small counter to count down on the popup window for 60 sec.
Here the code above tells the popup to redirect Client to login page after 60 sec for popup rise.
Now; let us edit the click event of the Buttons;

Session Extend button

protected void lnkExtendSession_Click(object sender, EventArgs e)
  {

FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;
        FormsAuthentication.RenewTicketIfOld(fi.Ticket);
      Response.Write("<script>window.close();</script>");
        }

The code above extends session for another 20 min (if the user stays ideal all that time).

End Session Button

protected void lnkEndSession_Click(object sender, EventArgs e)
    {
        Response.Write("<script type=\"text/javascript\">window.opener.parent.location = \"Login.aspx\";window.close();</script>");
    }

The code above will close the session if client click end session link button.

In this way we can give our client to extend his/her session from the popup and if the client is a way from the pc the popup will end the session and redirect the main page to login page. By the way in this article I used session duration as 20 min, there for its hard coded.

Hope this Helps

WRN: Assembly binding logging turned off

 I started to received this error since yesterday and after i add an assembly reflection to retrieve the assembly version. Interesting thing that when the application is deployed to IIS it starts to work fine! but after some time i started to receive this error "WRN: Assembly binding logging turned off", my reflected assembly can not be found! WHAT!!!!! just before 10 sec it was working!!. I debugged my codes and find out that there is nothing wrong, after that i decided to clean all asp.net temp files on the iis server and restart iis again.But before i restart iis i recopied the "Lost DLL" ( which it was not lost) to my application bin folder and yuppie its working again. in my situation it usually takes about 30 min to lose the dll :D, 1 hour passed and nothing happened until now.

Update :  I used ildasm tool to find out what happens to my assembly after build. I found out that the assembly is built with a different  Culture!  normally on development no culture assigned to the assembly but after that when CCNET build the application a new culture is assigned!. that made other assemblies do not find the refrance of the wanted assembly!.

hope this helps

UCertify Prep-Kit (070-553 C#) Review
Few days before, I have been asked to review one of products of UCertify Company which is Prep-Kit (070-553 C#). But before writing my review I would like to explain WHY and HOW it's important to get certified.
 WHY;

If you are working in IT section you know very well that the knowledge you have can not be measured easily. You may spend years on the same position without any rise just because you are not able to show how much you know about your work and section. Therefore many companies like Microsoft have started certification programs which will help you to measure your knowledge and show the world that you have good experience in your subject. I believe that when you get certified, you will measure and show your knowledge, beside that you'll raise your life style and salary!

HOW;
This might be the difficult part of this process! If you entered any IT certification exams before (esp. Microsoft), you know very well that they do not ask you on a specific subject only! They will ask you whatever may be related with that subject. When you take such exams, you must be well-equipped to pass it; your daily knowledge may not be enough to make you pass the exam! Getting equipped with knowledge need a long time of study which you may not afford!

From my experience in this subject, I can say that you need some fast courses which will not take much time. There are many companies which offer such services. One of these companies is  UCertify and last week I had the chance to review and check one of those exams: Prep-Kit for (070-553 C#). I found that the package is very useful from these points of views;

  • The way of covering subjects: actually the package covers subjects according to Microsoft requirements in an easy way to make the reader remember what it is related to. ( I liked the flash cards: small hints but very useful)
  • Practice tests: this feature is very good, because it helps you to feel yourself in a real exam. Many practice tests that will help you measure whatever you studied about the subject.
  • Articles: yes articles! Some useful articles about the exam subjects.  
  • How to study:  shows you the right way to prepare yourself for the exam.
  • User-friendly interface
  • And many many more....

I did not think that studying for IT exams could come that much easy, but after I saw the package above, I believed that there is no way to FAIL! By the way, UCertify gives a money back guarantee if you fail to pass the exam! .And before i finish here is some screen shot of Prep-Kit (070-553 C#);

 

 

 you can visit UCertify here http://www.ucertify.com.

Notice: If you want to buy any of uCertify PrepKit product you may use this code for 10% discount as my blog reader. the code "YOUNIS".

 

Hope this helps.

 

More Posts « Previous page - Next page »