Mike Borozdin's Blog

A blog about programming, web and IT in general

Design Patterns are not a Silver Bullet and the State of the Programming Blogosphere

Design patterns are not a universal tool that can be applied to any project or be used with any programming language. Quality code can be produced without implementing any pattern or even without using OOP. One shouldn’t think of their colleagues as of bad developers if they don’t know the names of fancy design patterns. Moreover, not any single programming project is a business application.

Recently I have read so many blog posts where authors ranted about design patterns, test-driven development and similar stuff. It feels like many people approach design patterns as a silver bullet that will help them to solve any tricky problem they may encounter. Furthermore, the same people become really angry if somebody thinks out of the box and simply disagrees with their ideals. I don’t imply that the majority of programmers think so, but the blogosphere tend to be in such a state. At least, the blogosphere I’m circulating in, being mainly a web developer I mostly read about web related technologies. Sometimes, it’s even amusing to read people’s reaction to the opposite opinions, especially if an opinion is expressed by Joel Spolsky. Frankly, it looks like almost every programming blogger feels honoured to disagree with Mr Spolsky.

Anyway, design patterns don’t deserve that buzz they are getting. Most of design patterns are so obvious that it is even silly to read or write about them. For instance, I’ve come across a great number of articles about Dependency Injection that in fact is a pretty trivial thing. Every smart developer is able to come up with it when he needs it. There is no point of trying to memorise every single pattern, because it can lead to its stupid implementation when it’s completely undesirable, for example, in small projects where the patterns implementation code can become bigger than the code performing some real job. Of course, I don’t think that it is bad if a common programming technique has finally got the name, but it is stupid to think that if somebody doesn’t know what “dependency injection” is, then he will never produce good code. “Dependency Injection” is hardly more than just a name.

In addition, design patterns and even OOP are not universally applicable. There are many programming projects besides business applications and often you are limited by the resources you have. Many popular applications that are used by everyone are written in pure C which doesn’t support OOP. However, this doesn’t mean that the code written in C is bad or “smells” as some design patterns followers would say. There is a great presentation called “The (lack) of design patterns in Python” on this topic.

Also, a gap between different worlds of programming often leads to misunderstandings when, for example, somebody tries to prove that everyone should do test-driven development even when programming with a Assembly language. It’s usually the design patterns adepts who can’t imagine that programming isn’t all about writing custom business applications.

Indeed, even if we are just web developers we are still fascinated with other stuff, like computer games with mind blowing graphics or convenient operating systems or precise search engines and a lot more, but when people create all that software they think not about design patterns but about useful and fast algorithms.


Posted by Mike Borozdin on Monday, January 04, 2010 3:45 AM GMT
Shout it Kick it!  
Permalink | Comments (8) | Post RSSRSS comment feed

Free .NET 4.0 Hosting

I received an e-mail from DiscountASP which hosting services I was using that they had launched a free beta testing programme of their .NET 4.0 hosting. The beta testing is open to everyone, it’s not limited to the DiscountASP customers.

