Blog Moved To http://weblogs.asp.net/meligy

Cross posting from the new blog @ http://weblogs.asp.net/meligy

  Home  |   Contact  |   Syndication    |   Login
  304 Posts | 3 Stories | 142 Comments | 110 Trackbacks

News

My main blog url now is: weblogs.asp.net/meligy

SponsoredTweets referral badge

Twitter












Tag Cloud


Article Categories

Archives

Post Categories

BlogRoll

About Me:

Friday, November 06, 2009 #

imageMicrosoft has released a final version of its book “Microsoft Application Architecture Guide, 2nd Edition”.

The book is described as:

This guide is available online here in the MSDN Library and will be available in the Fall of 2009 as a Microsoft Press book, ISBN# 9780735627109, that you can purchase through local and online booksellers.

The guide is intended to help developers and solution architects design and build effective, high quality applications using the Microsoft platform and the .NET Framework more quickly and with less risk; it provides guidance for using architecture principles, design principles, and patterns that are tried and trusted. The guidance is presented in sections that correspond to major architecture and design focus points. It is designed to be used as a reference resource or to be read from beginning to end.

The guide helps you to:

  • Understand the underlying architecture and design principles and patterns for developing successful solutions on the Microsoft platform and the .NET Framework.
  • Identify appropriate strategies and design patterns that will help you design your solution's layers, components, and services.
  • Identify and address the key engineering decision points for your solution.
  • Identify and address the key quality attributes and crosscutting concerns for your solution.
  • Create a candidate baseline architecture for your solution.
  • Choose the right technologies for your solution.
  • Identify patterns & practices solution assets and further guidance that will help you to implement your solution.

 

More information about the book in this blog post:

http://blogs.msdn.com/jmeier/archive/2009/11/05/now-available-patterns-practices-application-architecture-book.aspx

 

The book is:

Available for online reading at:

http://msdn.microsoft.com/en-us/library/dd673617.aspx

Available for free download (PDF Format) at:

http://www.codeplex.com/AppArchGuide/Release/ProjectReleases.aspx?ReleaseId=20586

Available in print (to buy hard copy) from Amazon at:

http://www.amazon.com/Microsoft%C2%AE-Application-Architecture-Patterns-Practices/dp/073562710X

 

Have fun reading,

 


Cross posted from weblogs.asp.net/meligy



Saturday, October 31, 2009 #

While I was planning to write about the same topic and have the draft ready in my Windows Live Writer waiting to complete, I found an interesting question in StackOVerflow and couldn’t just resist to answer:

ORM/Persistence layer AdviceORM

The question starts with:

I'm starting a new project and I'm looking around for either a very good ORM or for a non-SQL-based persistence layer.

Then follows up with a REALLY GOOD summary of what he believes about each known ORM he knew out of his own findings and search. I advice you to go read it.

However, all this investigation didn’t get him to a single choice answer. And I can’t blame him. This is one fo the questions that will remain for so long without a single answer, or maybe having the popular “It depends” answer.

 

I have had a LONG research in this topic as well. I have read for so long (and watched videos/casts) to make sure of the best usage of many ORMs and then used them sometimes in test projects sometimes in production, and I wanted to share my thoughts based on this. I posted a long answer there on the question in StackOverflow, and I want to share this answer with you here. I may also have a second part of this post based on my existing Windows Live Writer draft, but, based on my previous times, I think I won’t!

Let me first quote some parts from the question itself:

I also want to avoid at all cost having to mess with string-based queries so tools supporting LINQ or otherwise intuitive and possibly strongly typed queries get a big bonus.
Finally working with POCO objects is another thing I'd really want to do
Here's a list of products I've evaluated and why they don't fit, just so that I don't see any advice about using those:

  • NHibernate: crazy xml stuff, too much set up, high maintenance complexity and cost for model changes, session factories are messy and don't fit well with my needs
  • Castle ActiveRecord: NHibernate based, little documentation plus some problems related to NHibernate still apply. Furthermore, to get decent models it takes so many attributes that one is better off creating the schema manually, and the way relations are handled is a shame.
  • Linq To SQL: missing POCO objects and according to MS it won't improve much overtime (EF is what they're committed to)
  • Entity Framweork: although in v4 POCO objects are possible, they're still pretty hacky and force you into doing too much manual work to set things up. Besides, v4 is just a beta
  • LLBLGen Pro: good, especially with SelfServicing adapters, but not POCO. Also, the LINQ provider isn't perfect yet. Finally, deleting a group of objects is not possible via LINQ which results in mixing APIs (one of which is far from intuitive) and that I don't like.
  • SubSonic SimpleRepository: for a few minutes I thought I was dreaming. The deam came to an end as I figured out how the thing didn't handle relationships
  •  

    Here was my answer:

    If you can afford LLBLGen license, go for it.

    I seriously don't like LINQ query-syntax the more I work with it (although I LOVE the language features related to it like Extension Methods and Expression Tres).

    I loved at first like everybody else, but being uncertain whether [[ where employee.Name.StartsWith("John Smit") ]] in that XYZ LINQ provider will be done in SQL statement or in LINQ to Objects (after the SQL returns all results), and whether [[ user.Roles.Contains(role) ]] will at all work or not is a big step behind.

    LLBLGen can make deleting all items without loading them as easy as

    MyEntityCollection.DeleteAll( new MyEntity {Condition = value} );

    This is pretty simple and I like it. You get lazy loading and you set eager/deep loading by default and/or per query using Prefetch API. You can compose and construct dynamically (and easily) any filter/sort/loading at infinite levels. It's very nice.

    There are only two problems about LLBLGen: first, it's price not all companies would love to pay especially given the hype Microsoft alternatives have. Second, the naming convention although standard in RDBMS theories) like PredicateFactory instead of "where" or "filter" and Prefetch instead of deep loading and even SortExpression instead of orderby, those all are a little scary to a developer working with it for the first times, but soon you learn to love them, given the power and ease they give. There are talks about POCO support in LLBLGen 3.0. I cannot tell about it because I don't know.

    Now given I no longer work in a company that uses LLBLGen, the company uses LINQ to SQL mainly because it's "proven" in so many projects without big failures (unlike EF 1, which is lacking even LINQ features in LINQ to SQL and has very bad performance and can be quite limiting in advanced mapping - which it should have been best for!). This website StackOVerflow itself runs on top of it!!! I used both in this company (EF after L2S) and hated both. The decision for new projects remained LINQ to SQL, and doing all we can to overcome it's limitations. You can work around it to do SEMI-POCO (you still need to use some L2S related types when it comes to associations).

    I also do some small projects at home. Since I nolonger have LLBLGen license, I decided to learn NHibernate and use it along with Fluent NHibernate and LINQ To NHibernate. I have learned through this that NHibernate is VERY strong. It changed how I work by some features like updating DB schema automatically (I never touched the DB almost when using it). LINQ provider (in NHibernate Contrib project) is quite lacking sometimes but there is the unreleased source code of NHibernate itself contains a better LINQ provider (haven't tried it yet). The "Session" in NHibernate has problems when you are doing web development similar to those related to DataContext in L2S or ObjectContext in EF (LLBLGen doesn't suffer from those thanks to self tracking entities).

    The biggest problems I had with NHibernate though was ability to find information. Too many pieces that should be put together in certain way and not much guidance can include advanced information for both mapping and querying. If not I had a friend (Tuna Toksoz , @tehlike on twitter) who happended to be a committer in NHibernate project source code, I'd really be in serious trouble.

    The moral I learned was: If you want something that just works and a bit basic use Linq To Sql or SubSonic, if you want something in the middle and your production environment can afford BETA .NET version (given golive exists) use Entity Framework 4.0, if you want something very powerful and can afford the hard learning process go to NHibernate, AND, BEST OF ALL, if you can afford LLBLGen, USE IT.

    Let me know your own thoughts on the topic.


    Cross posted from weblogs.asp.net/meligy



    Wednesday, October 14, 2009 #

    Image007000 - Copy Today (technically yesterday, since it’s 3:26 AM already while I’m starting this), Mr. Adam Mohamed Meligy finally arrived home, after staying 9.5 days in nursery. This –dear audience- given Mr. Adam arrived to our world only in October 5, 2009, a date that the entire world will (sooner or later) always remember!

    Mr. Adam is now taking a personal cover, pretending to be a normal baby, while he is pretty professional, he cannot sometimes hide his special natures, being relatively quiet compared to normal babies, and highly responsive to touches and (believe it or not) spoken notes/requests.

    These are things that the world will remember once Mr. Adam finishes his first big achievement in the field he will take up for living (God Willing). Some other small details matter more to the family, both his grandparents –for example- note him as their first grandchild. I –personally- recognize him as my extra chance in life! If I fail to manage to be another Anders Hejlsberg/Martin Fowler, Scott Guthrie/Brad Abrams, or Scott Hanselman/Rob Conery/Phil Haack (still trying), Mr. Adam has a bigger chance; else wise, he’ll be digging his road as a notable figure in some different field (God Willing).

    I feel that I was blessed with not just two more legs and hands, one more tongue and a couple of stronger eyes, extra more years to live, but also with an extra brain and superpowers. You can always upgrade your thinking methodologies, even reinvent the way you think completely, but you are always limited to your physical brain constraints that -although can be always stretched more and more- have their limits. Now I have an extra brain that can do pair thinking with me and reinvent the way things happen by the experiences he will be having on his own (God Willing).

    So, this is to log that Mr. Adam (temporarily until he decides to replace that with “Eng.”, “Dr.”, and/or “Prof.”) has just finished implementing phase zero,  coming to existence!

    Few More Facts About Mr. Adam’s Arrival

    • The exact time of arrival to world is October 5, 2009, 10:30 AM Abu Dhabi Time, that’s 8:30 AM Cairo Local Time (CLT), 6:30 GMT.
    • Although born in Kornesh Hospital, Abu Dhabi, UAE, Mr. Adam holds the Egyptian nationality, just like his parents. He also inherits the Islam religion, which he will be (God Willing) discussed about as soon as starts making conversations, so that he practices it for the sake of belief, not inheritance!
    • Mr. Adam reached our world after hiding in a secret cafe for slightly less than 35 weeks, reaching our world at the weight of 2.25 Kg.
    • Mr. Adam has his email, Facebook and twitter accounts created on the day of arrival and moderated by parents. Soon (God Willing) he will be running those himself, and creating his own LinkedIn account on his own once he finishes his first school and starts a professional expert career simultaneously.
    • Mr. Adam has come with the message to make the world a a better place to live for humans, not to dominate the entire world ;-).
    • Since arrival, the protocol requires using the prefix “Mr.” when mentioning Mr. Adam’s name in conversations. Only tweets/categories, etc… are allowed exceptions due to technical/official nature. This prefix is temporary as per the relevant note above.

    On behalf of the family, I congratulate the world on having Mr. Adam with us. I’ll be following up with his significant news until he starts blogging (hopefully soon, God Willing).

     


    Cross posted from weblogs.asp.net/meligy



    Monday, October 12, 2009 #

    Few minutes ago a colleague and friend asked me about some problem he was having with ASP.NET themes. He was using a theme and including a CSS file in it, the CSS file was linked in the generated HTML but clearly it was not applied. Putting the URL of the CSS file in the browser address bar would return an empty result in Firefox, and a crappy DOCTYPE,HTML,HEAD,BODY tags in IE. The same website works normally with other developers running Windows XP or Windows 7.

    Going further to the problem, I tried checking the file access, giving extra permissions and so on, checking web.config and global.asax for any ASP.NET HTTP Handler or HTTP Module that might be handling all requests. None of this existed. Then, I switched to IIS, trying to change the website from custom Application Pool to default integrated pipeline one to default classic (IIS 6 like) one, but no use.

    Now I started thinking, images in the website didn’t show also! I didn’t know whether this was a DB/code issue or related to not showing the CSS, well, maybe something is wrong with IIS installation, right? Well, exactly!!!

     

    Here’s what the problem was:
    Capture

    Having installed IIS 7.5 for the first time, the guy thought he just needed to choose ASP.NET features in WWW, he never realized he has to have “Static Content” checked as well. It was really funny when discovered!

    Wouldn’t you agree?


    Cross posted from weblogs.asp.net/meligy



    Friday, October 09, 2009 #

    Few minutes ago, I saw @mShady, my dear friend (Real life friend, not just on twitter) tweeting:

    RT @ASGEgypt: RT @scrum_coach: Should the team be allowed to drop the retrospective? http://bit.ly/bkOgv  #scrum #agile #lean #xp #kanban

    I checked the post and found the options are:

      1. Yes, It’s their process why not?
      2. No, explain to them and work through why the retrospective is so important.
      3. Maybe, if they are no longer a team then why continue with Scrum?
      4. Only do retrospectives once a quarter and build up a good list of things to change.
      5. Yes, the process will take care of itself we don’t need to watch it that closely. After all it’s common sense!

    Interesting question! Not the most important topic in Scrum but like the way Agile works in general, if you play with it wrong, it is an indicator you have something else wrong as well before that, so, it gives you an alert.

    See the rest of the blog post. I find the options my main interest, and wanted to share with you here how I answered this question:

    I’d say have a really short one if the team members have been working together for sometime it can go really quick (an hour or so) just before the planning for the next sprint. We used to do so in a previous company and it was pretty successful.
    It was like it’s one meeting divided into 2, one hour or so for previous sprint retrospective, and probably rest of the day (or most of it) for the planning for next sprint.

    If they cannot have a quick meeting like this quickly then something else is wrong and they need to work on their team skills. Time boxing would be one option: The meeting will be needed “more” if they do not communicate well, Time box it to 2 hours or so and make it clear and strict since beginning, and consider investigating (assuming you are scrum master or team leader) what other issues the team may be suffering from.

    However, I find myself going with (1) and (5) at the same time, “it’s their process” and “After all it’s common sense!”.

    What do you think??

     


    Cross posted from weblogs.asp.net/meligy



    Friday, January 25, 2008 #

    Note:
    This is ported from my old weblog. Originally published December 19, 2005

    This is a well commented example for a GridView with implementation of RowDataBound and DataBound events. I also demonstrate in it some of the important properties of GridView, like the slight diffrences when dealing with Grid Paging, Rows, Cells, and Columns. I prefered to heavily comment the code than to write separate paragraphs describing it as I do believe that the code is what gets the idea in a direct way.

    The example is a simple page that uses SqlDataSource to connect to a SQL Server 2005 Express database and show the results on a GridView with paging capapility. Many parts of the code don't show the best practices for their situation and those are only included for demonstration purpose as they are not the main focus of the example.

    I'll start with the code behind of the page as it's the most important part:

    /******************************************************************
     * The sample is provided AS IS without any warranty
     * All rights reserved (C) 2005, Mohamed A. Meligy
     * http://www.GeeksWithBlogs.NET/Mohamed
     * All rights reserved (C) 2005, Mohamed A. Meligy
     * http://weblogs.asp.net/meligy
     * Distribution of this code without this legal note is prohibited.
     ******************************************************************/
     
    //Default "using" set of a new System.Web.UI.Page Visual Studio 2005 template:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
     
    /// <summary>
    /// To test the GridView behavior in action,
    ///     you need to have SQL Server Express installed (comes by default with VS2005),
    ///     and Northwind database attached to it
    ///     (attaches by default when you select "Quickstart Tutorials"
    ///     from the .NET Framework 2.0 SDK Programs menu, and choose to install them).
    /// Alternatively, change the ConnectionString property of the SqlDataSource
    ///     to point to another installed instance
    ///     of SqlServer 2000 or SqlServer 2005 that has Northwind database attached.
    /// </summary>
    public partial class GridViewSampler1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Limiting redundancy of useless execution.
     
            //You do no need to check IsCallback if you
            //  don't have controls with Callback Enabled.
            if (!IsPostBack & !IsCallback)
            {
                //This makes performing paging and sorting uses AJAX.
                GridView1.EnableSortingAndPagingCallbacks = true;
     
     
                //Small number so that I can see many oages out of
                //  9 rows only (Yhe total Rows Count of Northwind's Employees DataTable).
                //Also selected it in a way that last Page Rows Count will be
                //  different than other pages.
                GridView1.PageSize = 2;
     
     
                if (!IsPostBack)   //Just to prove the AJAX thing.
                {
                    PostBackStatus.Text = "Not PostBack";
                }
                else   //Never happens, as I don't require a PostBack.
                {
                    PostBackStatus.Text = "Page Is PostBack";
                }
            }
        }
     
     
        /// <summary>
        /// Executes when the databinding is complete
        /// </summary>
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
     
            //I'll use it to show which set of Rows I'm showing in the page.
            GridView1.ShowFooter = true;
            //Similar to: GridView1.FooterRow.Visible = true
     
     
            //Stretching the first cell to fill the whole FooterRow:
     
            //Removing all non needed cells,
            //  from the end to start
            //  (so that the Cells collection is not recreated with every Removal).
            for (int cellNum = GridView1.Columns.Count - 1; cellNum > 0; cellNum--)
            {
                GridView1.FooterRow.Cells.RemoveAt(cellNum);
            }
     
            GridView1.FooterRow.Cells[0].ColumnSpan = GridView1.Columns.Count;
            GridView1.FooterRow.Cells[0].HorizontalAlign = HorizontalAlign.Center;
     
     
            int startIndex = GridView1.PageIndex != GridView1.PageCount - 1 ?
     
            //Not in last page.
            GridView1.PageSize * GridView1.PageIndex
     
            //GridView1 Rows Count is Count of the Rows of the current page, so,
                //  unless Paging is Disabled, this is not total Rows Count.
                //gridViewTotalCount is declared and assigned just after this method.
            : gridViewTotalCount - GridView1.PageSize + GridView1.Rows.Count;
     
     
            GridView1.FooterRow.Cells[0].Text =
                string.Format
                    ("Showing Employees {0} to {1} of {2}",
                    startIndex + 1,
                    startIndex + GridView1.Rows.Count, gridViewTotalCount);
        }
     
        TableCell myCell = null;
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //I'll add that to every Row bound in the GridView.
            myCell = new TableCell();
            //Note that for the header, footer, and separator rows, DataItemIndex is -1
            myCell.Text = e.Row.DataItemIndex.ToString();
     
     
            //Note that when you add the cell,
            //  this does NOT increase the GridView Columns Count.
            e.Row.Cells.Add(myCell);
     
     
            //The past lines will affect also HeaderRow, FooterRow, and even Pager,
            // you'll see when you run that this is not a desired behavior.
     
     
            //You can limit your code on condition. This is the recommended way.
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Do your UI logic now for data binding,
                //  much similar to DataGrid ItemDataBound.
     
     
                //Example: changing color of text
                //  for normal and alternative rows ONLY by code.
                if (e.Row.RowIndex % 2 == 0)
                {
                    e.Row.Style["color"] = "#0000ff";
                }
                else
                {
                    e.Row.Style["color"] = "#00bb00";
                }
     
                //This is the EmployeeID Cell
                e.Row.Cells[0].Text =
                    "I'm alternative employee with code: " + e.Row.Cells[0].Text;
     
     
                //Another sample change making use of the DataItem:
     
                // This is specific to our case where the GridView is bound to
                //  first DataTable in the DataSet returnd by the EmployeesSqlSource.
                // This is when SqlDataSource DataSourceMode = DataSet (Default)
                DataRowView rowView = (DataRowView)e.Row.DataItem;
     
                e.Row.Cells[GridView1.Columns.Count - 1].Text =
                    int.Parse(rowView["Extension"] as string).ToString("###-##");
            }
        }
     
        int gridViewTotalCount;
     
        protected void EmployeesSqlSource_Selected
            (object sender, SqlDataSourceStatusEventArgs e)
        {
            //GridView has no way of telling total Rows Count when paging is enabled.
            gridViewTotalCount = e.AffectedRows;
        }
    }

     

    Now to the page XHTML source:

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="GridViewSampler1.aspx.cs" 
        Inherits="GridViewSampler1"
        %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml">
     
    <head id="PageHeader" runat="server">
        <title>GridView Sample</title>
    </head>
    <body>
     
        <form id="form1" runat="server">
            <div>
            Postback Status:
                <asp:Label ID="PostBackStatus" runat="server"></asp:Label>
     
                <asp:GridView ID="GridView1" runat="server" 
                    AutoGenerateColumns="False" AllowPaging="True"
                    DataSourceID="EmployeesSqlSource" DataKeyNames="EmployeeID"
                    OnDataBound="GridView1_DataBound"
                    OnRowDataBound="GridView1_RowDataBound">
                    <Columns>
                        <asp:BoundField DataField="EmployeeID"
                            HeaderText="EmployeeID" InsertVisible="False"
                            ReadOnly="True" SortExpression="EmployeeID" />
                        <asp:BoundField DataField="LastName" 
                            HeaderText="LastName" SortExpression="LastName" />
                        <asp:BoundField DataField="FirstName" 
                            HeaderText="FirstName" SortExpression="FirstName" />
                        <asp:BoundField DataField="Title" 
                            HeaderText="Title" SortExpression="Title" />
                        <asp:BoundField DataField="BirthDate" 
                            HeaderText="BirthDate" SortExpression="BirthDate" />
                        <asp:BoundField DataField="PostalCode" 
                            HeaderText="PostalCode" SortExpression="PostalCode" />
                        <asp:BoundField DataField="Extension" 
                            HeaderText="Extension" SortExpression="Extension" />
                    </Columns>
     
                    <EmptyDataTemplate>
                        <div style="text-align: center">
                            No Data Available.
                        </div>
                    </EmptyDataTemplate>
     
                </asp:GridView>
                <asp:SqlDataSource ID="EmployeesSqlSource" runat="server"
                    ConnectionString=
    "Data Source=MELIGY\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"
                    ProviderName="System.Data.SqlClient"
                    SelectCommand=
    "SELECT [EmployeeID], [LastName], [FirstName], [Title], [BirthDate], [PostalCode], [Extension] FROM [Employees]"
                    OnSelected="EmployeesSqlSource_Selected"></asp:SqlDataSource>
     
            </div>
        </form>
    </body>
    </html>

     

    Samples of the output of the code:




    Hope that you like it.

     


    Cross posted from weblogs.asp.net/meligy



    Sunday, September 27, 2009 #

    Yesterday I changed my twitter username from @Mohamed_Meligy to just @Meligy.

     

    Why?

    I have been thinking about this step for a long time, as my tweets are relatively long, and when I want to to allow people to re-tweet. With my old username, I used to have to write at max 120 characters per tweet to allow re-tweet (leaving 20 characters out of the real 140 characters limit to “RT @Mohamed_Meligy: ”). With my new twitter username I can use up to 128 characters (leaving 12 for “RT @Meligy: ”). I know I ‘m a person who can make nice use of those 8 extra characters, but is this worth doing? For sometime I thought: No.

     

    My old username has some nice features. First, it includes my full name, so, that’s nice for people who don’t know me very well. Second, it has been around for over a year and over ~2390 tweets! That’s something!! People got used to using this twitter username when replying to me (mentioning me) and I did my best to put it everywhere in my Google and Facebook profile and blog and everywhere, and also used it with many twitter applications that require entering username/password.

     

    Few days ago, one of my friends brought up the topic and encouraged me to do the change. I tweeted asking my friends whether they would promote the change, and encouraged me even more, so, I switched twitter username to @Meligy.

     

    How

    Some friends may wonder, how did I change my twitter username and still kept all my previous followers and reserved the old username also still on twitter. What part of it is a feature of twitter, and what part is something I did?

    So, here is the story:

    1. I created a new twitter account with username @Meligy, and same password.
    2. I changed the @Meligy username to @Mohamed_Meligy2.
    3. In another browser I went to my old @Mohamed_Meligy account, changed username to @Meligy. Now I have @Meligy and @Mohamed_Meligy2.
      I noticed When I go to twitter replies in twitter website, it shows all replies that came to me, even those including @Mohamed_Meligy. This is good.
      The bad part is that when I click on @Mohamed_Meligy link in those replies/mentions, it goes to @Mohamed_Meligy not @Meligy.
    4. I changed the new account @Mohamed_Meligy2 back to @Mohamed_Meligy.
    5. I deleted the old @Mohamed_Meligy account from tweetdeck, and added both @Mohamed_Meligy and @Meligy (as default).
      I couldn’t just add the @Meligy account even with same password in both – I had to delete the old one.
    6. I used tweetdeck to tweet from both accounts “Changed twitter username from @Mohamed_Meligy to @Meligy. Followers needn't change anything except using @Meligy in future replies/mentions”.
    7. I started trying to remember all the websites and applications I logged with the old twitter username and change it to @Meligy.
      Having the same password on the other @Mohamed_Meligy account, I’ll be monitoring it for a while in case I forget some application or so.

    Note that any link to previous tweets (in the format: twitter.com/{username}/status/{tweetID}) before changing username will still be broken.

     

    Follow Me!

    If you already followed me back with the old username, you should still be able to receive my updates.

    If not, follow me on twitter via @Meligy.

     


    Cross posted from weblogs.asp.net/meligy



    Wednesday, September 23, 2009 #

    Some of you who use Firefox (FF) might know about a Firefox plug-in called “IE Tab” which allows you to view a page/tab using the Internet Explorer (IE) rendering engine INSIDE Firefox (so, if some page displays better in IE, you don’t have to leave FF and go open an IE window).

     

    Now, Google is doing something similar, but the other way around!

    Google has recently released “Google Chrome Frame”, a plug-in for IE that allows you to view a page/tab using the Google Browser “Google Chrome” rendering engine INSIDE Internet Explorer.

     

    This is interesting in two ways, first, it may decrease IE problems with crashes and such, and second, that Google maybe later will drop support for IE rendering engine in its products (like Google Mail, Reader, Video, Youtube, etc..), so that you have to use Firefox, Safari or Google Chrome (or Google chrome Frame) to use these applications.

    Interesting enough, this is the case already with one of Google’s new products, called Google Wave!

    They say the reason is supporting IE6!! They did much effort to get it to work with it but it didn’t. Of course the Chrome Frame plug-in is supported under IE 6, so, is supposedly solves their problem!

     

    Google Chrome Frame Homepage:

    http://www.google.com/chromeframe

    Related News:

    Google’s Plan to Kill Internet Explorer? Google Wave

    Google Has A Solution For Internet Explorer: Turn It Into Chrome

     

    Firefox IE Tab Extension:

    http://ietab.mozdev.org/

     


    Cross posted from weblogs.asp.net/meligy



    Wednesday, September 09, 2009 #

    This was originally an email I sent to .NET team in my company, then decided to share as a blog post.

    The problem:

    • Let’s say you have a complex application, and this application (or part of it) runs very slowly. No bug s in results, no errors or exceptions, but it just so slow! Now you want to know which part of your code is the reason, which method(s) you need to go and modify., which methods take so long to execute or consume so much memory/CPU. How would you know that?
    • Let’s say you want to improve the performance of your application in general (say add caching or such), so, you want to identify which parts of your code deserve your attention and will really make difference (so that you don’t waste your time on optimizing something that will not have big effect in performance), for  example, you might want to identify which methods are called more than others from different parts of your code. How would you do that?

    How to solve it, or, what is a profiler (v. short):

    It is an application that you can run along with your own program. It’ll track all method calls and how any method call other method and most importantly how long each method call will take, and how it consumes resources.

     

    There are many .NET profilers out there.

     

    So, what about EQATEC:

    Quoting from homepage:

    Spot slow code

    Are you a .NET developer? Would you like your application to run faster? Then use our free profiler to spot you app's slow code.

    Point and go

    No source code changes are needed. Just point the profiler to your app, run the modified code, and get a visual report.

    Speedup any .NET app

    As the only code profiler in the world, our profiler can even handle Compact Framework applications.

    Language

    Version

    Platform

    clip_image001 C#

    clip_image001[1] VB.NET

    clip_image001[2] Managed C++

    clip_image001[3] F#

    clip_image002 C or C++

    clip_image002[1] Java

    clip_image001[4] .NET 3.5

    clip_image001[5] .NET 3.0

    clip_image001[6] .NET 2.0

    clip_image001[7] .NET CF 3.5

    clip_image001[8] .NET CF 2.0

    clip_image002[2] .NET 1.1

    clip_image001[9] WinXP, Vista

    clip_image001[10] Windows Mobile

    clip_image001[11] Windows CE

    clip_image001[12] XP embedded

    clip_image001[13] PocketPC, PDA

    clip_image002[3] Linux

    To use it with ASP.NET application, all you need to is:

    • to put the path of the “bin” folder of your website as “App Path” (no need for source code or debug files), then it shows a list of all assemblies in it so you choose the DLL(s) you want to profile, and click “Build” at the right corner of the screen:
      EQUATEC
    • Click “Open output folder” on the bottom left corner, copy the DLLs from there to your website “bin” folder
      • Alternatively you can click “App Options” and set the output folder to “$(AppDir)” so that the generated files replace the old one
      • You need to repeat these previous steps if you build the website again using Visual Studio
    • run the website and start using it for a while
    • go to EQUATEC “Run” tab and click “Take Snapshot
    • go to the “View” tab and start reading the results

    It might be important also to spot the limitations:

    Known limitations

    This is a list of known limitations and problems in version 2.0.

    • Blocking methods, such as Read(), will be counted as the total time, including the time the thread spends being descheduled and waiting for the call to complete. For now, you will have to recognize and judge situations like this manually.
    • No debug information is available for the profiled assemblies. It means that you cannot debug the profiled versions - but you would probably not like to do that, anyway.
    • No Visual Studio integration yet. We are looking into providing an add-in that will make it even easier to enable profiling your solution's assembly files.
    • No full method signature is displayed yet. So if you have several overloaded methods by the same name, or use generic methods, you cannot easily distinguish them as their signature (the method's parameter list) is not displayed anywhere.
    • Only defined methods are currently profiled, not referenced ones. So all the methods that your application itself defines will be profiled, but not System.* etc.

    I hope this is useful for some of you as it was a real saver at times to me. Thank you very much!


    Cross posted from weblogs.asp.net/meligy



    Saturday, August 29, 2009 #

    Emad Ashi (@splashup on twitter) interviewed me in the 5th episode of his first Arabic podcast series DotNetArabi to talk about Object Relational Mapping in .NET in Arabic.
    Podcast Page: Mohamed Meligy Talking about ORMs (MP3 Direct Download)
    السلام عليكم
     
    أصدقائي العرب ممن يتابعون هذه المدونة.. يسعدني أن أعلن عن أول حديث لي على الانترنت - و كذلك أول حديث لي على الانترنت بالعربية، عن الـ Object Relational Mappers – ORMs
    شكرا جزيلا لـ “عماد العشي” (splashup@ على تويتر) على استضافته لي في موقع “دوت نت عربي DotNetArabi”، و هو موقع عربي يتضمن لقاءات صوتية مع العديد من المطورين في مجال الدوت نت، تماما على غرار DotNetRocks ، HanselMinutes و سواها، و هو في حد ذاته فخر لي أن أكون ضيفا للحلقة الخامسة في برنامج كهذا، خاصة عندما يكون ضيف أولى الحلقات هو عمر قعدان (omarq@ على تويتر).
     

    الحلقة 5: محمد مليجي يتكلم عن الـ ORM (Object Relational Mapping)

    وصف الحلقة من دوت نت عربي:
    محمد مليجي تكلم عن الـ ORM (Object Relational Mapping) و هي برامج مساعدة تستطيع من خلالها نقل المعلومات و تحويلها من طبيعة قاعدة البيانات إلى طبيعة البرامج المبنية بأسلوب الـ Object Oriented. حلقة غنية بالتفاصيل و المعلومات القيمة جدا.
    Listen to the episode now (in Arabic):
    الشكر خاص جدا لعماد الذي أتى لي في وقت قل فيه اتصالي بمجتمع المطورين في مصر، و اقتصر نشاطي في مجتمع المطورين بصفة عامة على بعض المحاضرات خارج نطاق الالتزامات الرسمية في شركتي الحالية، و مشاركات قليلة في المنتديات و المجموعات البريدية خاصة ALT.NET و مدونتي هذه، (و هو ما يقل مع الوقت) و متابعة أخبار المجتمعات العربية على تويتر كـ Mohamed_Meligy@ و على Google Reader.
     

    Related Links:


    Cross posted from weblogs.asp.net/meligy



    Wednesday, August 26, 2009 #

    Here’s another email from the internal mailing list of Injazat .NET Ninjas (Ninjazat, AKA  as we call ourselves), that I’m sharing with blog readers as well.

    Just a place holder, until I move one of my 18 (just discovered the number now – terrifying!) drafts in my Windows Live Writer into a published post, or delete them all!

    Subject: [Learning] Some very interesting videos

    Some videos from NDC 2009 event (Norwegian Developers Conference 2009) - about software design and related issues:

    · NDC Video – Robert Martin – S.O.L.I.D Principles of OO class design

    · NDC Video – Robert Martin – Craftsmanship and Ethics

    · NDC Video – Robert Martin – Component Principles

    · NDC Video – Robert Martin – Clean Code III – Functions

    · NDC Video – Michael Feathers – Working Effectively with Legacy Code

    · NDC Video – Jeremy D. Miller – Convention Over Configuration

    · NDC Video – Michael Feathers – Seven Blind Alleys in Software Design

    · NDC Video – Ted Neward – WCF Patterns

    · NDC Video: Michael Feathers – Design Sense

    For the complete list of videos from this event check videos from:

    · Day 1

    · Day 2

    · Day 3

    My favorite topics are (recommendations):

    · NDC Video – Robert Martin – S.O.L.I.D Principles of OO class design

    · NDC Video – Michael Feathers – Working Effectively with Legacy Code

    Of course the other topics are interesting as well.

    Enjoy!

     


    Cross posted from weblogs.asp.net/meligy



    Tuesday, July 28, 2009 #

    Simplified (Inaccurate) Background About OpenID

    Some websites allow you instead of registering and logging-in (meaning re-entering the same information you entered before in so many other sites), to enter what is called Open ID URL, which is a URL given by a another website that you already logged in and has your information (called OpenID provider).

    Once you enter the URL and continue, you get redirected to the OpenID provider confirmation page whether you want to be able to login to the new website using the same login,which gets redirected back to the new website but this time as logged in user.

    If your OpenID provider is a popular provider, like Yahoo or Google or so, some websites will give you a shortcut to writing the URL at login by just selecting the provider from a predefined list of providers in the login page. If your provider is not in the list, or the website does not offer any shortcut list at all, you should be able to know your OpenID URL to enter same as you know your User ID or so.

    Google and OpenID

    The first relation between Google and OpenID started with Blogger. It first accepted logging in to write comments on Blogger using OpenID, and had Blogger itself become an OpenID provider (you enter your blog URL as your OpenID URL). Why Google did this to Blogger accounts only not all Google Accounts (used for Gmail, etc..)? I don’t know. I think this is because Blogger accounts were not yet merged with Google Accounts at this time.

    Later Google as a whole became an OpenID provider for all Google Accounts (AKA Gmail Logins), with different OpenID URL. This means if you have Blogger account, you have two different OpenID URLs offered by Google each maps to DIFFERENT LOGIN. Again, maybe because of backward compatibility or whatsoever.

    If your real blog is not on blogger, and you use your Gmail account primarily, you may want to use the Google Accounts Open ID URL as your OpenID login to all websites that support logging in with OpenID, but, unlike the easiness of remembering a Blogger blog URL, the Google Accounts Open ID URL is a bit ugly and you might not know about it.

    Well, here is the Google Accounts Open ID URL (yeah, the entire blog post is about this single line):

    https://www.google.com/accounts/o8/id

    Note: You do NOT replace the part "ID" with your Google Account user-name/email. The OpenID URL is "AS IS" above whatever the Google Account ID is..

     

    Have fun!

     


    Cross posted from weblogs.asp.net/meligy



    Thursday, July 23, 2009 #

    Yet another internal .NET Team email in my current company, Injazat Data Systems, that I sent yesterday, and am sharing with you as well.

    jQuery:

    · Simplify calling ASP.NET AJAX services from jQuery

    · Use jQuery and ASP.NET AJAX to build a client side Repeater

    · Reordering invoice lines using jqGrid and TableDND extension

    · LA.NET jQuery Posts/Articles

    Agile

    · Implementing Scrum

    ASP.NET

    · Web Development With ASP.NET Learning Material (Course - Source: MSDN Ramp up Learning Program)

    · ASP.NET Articles on CodeGain (Many Articles)

    WCF

    · Posting Twitter Tweets from ASP.NET using the WCF REST Starter Kit Preview 2

    WF

    · Migration Guidance for the WF Developer

    o Part 1

    o Part 2

    Office Open XML

    · Embedding Any File Type, Like PDF, in an Open XML File

    Fun

    · YoutTube: Windows Live Messenger 10th Anniversary Celebration Video

    · 99 Amazing Widescreen Wallpapers To Spice Up Your Desktop

    As usual, those and others are all originally shared on my Google Reader Shared Items:

    http://www.google.com/reader/shared/08221036579558509505

    Regards,

    Happy weekend,

     


    Cross posted from weblogs.asp.net/meligy



    Sunday, July 19, 2009 #

    The reason I’m writing this is because every other day I see someone twitter statuses like: “TweetDeck does not support Arabic”, “Cannot view Arabic tweets in TweetDeck” or similar notes, so that I can just guide people to this post rather than write the same tweet reply!

    TweetDeck supports Arabic and other complex script languages. I guess any Unicode language. It’s just not enabled by default.

    A picture is worth 210 words. Here is what you need to enable it:

    tweetdeck

     

    Yet, one thing I don’t understand is: why it’s not the default in TweetDeck ???

     

    N.B.

    If you wonder why I care so much; this is because I believe TweetDeck is the best twitter client ever.

     


    Cross posted from weblogs.asp.net/meligy



    Tuesday, July 14, 2009 #

    Allow me to quote here some emails I sent to the the Dot NET developers group in my company, Injazat, or, as we call ourselves, Ninjazat. I thought it’ll be useful to share some with you as well.

    ·         ASP.NET MVC - 20 Hours of FREE Video Tutorials

    ·         LINQ FAQ

    o   LINQ FAQ for Newbie’s

    o   LINQ FAQ Part 2

    ·         How we handle application configuration

    ·         ScottGu ASPNETMVC Session Video Available Now (Part 1/2 & 2/2)

    ·         Web Validation: Best Practices and Tutorials

    ·         Building a Single Sign On Provider Using ASPNET and WCF

    o   Part 1

    o   Part 2

    o   Part 3

    ·         NxtGenUG Cambridge: Creating extendable applications using MEF slides and code

    ·         Dynamic Languages and .NET - Developer Day Scotland slides and code samples

    ·         patterns & practices: Data Access Guidance (VS 2010 Stuff)

    ·         Refactoring challenge

    o   Part 1 - Examination

    o   Part 2 – Preparation

    ·         LINQ is not LINQ To SQL

    ·         Visual Studio Programmer Themes Gallery

    ·         Connecting to Mailbox on Gmail and Fetching List of Emails using POP3 and ASP.NET

    ·         Optimize your page for UpdatePanel

    ·         CMS in the .NET World

    ·         Getting jQuery Goodness into ASP.NET AJAX - Take II

    ·         What to do when SELECT query is Running Slowly?

     

    As usual most of them coming from my Google Reader Shared Items http://www.google.com/reader/shared/08221036579558509505

    Previous Email:

    ASP.NET AJAX Control Toolkit ModalPopupExtender Control in Action

    http://www.codeproject.com/KB/ajax/ASPModalInAction.aspx

    Previous Email:

    [jQuery] Animate Image Filling Up Using jQuery

    Make Sure To See The Demo First:

    http://buildinternet.com/live/imagefill/

    See the article then:

    http://buildinternet.com/2009/06/animate-image-filling-up-using-jquery/

     

    Have Fun!

     


    Cross posted from weblogs.asp.net/meligy



    Monday, June 29, 2009 #

    I was going to put this on twitter but it’s a bit longer to tweet.

    Last week I shared some videos on Google Reader and twitter from Microsoft’s MSDN Chopsticks video website. If you don’t know it, it’s a VERY nice videos website with much content on very interesting topics and very recent products as well as different experience levels of content.

    http://www.microsoft.com/belux/msdn/nl/chopsticks/

    Today, some other friends on twitter noticed the Chopsticks site and were wondering why it doesn’t allow downloading the videos (you can only view them online).

    Well, there is a work around to download the videos though:

    1. Go to the video web page (you need to have Silverlight installed, and a .NET passport login, like Hotmail account).
      I’m using a sample here: “Using ASP.NET MVC Model Binder” http://www.microsoft.com/belux/msdn/nl/chopsticks/default.aspx?id=798
      image
    2. [Update: Skip this is step. Go to Step 3>1]
      If you hover on the video player, you find some icons/buttons that were not showing.
      1. Click the 2nd icon/button from the left, which has the tip “EMBDE”.
         image
      2. When you click it, it shows like this:
        image
      3. Extract the URL in the text following “Embed this video”
        In this example the text is:
        <iframe src="http://www.microsoft.com/belux/msdn/nl/chopsticks/player.aspx?id=798&e=1" frameborder="0" width="493px" height="385px" scrolling="no" marginheight="0" marginwidth="0" ></iframe>
        so the URL is: http://www.microsoft.com/belux/msdn/nl/chopsticks/player.aspx?id=798&e=1
    3. Go to the URL, when the page displays
      1. [Update: the next steps should work in the video page itself not having to get EMBED URL (skip previous STEP 2).
        If the video URL is not found yet, try STEP 2]

        show the source code of that page.
        In Firefox you do this by right clicking near the end of the page and choose “View Page Source” (if you right click up, it’ll show “Silverlight” instead)
        image
      2. In the source look for a line that starts with:
        <script type='text/javascript'>Silverlight.InstallAndCreateSilverlight("1.0",document.getElementById("
        In this example the code is: (found near the end of the </form> tag)
        <script type='text/javascript'>Silverlight.InstallAndCreateSilverlight("1.0",document.getElementById("SilverlightInstallPromptHost"),createPlayerSilverlight("http://mediadl.microsoft.com/MediaDL/WWW/B/belux/msdn/chopsticks/community/maartenballiauw-mvc-model-binder.wmv", "http://www.microsoft.com/belux/msdn/nl/chopsticks/default.aspx?id=798", true, true, 1, 538953 ));</script>
        This way you can extract the video URL as the value in between createPlayerSilverlight(" and it’s closing "), you should find (based on this example) the URL: http://mediadl.microsoft.com/MediaDL/WWW/B/belux/msdn/chopsticks/community/maartenballiauw-mvc-model-binder.wmv
        This is the video URL. Go put it ion your favorite download manager, and enjoy watching the video anytime.

    I hope this is useful for somebody!


    Cross posted from weblogs.asp.net/meligy



    Monday, June 01, 2009 #

    1. Go to https://addons.mozilla.org/en-US/firefox/addon/10434 ( Update: This is the only official provider made by Microsoft itself)
      This is the URL I originally posted (from which the below screenshots come): https://addons.mozilla.org/en-US/firefox/addon/12205 - Of course you are recommended to go to the official URL above.
      image
    2. Check “Let me install this experimental add-on” and click “Add to FireFox”
      image
      Now the add-in is there.
    3. In the search bar, click the little triangle at the left and choose Bing.
      image
    4. In your browser it may not the first item nor bold as in the pic here. Click “Manage Search Engines…”.
      image 
    5. Click “Move Up” to have it the first item
      image
    6. If you have Google Toolbar, you need to check more settings:
      1. Go to Google Settings. In the “Layout” tab, make sure to choose “Classic Toolbar Layout”. Save that.
        image image
      2. In Firefox address bar, type:
        about:config
        without “http://” or anything, and click the button that appears then.
        image
      3. In the “Filter” field type: “browser.search.defaultenginename”
        image
      4. Double click the only result that will show, you get a message box where you should  enter text. Replace the existing text “Google” with “Bing” instead, and click OK.
        image
      5. Close the window. Your default provider is set.

    Have fun :-)

     


    Cross posted from weblogs.asp.net/meligy



    If you are not on Twitter, let me spread this by @bing:

    Ladies and Gentlemen, www.bing.com is live. :) (rollouts will continue however to partners and other mkts, more to come) ^betsy

    Bing, if you don’t know, is Microsoft’s new search engine, also known as “Decision Engine” since it has features that help answer what you are wondering about rather than just display links.

    For those wondering about Live Search. I think I read somewhere that both search engines will remain there for a while, then Live will be brought out to Bing. Nothing to confirm yet though. In Bing homepage you read “Live Search is Evolving. Welcome to Bing”.

     

    For quick video of what Bing can give to you, check this.

    For an official introduction about what Bing is, check this.

     


    Cross posted from weblogs.asp.net/meligy



    Thursday, May 21, 2009 #

     

     

    IMPORTANT UPDATE

    There was a sudden last-minutes issue with the transportation / flights configuration that prevented me from making it to Cairo. I’ll be unfortunately missing out this event. M. Smay my friend will be a great backup with all the additional details he has to provide about his session content as well as an open session for the convenience of all of you.

    Sorry for missing out. I had to. I’m working with dotNETwork to re-organize my session as part of June 2009 gathering, but this is gonna be another story!

     

    Most of you already know I have moved recently from Cairo to Abu Dhabi. What only a selected set of you are aware of, is that I am still having my heart all set for the developer community in Egypt and still communicating with many of them via Twitter; not only that developers in Abu Dhabi are not into spending time in gatherings or anything than doing work and surviving, but also because I have made the only long lasting and fulfilling friends relationships with the key persons that I see in the different communities, especially my old friends from Microsoft MDC and ArabTeam2000, Demo Day attendees (who still talk to me since 2007), and - of course – dotNETwork, admins, speakers, and participants (who are much more than just attendees).

    Fridays City Stars 23rd of May 10:00 AM - 01:00 PM

    This Saturday isA I’ll be giving a session that relates to one of my beloved topics in development. Here is the information of the session:

    Session Title

    Lesser known .NET Enterprise Patterns & Practices

    Tag Line

    Is your mind ready? Booting up journey in enterprise patterns & practices in .NET

    Session Summary

    Through an illustration and a thoughtful discussion we are going to see how to go with our applications to the next level, leveraging ease of maintenance, integration points, and scalability out of the box; showing sample enterprise patterns and best practices that are very popular in many development platforms but are rarely used or even known for typical .NET developers

    The session will be like April’s session in Fridays City Stars, Nasr City. If you want to know what that is, this is because the Canadian University in Egypt  has stopped all activities in Saturday temporarily for reducing cost; you know, the crisis!

     

    Agenda, date and location

    • Lesser known .NET Enterprise Patterns & Practices
      by Mohamed Meligy - Information Analyst, .NET Technologies – (Injazat Data Systems, Abu Dhabi)

    • A lap around Visual Studio 2010
      by Mohamed Samy - Technical Architect (iSource Egypt)


    Fridays City Stars 23rd of May 10:00 AM - 01:00 PM

     

    Have you noticed something? Yes, my closest friend and one of the most lasting / oldest friend in this life, and in the field of course, Mohamed Samy, will be giving a session the same day. HE is such a true guru, and I fear everything ‘m going to say may look very pale compared to what he has to say about VS 2010.

     

    By the way, the attendance will require you to only pay 19 EGP or so– for a sandwich or meal that YOU eat (they have discounts for attendees). This is the host requirement and dotNETwork has NOTHING to do with it. After all, the only available host is now a commercial place. If you can help dotNETwork host the sessions in a completely free place, please contact anyone from dotNETwork and help get that done. PLEASE.

    Anyway, I think 20 EGP for something YOU get within the day is not very little but not much also. I saw guys paying the same to the cafe near the University when it was hosted there.

     

    Please be there. I know everybody was too busy to do right publicity of this event, and I myself am writing this very shortly before the event day, but, I’ll not be able to come back to Egypt even every few months, so, this time is very rare for me. Please let me meet the most of you who can make it. This is a personal request, to my true friends. period

     

    Related Sites

     


    Cross posted from weblogs.asp.net/meligy



    Wednesday, May 20, 2009 #

    Check the add-ins you installed before Visual Studio 2010 if you enabled VS 2010 integration in them. Particularly TestDriven.NET is the problem. Go to “Add Remove Programs” / “Programs and Features”, find Test Driven.NET, click “Change”, and then modify it to remove VS2010 integration from it.

     

    Also, if you are using AnkhSVN, make sure to download a new latest daily update build and use that, otherwise, you’ll get an exception when starting VS 2010.

     

    I’ll be writing more about VSTS 2010 and .NET 4.0 in the next coming months (if God will), since now I can run it :D (before, I did not have the fix that extends the Virtual Machine expiration after January 1st, 2009).

     

    BTW, for R# deep lovers (like me), Resharper for VS 2010 is expected next month.

     

    Have fun, please!

     


    Cross posted from weblogs.asp.net/meligy



    Tuesday, May 19, 2009 #

    Typemock guys, the guys behind the only mocking framework that can apply mocking in complex environments like Microsoft SharePoint, are releasing a new Product,, ASP.NET Bundle.

    Here is what they’re saying about it:

    Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle - and for the launch will be giving out FREE licenses to bloggers and their readers.

    The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

    Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

    The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you'll get a license automatically (even if more than 60 submit) during the first week of this announcement.

    Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

    Go ahead, click the following link for more information on how to get your free license.

    Of course you know what to do to spread the word! I hope no one minds this post ;-) ;-)


    Cross posted from weblogs.asp.net/meligy



    Thursday, May 14, 2009 #

    the AjaxControlToolkit has a new release, the release includes bug fixes and new HTMLEditor, ComboBox, ColorPicker controls/extenders.

    HTML Editor

    I liked the HTMLEditor control so much from first sight. Pretty lightweight and customizable. I still need to check whether it works fine inside UpdatePanel and whether it can be used with RequiredFieldValidator or so.

    image  image

    http://www.asp.net/AJAX/AjaxControlToolkit/Samples/HTMLEditor/HTMLEditor.aspx

     

    Color Picker

    The ColorPicjker is just an extender to TextBox control. This means a lot of opportunities and promises less problems with validators, etc... It’s a very nice one too.

    image

    http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ColorPicker/ColorPicker.aspx

     

    Combo Box

    The ComboBox is a control that is like a DropDownList with auto complete except that the user can enter a new text that is NOT in the existing items. This is good or bad based on your sole use.

    I did not like how it’s not well styled in the example page. This means it’s going to be headache to style in my sites as well, which is one of the biggest problems with AJAXToolkit in general.

    image

    http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx

     

     


    Cross posted from weblogs.asp.net/meligy



    Monday, May 04, 2009 #

    Just in case you missed the news, Yahoo has created it’s own query thingy. No, no LINQ provider, it’s a “query language”. Check it out!

    http://developer.yahoo.com/yql/

    Quote:

    What is YQL?

    Yahoo! makes a lot of structured data available to developers, primarily through its web services. These services require developers to locate the right URLs and documentation to access and query them which can result in a very fragmented experience. The YQL platform provides a single endpoint service that enables developers to query, filter and combine data across Yahoo! and beyond. YQL exposes a SQL-like SELECT syntax that is both familiar to developers and expressive enough for getting the right data. Through the SHOW and DESC commands we enable developers to discover the available data sources and structure without opening another web browser.

    How Do I Get Started?
    1. Check out the YQL Console.
    2. Read how to access YQL from your application.
    3. Get your Access Keys to sign your requests if you need them.
    Usage limits

    YQL has the following API usage restrictions:

    Per application limit (identified by your Access Key):
    • 100,000 calls per day.
    Per IP limits:
    • /v1/public/* 1000 calls per hour
    • /v1/yql/* 10000 calls per hour

    All rates are subject to change. In addition, you may also be subject to the underlying rate limits of other Yahoo and 3rd party web services.

    Try the console Read Documentation Download PDF Documentation

     

    Update:

    You can also check this for more details.

     

    Yes, I’m thinking about a LINQ provider to encapsulate this.

     

    Happy YQLing ;)

     


    Cross posted from weblogs.asp.net/meligy



    Wednesday, April 01, 2009 #

    If you don’t know what eager loading is, Jump to “What’s eager loading?”.

    Eager Loading Syntax

    If you are eager loading Products for example in a typical (Categories 1<->* Products) relation, the standard syntax would like:

    DbDataContext.Categories.Include(“Products”)

    What is the problem with that?

    The “Products” part. The word “Products” is a string. If I rename the Products table to ShopProducts or whatever or even remove it from this data diagram and have it elsewhere, or even something wrong happens and the relation is removed from DB/diagram by mistake, my code will still compile, but will fail when it runs. This is BAD BAD BAD.

    How to solve this?

    Since I always believe that if something exists somewhere you shouldn’t do it yourself unless its totally broken (and I mean REALLY REALLY BROKEN), I started searching inside the Entity Framework itself for something to get the entity name from.

    At first it seemed super easy. Every entity class has a static property “EntityKeyPropertyName”, so, I thought I can write something like:

    DbDataContext.Categories.Include(Product.EntityKeyPropertyName); // But this didn’t work

    Where Product is the entity class generated for table “Products”. Note that singularizing the name (Products becomes Product) does not happen automatically like in Linq-To Sql, you’ll have to change it manually, which is not required for the code here of course.

    As you an see n the comment, this didn’t work. The value of property was always “-EntityKey-”, the default value of the abstract class “StructuralObject” which all entity classes inherit.

    I kept searching all over until I found that the only place I can get the name from was an Attribute generated on the class somewhat like this:

    [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseNameFlowModel", Name="Products")]

    My requirement was simple. if the diagram has something wrong that the relation between ParentTable and ChildTable tables but not about the entity classes themselves, My code should not still compile and fail on run. I need to use some code that depends on the relation so that if something is wrong with the relation this code fails early and I know about it the problem the next time I build the VS project.

    The Final Solution

    I tried badly to get the entity name from the API, after frustration, I ended up writing this code:

    using System;
    using System.Collections.Generic;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    using System.Linq.Expressions;
    using System.Reflection;
     
    namespace Meligy.Samples.EntityFramework
    {
        public static class LinqExenstions
        {
            //Used for child entities.
            //Example: Order.Customer
            public static ObjectQuery<T> Include<T>(this ObjectQuery<T> parent,
                                                    Expression<Func<T, StructuralObject>> expression)
                where T : StructuralObject
            {
                return Include(parent, (LambdaExpression) expression);
            }
     
            //Used for child collections of entities.
            //Example: Order.OrderLines
            public static ObjectQuery<T> Include<T>(this ObjectQuery<T> parent,
                                                    Expression<Func<T, RelatedEnd>> expression)
                where T : StructuralObject
            {
                return Include(parent, (LambdaExpression) expression);
            }
     
            private static ObjectQuery<T> Include<T>(ObjectQuery<T> parent,
                                                     LambdaExpression expression)
                where T : StructuralObject
            {
                //There must be only one root entity to load related entities to it.
                if (expression.Parameters.Count != 1)
                {
                    throw new NotSupportedException();
                }
     
                //We'll store entity names here in order then join them at the end.
                var entityNames = new List<string>();
     
                //We split the calls ... Entity.MemberOfTypeChild.ChildMemberOfChildMember etc..
                //Example: (Order ord) => ord.Customer.Address
                string[] childTypesMembers = expression.Body.ToString().Split('.');
     
                //Get the root entity type to start searching for the types of the members inside it.
                //In prev. example: Find: Order
                Type parentType = expression.Parameters[0].Type;
                //entityNames.Add(GetEntityNameFromType(parentType));
     
                //The first word in the expression is just a variable name of the root entity. 
                //  Skip it and start next.
                //In example: First part is: ord
                for (int i = 1; i < childTypesMembers.Length; i++)
                {
                    string memberName = childTypesMembers[i];
     
                    //Get the member from the root entity to get its entity type.
                    MemberInfo member = parentType.GetMember(memberName)[0];
     
                    //We cannot get the type of the entity except by knowing
                    //  whether it's property or field (most likely will be property).
                    //Bad catch in the reflection API? Maybe!
                    Type memberType = member.MemberType == MemberTypes.Property
                                          ? ((PropertyInfo) member).PropertyType
                                          : ((FieldInfo) member).FieldType;
     
                    //Add the eneity name got from entity type to the list.
                    entityNames.Add(GetEntityNameFromType(memberType));
     
                    //The next member is belong to the child entity, so,
                    //  the root entity to seach for members should be the child entity type.
                    parentType = memberType;
                }
     
                //Join the entity names by "." again.
                string includes = string.Join(".", entityNames.ToArray());
     
                //Simulate the original Include(string) call.
                return parent.Include(includes);
            }
     
            private static string GetEntityNameFromType(Type type)
            {
                // We didn't just use the Entity type names because maybe
                //  the table is called Orders and the class is Order or OrderEntity.
     
                if (type.HasElementType) //For arrays, like: OrderLines[]
                {
                    //The type of the element of the array is what we want.
                    type = type.GetElementType();
                }
                else if (type.IsGenericType) // for collections, like: EntityCollection<OrderLines>
                {
                    var genericClassTypeParameters = type.GetGenericArguments();
     
                    //The generic class must have one entity type only to load it.
                    if (genericClassTypeParameters.Length != 1)
                        throw new NotSupportedException();
     
                    //The type of the element of the collection is what we want.
                    type = genericClassTypeParameters[0];
                }
     
                //Get the attributes that have the entity name in them.
                var entityTypeAttributes =
                    type.GetCustomAttributes(typeof (EdmEntityTypeAttribute), true) as EdmEntityTypeAttribute[];
     
                //Make sure there IS one and ONLY one attribute to get the only entity name.
                if (entityTypeAttributes == null || entityTypeAttributes.Length != 1)
                    throw new NotSupportedException();
     
                //Return the entity name.
                return entityTypeAttributes[0].Name;
            }
        }
    }

     

    This enables you to write:

    DbDataContext.Categories.Include( (cat)=> cat.Prodycts);

    Or:

    DbDataContext.Prodycts.Include( (prod)=> prod.Category);

    According to your need.

    For things like: Order.Customer.Address (multiple levels), you’ll have to write code like:

    DbDataContext.Orders.Include( order => order.Customer ).Include( customer => Customer.Address );

    What’s Eager Loading? (in case you don’t know)

    Let’s say you have tables Products, and Categories with relation 1<->* between them (Any category has many products; one product has one category). Let’s say you want to display a page of all products grouped by categories. Something like the following list but with much more information of course:

      • Category 1
        • Product A
        • Product B
        • Product C
      • Category 2
        • Product X
        • Product Y
        • Product Z

    If you are using some ORM / Code generator that creates for you classes like “Product”, “Category” and gives you properties like “myCategory.Products” , “myProduct.Category”, how would you create such page?

    Normally you’ll put a repeater or such for products inside a repeater for categories.

    image

    The products repeater will have its data source set to the current category item of the Categories repeater, something like “( (CategoryEntity)Container.DataItem ).Products”. Fine with that? Familiar?

    OK. Now, if the code generator that generated the “Products” property has something like that:

    public List<PRoduct> _Products;
    public List<PRoduct> Products
    {
        get
        {
            if (_Products == null)
            {
                _Products = (from products in DB.Products
                             where products.CategoryID == this.ID
                             select products)
                    .ToList();
            }

            return _Products;
        }
    }

    * Nevermind the LINQ syntax. It’s just like writing “SELECT * FROM [Products] WHERE …” with all the dataset/datareader stuff.

    Lazy Loading (AKA. Deferred Loading)

    If the generated code (or your code) looks like this, this means that that for every category in the database, you’ll have a separate DB call to get the products of this category.

    It also means that the products of each category will not be loaded until someone writes code that calls the getter of the Products property. That’s why this style of coding (not loading the related objects until they’re asked to be loaded) is called Lazy Loading.

    This is good for a single category where you may be seeking just the basic information of the category and will not try to load products, since then they will not be requested when you don’t ask for it.

    However, this is very bad for our example page. Because it means that a new DB call for each category. Imagine that you have 20 or 50 or 100 Category there, this will give you how many DB calls? (Hint: N Categories + 1 call for the category list itself).

    Eager Loading

    What if the code in the getter above was in the constructor?. Imaging something like:

    public Category(int categoryID)
    {
        // Code that laods category info from DB. Does not matter here.
        //Could be in factory method or such. Not our topic
        _CategoryID = categoryID;
        // .... .... .... Continue Loading Logic

        //The important part
        _Products = (from products in DB.Products
                     where products.CategoryID == this.ID
                     select products)
                    .ToList();
    }

    This is good in case you know that in every situation when you use the category, the Products will be needed. This is probably not useful in a Product/category Scenario but think of a Person table and Address table where most likely whenever you load a Person you’re going to load his Addresses.

    This is also useful especially when using ORM/code generator as in the first example. Lets get back to the Repeater example. If you use Entity framework or similar ORM, and you set the Categories query to load the Products eager loading (meaning each Category is created with its Products loaded already), Entity Framework can have a single connection and only TWO database hits, one for the Categories, and one for the Products. This is very useful in many listing scenarios. It also help especially when you have many parent objects (say Categories) or if the parent object needs to load entities of many different classes (say User needs to load Roles and Permissions and Personal Information and History and …. (if such case is applicable for you of course.

    Now that you know what eager loading is, you can go up and check how the Entity Framework does that.

     


    Cross posted from weblogs.asp.net/meligy



    Thursday, March 19, 2009 #

    Follow Me On Twitter

    http://twitter.com/Mohamed_Meligy

    So, a very short note on my last news is that now I’m in Abu Dhabi, UAE; for a while not having a laptop, which is why I haven’t blogged since dotNETwork CodeCamp’09.

    Then I thought of Micro-blogging. If you know Twitter already you know what I mean, if not, think of something like facebook status; micro space to say something that’s in your mind now. A good way to say something quick and it has been popular for technical guys and even some western public figures for years.

    So, basically, you can have people who subscribe to (AKA “follow”) your Twitter updates using Twitter website or just subscribing to your updates RSS feed, can include links or mention other users or reply to their updates. You can “tweet” by going to the website or by sending SMS, or using one of many desktop applications / add-ins that exist for this, and yeah, it has a facebook application that sets your facebook status to your last Twiter update.

    I’ve been member of Twitter for long, but I just follow the updates of some other guys and very rarely have my own updates. Now I’m going to send more updates myself!  [If god Will]

    My last two updates before writing this post:

      1. It's a final releases weekend!!! Internet Explorer 8 final is out too, download from http://tinyurl.com/ie-home
      2. ASP.NET MVC v1 is out. Download from http://tinyurl.com/aspmvc1. Also check the ebook http://tinyurl.com/aspmvcebook

    But NOTE that I do intend to make my twitter updates a hybrid between technical stuff and personal stuff.

    Based on the Twitter client i use and primarily my mood and how much I get busy (and with what) I’ll either be sending an update every few minutes or having no updates for a year or more. We shall see how this may go!

     

    Follow Me On Twitter

    http://twitter.com/Mohamed_Meligy

    BTW, pray for me to get my laptop this Sunday as expected [If God Will]. I like the huge DELL super-flexible wide screen and it’s stretching & rotating holder so much, but I need to blog about those snippets of code I have written in the new project I’m working on now and dump more of my thoughts about validation, LINQ, Domain Driven Design, ASP.NET workarounds and such. I need to finish stuff in the weekend some related to work and some related to family and some related to BLOGGING ;). I need to use OneNote to document my meetings wherever they are set and still have my Wi-Fi Internet. Man, I just cannot work without this portable thing in my hands!

     

    BTW#2:

    If you are subscribed to my Google Reader Shared Items (where I share everything I read or find interesting on the web and SO MANY FEEDS), you’ll get my Twitter updates as well, as I’m subscribed to my own Twitter feed and share my updates in the same feed.

    Google Reader Shared Items

    http://www.google.com/reader/shared/user/08221036579558509505/state/com.google/broadcast

     


    Cross posted from weblogs.asp.net/meligy