As their website says you will have the following:

  • Windows Server 2008 R2 Platform
  • .NET Framework 4.0 beta 2
  • 50 MB disk space
  • 50 MB SQL Server 2008 disk space
  • FTP
  • Uses DiscountASP.NET subdomain
  • End Date: Sunday, January 31, 2010
  •  

    http://labs.discountasp.net/netfx4/index.aspx


    Tags:
    Posted by Mike Borozdin on Thursday, December 10, 2009 2:09 PM GMT
    Shout it Kick it!  
    Permalink | Comments (1) | Post RSSRSS comment feed

    Enjoying Sexy Microsoft LifeCam Cinema

    Recently I have received a nice present from Microsoft (yes, I do receive some cool stuff from them, since I’m a Microsoft Student Partner) – a Microsoft webcam.

    I must admit I’m not an expert in web cameras, although I’m using my laptop built-in webcam very intensively, since I’m living in the UK now away from my parents who are in Russia and whom I call each day with Skype. Anyway, the video quality of my built-in web camera is pretty awful, but I wasn’t aware of that before, I mean there was a noise and the video at times wasn’t very smooth, but I didn’t pay much attention to that.

    However, after unpacking and installing the Microsoft camera, I was simply blown away by the video quality. They claim this camera supports HD with 720p, but since I’m not in the HDTV bandwagon, I can’t tell you what it is, you’d better ask Wikipedia about tis. Anyway, the quality is superb, moreover it supports different resolutions up to 1280x720.

    Before (with my laptop built-in camera) the video looked like this:

    image_sb_1

    But now it looks like this :-):

     2009-12-04 19-12-50.751

    Please, note I haven’t adjusted any settings and the resolution is just 640x430.

    Also, the camera has good auto-focusing, meaning that if you move around, back and forward it will automatically focus, to illustrate this feature, I placed a sheet of paper in front of my two cameras. I bet you can guess which image belongs to which camera.

    image_sb_2

    2009-12-04 19-11-27.441

    Moreover, the came has a built-in microphone that appears to be even better than my cheap external Logitech mike.

    The only glitch I have found so far is its fixing mechanism, I mean perhaps it fits perfectly regular displays, but I don’t think the fix fits my laptop very well, although the camera fixed on it, but I have a fear that it’s not fixed firmly enough.

    To learn more about this lovely camera follow this link.


    Tags:
    Posted by Mike Borozdin on Friday, December 04, 2009 11:20 AM GMT
    Shout it Kick it!  
    Permalink | Comments (5) | Post RSSRSS comment feed

    AJAX File Upload in ASP.NET with the AsyncFileUpload Control

    Finally, it has become possible to easily add AJAX file uploading capabilities to ASP.NET applications. The newly released version of the AJAX Control Toolkit ships with two new controls, one of them is called AsyncFileUpload control which was designed specially for the above mentioned purpose. It’s really great that a new version of AJAX Control Toolkit has arrived, because the project seemed to be dead, especially since ASP.NET MVC had taken its place on the stage and many developers switched to it and to jQuery which can also be used with ASP.NET WebForms.

    Anyway, it is the time to introduce the control for asynchronous file uploading. First of all, you should download the newest version of the ACT, unpack it and add to the Visual Studio toolbox, or replace the previous versions controls. Actually, you can follow these installation instructions.

    After installing the toolkit, just create a new web site, place a ScriptManager on a web page and eventually drop a AsyncFileUpload. Basically, here is a small code snippet asynchronous image uploading and immediate displaying it on the page.

     Default.aspx

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <%
    @ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <!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 runat="server">
    <
    title></title>
    <
    script type="text/javascript">
    function
    showUploadConfirmation() {
    alert("Upload finished!");
    }
    </script>
    </
    head>
    <
    body>
    <
    form id="form1" runat="server">
    <
    asp:ScriptManager runat="server" />
    <
    div>
    Just some time to make sure that the page doesn't get reloaded after uploading: <%=DateTime.Now %><br />

    <
    cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server" UploadingBackColor="Yellow"
    OnUploadedComplete="ProcessUpload" OnClientUploadComplete="showUploadConfirmation" ThrobberID="spanUploading" />
    <
    span id="spanUploading" runat="server">Uploading...</span>
    <
    br />

    <
    img src="" id="imgUpload" alt="" />
    </
    div>
    </
    form>
    </
    body>
    </
    html>

    There are a few points of interest in this piece of code. In this particular example I’m only using some of the AsyncFileUpload attributes.

    OnUploadComplete – the name of a public code-behind method that is invoked after uploading is completeat

    OnClientUploadComplete – as the name suggests it is the same thing but it’s for client-side, therefore it’s just a JavaScript function

    ThrobberID – the ID of a control to display while uploading is in process, please note it can be either a WebForm control or an HTML one but with the necessary runat=”server” attribute

    UploadingBackColor – the background colour of the upload control during the uploading process

    For the complete list of the control attributes, please use this reference page.

    Also, please pay attention at the <img /> that is going to be used for immediate display of an uploaded image.

    The code-behind code is also not difficult to use.

    Default.aspx.cs

    protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
    string fileName = Server.MapPath("./") + "image.jpg";
    AsyncFileUpload1.SaveAs(fileName);

    ScriptManager.RegisterClientScriptBlock(AsyncFileUpload1, AsyncFileUpload1.GetType(), "img",
    "top.document.getElementById('imgUpload').src='image.jpg';",
    true);
    }

    Here we just have the method used for handling the event. The main idea is not just to save a received file, but also to display an uploaded image immediately. For this purpose we have to use ScriptManager.RegisterClientScriptBlock() that basically injects a portion of JavaScript code into a page. It is also important to notice that we are using top.document.getElementById(), this is because the AsyncFileUpload is still making use of the iframe to make the asynchronous upload possible.


    Tags: ,
    Posted by Mike Borozdin on Monday, October 12, 2009 11:24 AM GMT
    Shout it Kick it!  
    Permalink | Comments (0) | Post RSSRSS comment feed

    The *Intelligent* Blog Spam

    Nowadays, the comment spam isn’t those dumb messages that just used to contain an URL to scammers web site. Today, the comment spam is aimed to for SEO. Usually you receive a commentary that at first sight doesn’t have anything suspicious, it may have just a couple of words or “Thanks”, but if you look closer, you will notice that the URL field of the comment author is filled in and the web site doesn’t have anything in common with the topic of your blog post. By doing this they are trying to increase the Google PageRank, so it’s reasonable to add rel=”nofollow” to the URL field. Of course, if it happens once, it may be a real man, but if you are always receive such comments, then it can be nothing else, but spam.

    Moreover, such comments usually have some words and phrases that present in the original article, for instance I usually meet spam comments with “ASP.NET” or “Internet Explorer” in their text. But what amused me most of all is this particular comment:

    ASP.NET has gone in unmanaged and unstable state where we have 100s of project coded in ASP.NET 2.0 and when we open them in 2008 nothing opens, upgrading to 3.5 are mere nightmares. And finally so many new technologies just to boost the marketing headlines. But come on guys, its easy for one blogger to just blog about able to mix technologies with writing 100s of lines of code which one geek can understand. Have you even worked on any project involving more then 5 developers? Practically we are spending more monty to train new things to our staff, more money to buy new tools, more money to manage projects and more and more money to sit and search world of forums to find why one thing doesnt work then actually doing simple development.

    It is really hilarious, considering that fact that it was posted under article called “Is PHPLinq As Cool As Real LINQ?”.


    Tags:
    Posted by Mike Borozdin on Monday, August 17, 2009 4:10 AM GMT
    Shout it Kick it!  
    Permalink | Comments (1) | Post RSSRSS comment feed

    Why I hate PDF as an E-book Format or PDF vs CHM

    PDF (Portable Document Format) is a common choice for e-books, big manuals comprising of several hundred pages and other documents. At a first glance, it seems to be a reasonable choice. PDF is a really cross-platform format, the most popular PDF viewer – Adobe Acrobat – is freely available in all popular operating systems – Windows, Mac OS and Linux. But what is wrong with it?

    Well, the first of all, it tends to be slow, of course, it might depend on an application you are viewing your document with, but still opening large files in Adobe Acrobat doesn’t seem to be an easy walk. Of course, it’s not the only reason why I think this format is a poor choice for e-books.

    There is a significant disadvantage of PDF – its searching capabilities. Frankly speaking, it’s not format’s fault, but a glitch of the current PDF viewers. The problem with searching through PDF is its linearity, I mean, when finding some word or a phrase it will show you every occurrence of that word or phrase from the top of the document to its bottom. Sure, you can open the “Full Reader Search” window, but still it will just represent a list of matched occurrences.  So, it’s not very convenient to search through a 500 pages document for a word that you might find in its bottom or in the middle of the document.

    image

    Nevertheless, there is a document word that doesn’t have the above mentioned disadvantages. I suppose everyone must be familiar with it. It’s CHM (Microsoft HTML Help). In fact, the format is just a collection of simple HTML pages. But unlike PDF, CHM is quite fast. It supports chapters, yes, PDF does also can contain chapters in the document, but they are no so convenient. In addition, when you open a PDF document, all its contents get loaded at once, while CHM only loads the pages and the chapters you are reading.

    And of course the main advantage of CHM over PDF is its search capabilities. When you search through a CHM documents you will get a list of the relevant chapters and pages ordered by their relevancy.  The CHM search engine is also morphological aware.

    image

     

    In a conclusion I’m going to say that actually it’s quite obvious that PDF is such common as an e-book format because it is the format that is used for submitting books to a printing office and therefore they don’t have to prepare any other kind of documents to publish an e-book, they can just sell PDFs, while creating a CHM file involves a greater amount of work. As a result such e-books don’t have any significant advantages over printed ones. Sure, they don’t take any space on a bookshelf, they are cheaper than paper books and they don’t require cutting wood to create paper, but still they are not very convenient for reading and finding some information.

    Anyway, there are some places on the Net where it is possible to find CHM e-books.


    Tags:
    Posted by Mike Borozdin on Thursday, July 30, 2009 12:17 PM GMT
    Shout it Kick it!  
    Permalink | Comments (13) | Post RSSRSS comment feed

    Working with Google Maps API in ASP.NET

    Recently I have been working on a project where I needed to make use of some geographical data and I decided to use Google Maps for that. So, in this particular tutorial I will explain how one can start working with the Google Maps API in ASP.NET.

    Basically, the following topic will be covered:

    • How to find a place on the map by address
    • How to let a user choose a place on the map and retrieve its coordinates and save them in a database.

    What is Google Maps API?

    But first we need to learn some basic of working with Google Maps. As a matter of fact when integrating Google Maps in your application you have to use the Google Maps API, which is in fact just a set of JavaScript functions. As a result you don’t interact directly with the Google Maps API in ASP.NET, I mean server-side, but instead you place your code to client-side and work with JavaScript.

    image

     

    So, the Google Maps can be used with any server-side technology/language, like ASP.NET, PHP, Ruby on Rails, Python and etc., but this tutorial is about ASP.NET.

    Getting Google Maps API Key

    The first important step of getting started with the Google Maps API is obtaining the Google Maps API Key. Don’t worry it is free of charge and you receive the key immediately after filling in a form here.

    Creating a Simple Map

    Okay, now it’s the right time to open Visual Studio and create a new web site.

    Then, add the following code to the <head> tag:

     

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=<YOUR_API_KEY>&sensor=false"
            type="text/javascript"></script>
    <script type="text/javascript">
        function initialize() {
            if (GBrowserIsCompatible()) {
                var map = new GMap2(document.getElementById("map"));
                map.setCenter(new GLatLng(51.5, -0.1), 10);
                map.setUIToDefault();
            }
        }

    Don’t forget to change <YOUR_API_KEY> to an appropriate value. As you can see we have just one function called initialize() that creates a new instance of the map object. We also pass the object – a div – that will be a map container. Then, we invoke the setCenter() method that receives two arguments –coordinates and a zoom level. The setUIToDefault() method just adds the UI manipulators, if you remove or comment that line, you will receive a bare map without any UI controls.

    Also, you need to add some code that will run the initialize() function and the HTML code for the map container.

    <body onload="initialize()" onunload="GUnload()">
        <form id="form1" runat="server">
            <div id="map" style="width: 500px; height: 500px"></div>
        </form>
    </body>

    The code is pretty self-explanatory, it just adds the handlers for the onLoad and onUnLoad events of the page and also we put a div that will contain the map, you can adjust its width and height in order to get a bigger or a smaller map.

    After compiling this page you should see a map similar to this one:

    image

    Finding a place by its address

    Well, it was pretty simple, but in real life project you usually have to find a place on the maps by its address. This is also possible with the Google Maps API. All you have to do is to make use of the GClientGeocoder class and its method called getLatLang() that accepts two parameters:

    • address – the address to look for
    • function – a callback function with one parameter point that posses the coordinates of the found place

    So, if we want to find a house where Sherlock Holmes lived we have to write the following code:

    <script type="text/javascript">
            var map;
            var geocoder;
            function initialize() {
                if (GBrowserIsCompatible()) {
                    map = new GMap2(document.getElementById("map"));
                    map.setCenter(new GLatLng(51.5, -0.1), 10);
                    map.setUIToDefault();
    
                    geocoder = new GClientGeocoder();
    
                    showAddress("221B Baker Street, London, United Kingdom");
                }
            }
            function showAddress(address) {
                geocoder.getLatLng(
                    address,
                    function (point) {
                        if (!point) {
                            alert(address + " not found");
                        }
                        else {
                            map.setCenter(point, 15);
                            var marker = new GMarker(point);
                            map.addOverlay(marker);
                            marker.openInfoWindow(address);
                        }
                    }
                );
            }
            </script>

    Also, we create a map overlay that will contain the address information, for this purpose we create an instance of the GMarker class and use the openInfoWindow() method.

    User Interaction with Map

    Okay, but what if we want to let user enter an address in a form and find its on the map? No problems! Just add the necessary field and write an event-handler.

    <script type="text/javascript">
            var map;
            var geocoder;
            function initialize() {
                if (GBrowserIsCompatible()) {
                    map = new GMap2(document.getElementById("map"));
                    map.setCenter(new GLatLng(51.5, -0.1), 10);
                    map.setUIToDefault();
    
                    geocoder = new GClientGeocoder();
                }
            }
            function showAddress() {
                var txtAddress = document.getElementById("<%=txtAddress.ClientID %>");
                var address = txtAddress.value;
                
                geocoder.getLatLng(
                    address,
                    function (point) {
                        if (!point) {
                            alert(address + " not found");
                        }
                        else {
                            map.setCenter(point, 15);
                            var marker = new GMarker(point);
                            map.addOverlay(marker);
                            marker.openInfoWindow(address);
                        }
                    }
                );
            }
            </script>
    </head>
    <body onload="initialize()" onunload="GUnload()">
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="txtAddress" runat="server" />
                <input type="button" value="Find" onclick="showAddress();" />
            </div>
        
            <div id="map" style="width: 500px; height: 500px"></div>
        </form>
    </body>

    Letting Users to Manually Select a Place on the Map

    Well, finding a place by its address is certainly cool, but we can add yet another level of interactivity to our map. Basically, we can let users to use manually choose a place on the map by just dragging a marker.

    <script type="text/javascript">
            var map;
            var geocoder;
            function initialize() {
                if (GBrowserIsCompatible()) {
                    map = new GMap2(document.getElementById("map"));
                    var center = new GLatLng(51.5, -0.1);
                    map.setCenter(center, 10);
                    map.setUIToDefault();
    
                    var marker = new GMarker(center, { draggable: true });
                    map.addOverlay(marker);
                    marker.openInfoWindow("Drag the marker to a specific position");
    
                    GEvent.addListener(marker, "dragstart", function() {
                        map.closeInfoWindow();
                    });
    
                    GEvent.addListener(marker, "dragend", function() {
                        var hdnLat = document.getElementById("<%=hdnLat.ClientID %>");
                        var hdnLng = document.getElementById("<%=hdnLng.ClientID %>");
    
                        hdnLat.value = this.getLatLng().lat();
                        hdnLng.value = this.getLatLng().lng();
    
                        marker.openInfoWindow("New position has been set");
                    });
                }
            }
            </script>
    </head>
    <body onload="initialize()" onunload="GUnload()">
        <form id="form1" runat="server">
            <asp:HiddenField ID="hdnLat" runat="server" />
            <asp:HiddenField ID="hdnLng" runat="server" />
            <div id="map" style="width: 500px; height: 500px"></div>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
                onclick="btnSubmit_Click" />
        </form>
    </body>

     

    If you look at the HTML code, then you will notice that we have added to hidden field that will contain the coordinates of a chosen place, so the first field is for keeping the latitude and the second one is for keeping the longitude. This time when creating a marker we set its options and one of the option is “draggable: true”, so it lets users to drag the marker over the map. Then, we should add event handlers, the main event is “dragend”. It occurs ever time a user place a marker on a new place. As a result, in its event handler we receive the coordinates of a new position and save them in the hidden fields.

    Also, we wrote an event handler for the “dragstart” event, just to close the info window while dragging the marker.

    In a real world application there would be some server-side code that would place the received coordinates into a database, but in this particular case, we will just output them:

     

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Response.Write("Latitude: " + hdnLat.Value + " Longitude: " + hdnLng.Value);
    }

     

    Passing the Coordinates from Server-Side to Google Maps

    Now, what if we have the coordinates stores somewhere in the database and want to point to that place on the map? Well, it’s still not difficult. We just have to pass the values from server-side to JavaScript.

    <script type="text/javascript">
            var map;
            function initialize() {
                if (GBrowserIsCompatible()) {
                    map = new GMap2(document.getElementById("map"));
                    
                    var lat = <asp:Literal ID="ltrLat" runat="server" />;
                    var lng = <asp:Literal ID="ltrLng" runat="server" />;
                    
                    var center = new GLatLng(lat, lng);
                    
                    map.setCenter(center, 10);
                    map.setUIToDefault();
                    
                    var marker = new GMarker(center);
                    map.addOverlay(marker);
                    marker.openInfoWindow("Here");
                }
            }
            </script>

    The easiest way to achieve this is to use the ASP.NET Literal controls that doesn’t generate any tags around their values.

    Since, those Literal controls are outside of the form tag, we have to use the FindControl() method to access them in code-behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        Literal ltrLat = (Literal)FindControl("ltrLat");
        Literal ltrLng = (Literal)FindControl("ltrLng");
        
        ltrLat.Text = "51";
        ltrLng.Text = "0";
    }

    Conclusion

    In this tutorial we have covered the basics of working with the Google Maps API. We have learnt how to add a map on a page, how to use geo coding for finding a place by its address on the map. We have also got to know how we can let users interact with a map by dragging a marker and how to receive the marker coordinates and store them on server-side. Finally, we have learnt how to pass the coordinates stored on server-side to the Google Maps API and point to that place on a map.

    Also, in this tutorial version 2 of the API was covered, however the 3rd version is currently in Google Labs.

    Resources

    The main resource for the developers willing to work with the Google Maps API is certainly the Google Code reference page.


    Tags:
    Posted by Mike Borozdin on Tuesday, July 28, 2009 6:34 AM GMT
    Shout it Kick it!  
    Permalink | Comments (2) | Post RSSRSS comment feed

    Using Live Mesh as a Free Backup Utility

    Recently I was looking for a free backup tool that would keep my important documents online and in case any problems with my laptop, I could easily recover them.

    I could use my own hosting space, but I thought it wasn’t convenient to manually upload the documents I was constantly working on. So, I decided to look for some automatic solution. Basically, I need the following things:

    • Ability to save the data online
    • Ability to perform automatic synchronization, i.e. when I change a file on my local computer it should get automatically updated on the remote storage and vice versa.

    Thus, such things as the built-in Windows utilities that required you save your data on external devices or network drivers wasn’t the thing I was looking for. Moreover, various online services like SkyDrive was still not the best choice, because they just provided an online storage, but didn’t give any mechanism of automatic file synchronization. I also had a look at Live Sync this service was very close to the thing I was looking for, but unfortunately it could only synchronize data only between connected devices, but it didn’t have any online storage. Anyway, I was given an advice to try Live Mesh.

    At a first glance Live Mesh is nearly identical to Live Sync, however it has one, but significant difference – it does provide an online storage of 5 GBs which was pretty enough for me.

    So, what do you need to do to start backing up important data with Live Mesh? First of all, you need to sign up with it. After that you’ll get an access to Live Desktop where you can create folders and upload files manually. Sure, manual file uploading isn’t the best thing to do and you can download an utility which reside in the system tray and will monitor all the changes of the files you set to synchronize. However, it’s not very clear how one can download the necessary software, in fact, you should select “Add Device" from the main menu.

    image

     

    After installing the software, you can just select the folder which contents you want to backup in Windows Explorer.

    image

    And every file you create or edit will be automatically added to your online storage.

    Generally, I’m very happy with Live Mesh and would definitely recommend to give it a try. Also, don’t forget that it’s presently in the beta phase, so many features are to come, for example, software for mobile devices, while now you can install it on Windows and Mac.


    Tags:
    Posted by Mike Borozdin on Wednesday, July 01, 2009 11:09 AM GMT
    Shout it Kick it!  
    Permalink | Comments (3) | Post RSSRSS comment feed

    Put EntityDataSource Attributes to Code-Behind

    The EntityDataSource control is a very powerful one. It allows you to rapidly create database driven application. You don’t have to manually write code for extracting, modification and deleting records from the database. Moreover since this code is backed by Entity Framework, you are not tied up with a particular database schema and can easily change it or even choose other database application.

    However when working with EntityDataSource sometimes I feel like I using plain old SqlDataSource and simply have too much unnecessary code in my .aspx files. For instance, you may end up have code like this one:

    <asp:EntityDataSource ID="EntityDataSource1" runat="server" 
        ConnectionString="name=NorthwindEntities" 
        DefaultContainerName="NorthwindEntities" EnableDelete="True" 
        EnableInsert="True" EnableUpdate="True" EntitySetName="Products" Include="Categories, Suppliers" AutoGenerateWhereClause="true">
        <WhereParameters>
            <asp:QueryStringParameter Type="Int32" Name="CategoryID" QueryStringField="CategoryID" />
            <asp:QueryStringParameter Type="Int32" Name="SupplierID" QueryStringField="SupplierID" />
        </WhereParameters>
    </asp:EntityDataSource>

    That certainly isn’t cool at all. Because it simply shouldn’t be in an .aspx file, not only because it breaks application layers, but simply because it inconvenient. It clutters .aspx files which should be templates only. What if a designer meets code like this? What if accidently change something?

    Instead it’s reasonable to move all these lines of code to code-behind.

    So, in your .aspx file you just leave this declaration:

    <asp:EntityDataSource ID="dsProducts" runat="server" />

     

    While put all the attribute assignments to code-behind:

    NorthwindEntities db = new NorthwindEntities();
    
    dsProducts.ConnectionString = db.Connection.ConnectionString;
    dsProducts.DefaultContainerName = "NorthwindEntities";
    dsProducts.EntitySetName = "Products";
    dsProducts.Include = "Categories, Suppliers";
    
    dsProducts.EnableUpdate = true;
    dsProducts.EnableInsert = true;
    dsProducts.EnableDelete = true;
    dsProducts.AutoGenerateWhereClause = true;
    
    dsProducts.WhereParameters.Add(new QueryStringParameter("CategoryID", TypeCode.Int32, "CategoryID"));
    dsProducts.WhereParameters.Add(new QueryStringParameter("SupplierD", TypeCode.Int32, "SupplierID"));

     

    In fact, the same technique applies to any other data source control, like LinqDataSource or even ObjectDataSource.


    Posted by Mike Borozdin on Monday, March 23, 2009 8:43 AM GMT
    Shout it Kick it!  
    Permalink | Comments (6) | Post RSSRSS comment feed

    CSS Class Names Instead of ASP.NET Client IDs

    In ASP.NET the client IDs of controls are often really unpredictable. When you need to add some JavaScript code that works with rendered controls you have to know their IDs. But usually an ID looks like something like this: “ctl00_contentBody_txtStreet”. There are several methods for overcoming that difficulty explained here. However they require writing additional code or even creating your own controls inherited from the original ones.

    But there is one simply but yet dirty way of addressing HTML elements rendered by ASP.NET. Do you remember that you can assign the CssClass attribute to any server control? Do you remember the jQuery selector that allows you to retrieve the elements with the specified CSS class? So, we can use it!

    The pattern is simple:

    <asp:TextBox ID="txtStreet" runat="server" CssClass="txtStreet" />

    You just add the CssClass attribute and give it a unique value.

    Then you can retrieve the value of the element or perform any other manipulation with jQuery:

    alert($('.txtStreet').val());

    Pretty simple. Although you must remember that it can take some time in case you have a long page because it will look through all the HTML tags to find the one with the given class name. At the same time for fast execution you can specify which elements to look for, you can simply add a tag name before, for instance “input” or a jQuery attribute – “:input”:

    alert($('input.txtStreet').val());

    Tags:
    Posted by Mike Borozdin on Thursday, February 26, 2009 1:32 AM GMT
    Shout it Kick it!  
    Permalink | Comments (9) | Post RSSRSS comment feed