Archive for C#

ADO.NET Data Service in Plain English

I have been using ADO.NET Data Service in Silverlight since Astoria team released the client library for Silverlight. I didn’t have a particular idea to use that service except this is something new that I like to try. After reading a few article about Astoria, I come to know that I can retrieve the data from Astoria service by typing the URL in browser. And we have to use the different HTTP verbs for CRUD operations. That’s all? I think “No”. So, I raised a question in MSDN forum last week. Today, I got very useful and informative reply from Mike Flasko. (Thanks a lot for your reply, Mike.)

Here is the original thread that I posted in MSDN forum. Now, I’m here to share this information with you all. Hope that you will find it useful.

Question : What is ADO.NET Data Service (Astoria)?

Hello,

Could anyone please explain me about ADO.NET Data Service in plain english without using marketing term?

AFAIK,
- we can query the data by typing URL in browser.
- it supports CRUD operations with different HTTP verb.

But I believe that there might be some important reasons why people created this framework.

  • What is the ADO.NET Data Service?
  • What are the advantages of using ADO.NET Data Service?
  • What’s wrong with Web service?
  • What is the reason why making differnt HTTP verb for CRUD operation?

Thanks in advance.
Michael Sync

Answer from Mike Flasko (Astoria Program Manager [MSFT] )

Hi Michael,

In general the goals of ADO.NET Data Services are to create a simple REST-based framework for exposing data centric services. We built the framework in part from analysis of traditional websites and then looked at how architectures were changing with the move to AJAX and RIA based applications. One key observation the team had was that in traditional approaches to web development the information exchanged between a client (ex. a webbrowser) and the mid tier was a combination of presentation + behavior + data (ex. HTML file with javascript and inline HTML tables of data) and that the core interactions to retrieve raw data was between the mid-tier and backend store (ex. SQL server or other). When we looked at RIA, AJAX, smart client, etc applications it became apparent that these architectures pushed much more “smarts” to the client tier where the client first retrieves the presentation + behavior information (as a DLL in the case of a Silverlight application) and then as the user interacts with the client application, the app turns back (ex. background async call) to the mid-tier to retrieve the data needed to drive the user experience. This is nothing new (separation of presentation + behavior from data), but its interesting to note it now not only a best practice but mandated in the architectures of today’s web and RIA apps. From this we looked at how such clients could consume data from the mid-tier today and how could we help improve the experience for the developer. A few areas came up:

  • Creating and maintaining rich data oriented services with current approaches requires a significant developer investment
  • Building generation purpose client libs/tools with current approaches to data centric services is hard

For #1, imagine you wanted to expose the data in your CRM database to you client tier application. Further assume you want to enable typical application scenarios like retrieving sorted views of the data, paging over the data, filtering, etc. To expose this data as a set of callable remote methods (using current approaches to developing web services) you would need to write a large number of methods to expose each of the entities in your CRM DB (customers, orders, etc) and then add additional methods for each to retrieve entities by key, sort them, page over them, etc etc. ADO.NET Data Services, addresses this issue by allowing you to declaratively state the contract of such a data centric service, by telling us the schema of the data and having the data services technology automatically create the required remote endpoints, enabling paging, sorting, etc with no code from the developer. Then as you change your data model, your service endpoints also change.

For #2 above, an interesting artifact of a REST-based approach to web services is that it promotes creating a uniform interface. That is, how you address items in an ADO.NET Data Service (i.e. how to construct URIs), how to interact with data (using HTTP verbs), etc is the same across any ADO.NET Data Service, regardless of the data it exposes. This uniform interface enables code reuse against your web services such that one can create reusable client libraries and UI widgets for all their services. For example, the ADO.NET Data Service team is doing this by shipping .NET , Silver light, AJAX, etc libraries which can talk to any data service. In addition, this feature (uniform interface) enables us to add features such as LINQ to ADO.NET Data Services since the translation of LINQ query statements to URIs is stable and well known.

This is already probably a bit too long Smile, but in addition to the items noted above, additional advantages of REST-based approaches also apply such as rich integration with HTTP such that you can leverage existing HTTP infrastructure (ex. HTTP Proxies) deployed at large …

I hope that helps….
~ Mike

Here are a few links for those who don’t know about REST Service.  

Hope you find it useful.
Related ~

Ascgen2 - OpenSource Image to Text (ASCII) Converter

I found this awesome opensource image to ASCII converter from lifthacker blog. This project is hosted in SourceForge <link> and is completely written in C#. This project is released under GPL license and you can download the executable and sourcecode from SourceForge with free of charges. Here is the technique used in this tool.

Original Image

Tifa - Final Fantasy Girl

Generated Image

ASCII Girl

The image above is generated by uisng Ascgen2. If you want to take a look the generated HTML version, you can check this link. (Demo : http://michaelsync.net/demo/ASCII-tifa.html )

Credit : I got Tifa Lockhart’s photo from Google Image Search. Full credits go to the original creator.

BTW, this girl is animated but I think she is hot. Wat ya say?

Related ~

Script#: C# to Javascript Converter

Have you heard about Script#? I heard about this toolkit last week even Nikhil started this project last year. I knew that there is a Java-to-Javascript converter called GWT (Google Web Toolkit) in Java World since long time back and I thought that it might be good if we, the C# developers, also have that kinda tools for ASP.NET web development. Now, the dream come true. Nikhil created Script# project that can convert the C# code to Javascript. I think it is pretty interesting (and strange ) tool and I wonder how Script# will convert the C# code to Javascript. Anyway, I started learning about Script# on last Friday. I’m gonna share what I have learnt about it so far. If you are already familiar with this tool, please share your thoughts about this tool. Thanks.

Introduction

Script# is a compiler that generate the Javascript instead of MSIL (Microsoft Intermediate Language) from C# sourcecode. Like GWT (Google Web Toolkit) that can convert the Java code to browser-compliant JavaScript and HTML, Script# is able to convert the C# codes to Javascript (either human-readable format or compact one). It is the best tool for those who hate to write the Javascript in HTML view.

Sourcecode Download : SSharp.zip

Example 1 : Getting Started with Script#

  • Download the ScriptSharp.zip from this link.
  • Extract it and double-click ScriptSharp.msi to install the Script# (You should note that Script# is currently available for Microsoft Visual Studio 2005. If you wanna use Script# with Visual Studio 2008, please check-out this post.)
  • Launch the Microsoft Visual Studio 2005 IDE and let’s create very sample Script# project
    Note: I recommended you to run the VS 2005 IDE as an administrator if you are using Windows Vista series.

  • Click “Script#-Enabled Web site” Project Template from “New Web Site” dialog (File>New>Web Site)
  • We will create one button named “clickMeButton” and the div called “greetingDIV” within
    tag.
    
    <div>
    <input type="button"  id="clickmeButton" value= "Click Me" />
    <br />
    <br />
    <div id="greetingDIV" class="divbox">
    Hello buddy!!
    </div>
    </div>
    
  • Go to the design-view and right-click on “Scriptlet” control as picture belowScript# - Scriptlet Control
  • Select “Edit C# Code” on content menu.
  • Paste the following code in Scriptlet Editor
    
    using System.DHTML;
    using ScriptFX;
    using ScriptFX.UI;public class MyScriptlet : IDisposable {private DOMEventHandler _clickHandler;
    
    private MyScriptlet(ScriptletArguments arguments) {
    _clickHandler = new DOMEventHandler(OnClickMeButton_Click);
    
    DOMElement clickMeButton = Document.GetElementById("clickmeButton");
    clickMeButton.AttachEvent("onclick", _clickHandler);
    }
    
    public static void Main(ScriptletArguments arguments) {
    MyScriptlet scriptlet = new MyScriptlet(arguments);
    
    }
    
    public void Dispose() {
    if (_clickHandler != null) {
    DOMElement okButton = Document.GetElementById("clickmeButton");
    okButton.DetachEvent("onclick", _clickHandler);
    _clickHandler = null;
    }
    }
    
    private void OnClickMeButton_Click() {
    DOMElement divGreeting = Document.GetElementById("greetingDIV");
    divGreeting.Style.Display = "block";
    }
    }
    

    Script# - Scriptlet Editor

  • Click “Save and Close” on Scriptlet Editor
  • Build the web application and Press “F5″ to run the application
  • (There is one button on the page.) Click this button.
  • “Hello Buddy!” message will be shown as picture below.Script# - Example 1

That’s.. You just created one script#-enabled webpage. Do you want to know what code Script# generated from your C# code? It’s easy. Just go to “View Source” and you will see the following script which is generated by Script#.


<script type="text/javascript">
//<![CDATA[
window.main = function main() {
Type.createNamespace('Scriptlet');

////////////////////////////////////////////////////////////////////////////////
// Scriptlet.MyScriptlet

Scriptlet.MyScriptlet = function Scriptlet_MyScriptlet(arguments) {
this._clickHandler = Delegate.create(this, this._onClickMeButton_Click);
var clickMeButton = $('clickmeButton');
clickMeButton.attachEvent('onclick', this._clickHandler);
}
Scriptlet.MyScriptlet.main = function Scriptlet_MyScriptlet$main(arguments) {
var scriptlet = new Scriptlet.MyScriptlet(arguments);
}
Scriptlet.MyScriptlet.prototype = {
_clickHandler: null,

dispose: function Scriptlet_MyScriptlet$dispose() {
if (this._clickHandler) {
var okButton = $('clickmeButton');
okButton.detachEvent('onclick', this._clickHandler);
this._clickHandler = null;
}
},

_onClickMeButton_Click: function Scriptlet_MyScriptlet$_onClickMeButton_Click() {
var divGreeting = $('greetingDIV');
divGreeting.style.display = 'block';
}
}

Scriptlet.MyScriptlet.createClass('Scriptlet.MyScriptlet', null, IDisposable);

// ---- Do not remove this footer ----
// Generated using Script# v0.4.2.0 (http://projects.nikhilk.net)
// -----------------------------------

ScriptFX.Application.current.run(Scriptlet.MyScriptlet);
}
ScriptHost.initialize([
'App_Scripts/ssfx.Core.js',
'App_Scripts/ssfx.UI.Forms.js'
]);
//]]>
</script>

Don’t you think that the generated Javascript code looks so similar to your C# code that you wrote in Scriptlet Editor? Yes. This is one of the advantages of using Script#. It can generate the human-readable Javascript that has the same structure as your C# code. If you are not sure how to write the object-oriented code in Javascript, you can just write the code in C# with the rich features such as IntelliSense, refactoring, compile-time and let Script# convert the C# code to the object-oriented Javascript code.

Note: The sample is already attached in this post. Please check-out “Example1.aspx” in zip file.

Okay. We’ve just done one sample with Script#. As the project is in very early stage, I notice that there are a few weak points and bugs in that project while I’m learning. And also, I’m kinda agreed with Dimitri Glazkov regarding on Script# project. (Check-out his post here.) Anyway, let’s learn more about Script# and we’ll see whether we should use it in real project or not.

Example 2 : Script# Ajax

  • Create the another Script#-enabled project
  • Add the “Generic Handler” to your project and name it “ExampleWebHandler.ashx”
  • Paste the following code in “ProcessRequest (HttpContext context)” function.
    
    context.Response.ContentType = "text/xml";
    context.Response.Write("Hi " + HttpUtility.HtmlEncode(context.Request.QueryString["name"]) + "!");
    

    Note: What this code does is that write the “Hi” after appending the name that came as a parameter in response.

  • Add one textbox to accept the user inputs, one button to invoke the server-side script and the div for displaying the result
    
    <div>
    Please Enter your name : &nbsp;&nbsp;
    <input type="text" id="nameTextBox" /> &nbsp;&nbsp;
    <input type="button" id="sayHiButton" value="Say Hi!!"/> <br /><br />
    <div id="result">
    </div>
    </div>
    
  • Add the argument to your scriptlet control. (Right-click on Scriptlet control and select “Edit” Arguments. then, Add one member (Name: name and Value: ExampleWebHandler.ashx?name={0}))

    Edit Arguments - ScriptletArgument Collection Editor

  • then, Click “OK” to close the “ScriptletArgument Collection Editor”
  • Paste the following code in “Scriptlet Editor”
    
    using System;
    using System.DHTML;
    using ScriptFX;
    using ScriptFX.UI;
    using ScriptFX.Net;
    
    public class MyScriptlet : IDisposable {
    
    private string _urlName;
    private DOMEventHandler _clickHandler;
    private XMLHttpRequest _request;
    DOMElement resultDIV = null;
    
    public static void Main(ScriptletArguments arguments) {
    MyScriptlet scriptlet = new MyScriptlet(arguments);
    }
    
    public void Dispose() {
    if (_clickHandler != null) {
    DOMElement okButton = Document.GetElementById("sayHiButton");
    okButton.DetachEvent("onclick", _clickHandler);
    _clickHandler = null;
    }
    if (_request != null) {
    _request.Onreadystatechange = (Callback)Delegate.Null;
    _request.Abort();
    _request = null;
    }
    }
    
    private MyScriptlet(ScriptletArguments arguments) {
    _urlName = arguments.name;
    
    _clickHandler = new DOMEventHandler(OnSayHiButton_Click);
    
    DOMElement clickMeButton = Document.GetElementById("sayHiButton");
    clickMeButton.AttachEvent("onclick", _clickHandler);
    }
    
    private void OnSayHiButton_Click() {
    InputElement nameTextBox = (InputElement)Document.GetElementById("nameTextBox");
    resultDIV = Document.GetElementById("result");
    resultDIV.Style.Display = "block";
    
    _request = new XMLHttpRequest();
    _request.Onreadystatechange = this.OnRequestComplete;
    _request.Open("GET", String.Format(_urlName, nameTextBox.Value.Escape()), /* async */ true);
    _request.Send(null);
    }
    
    private void OnRequestComplete() {
    if (_request.ReadyState == 4) {
    //if (_request.Status == 200) {
    _request.Onreadystatechange = (Callback)Delegate.Null;
    if (resultDIV != null) {
    resultDIV.ClassName ="divbox";
    resultDIV.InnerHTML = _request.ResponseText;
    }
    _request = null;
    // }
    }
    else {
    if (resultDIV != null) resultDIV.InnerHTML = @"<img src=""./images/indicator_technorati.gif"">";
    }
    }
    }
    

    Note: I assumed that you already have some ideas about Ajax before reading this article.

  • Build the application and run it. (You will see one textbox and one button as you have added on the page.)
  • Type the name you like
  • Click “Say Hi!” button. (You will see the result as below with the name that you enter.)

This demo is very sample that shows the way how to communicate between Script# code and the Server-side code. You can probably extends the web handler to get the more features as you need for your Script#-enabled application.

Debugging the Script#-enabled application

For IE Users, Go to “Debug->Windows->Script Explorer” or Press “Ctl+Alt+N” while you are running the project. You will see the list of script files that are included in page. Select the script file that you wanna debug and set the breakpoint. You know how to debug the Javascript with Visual Studio 2005, right?

For Firefox Users, Firebug is the best tool for debugging the Javascript.

Yeah. It is so sad to say that you are not able to debug the C# code that you wrote. Instead, you will be debugging the Javascript code which is generated by Script# compiler.. It makes you feel like debugging the MSIL code after writing the C# in IDE even the generated code is so much like the C# code that you wrote and human-readable but it is by-design so we can do nothing.

Conclusion

I’m gonna stop learning the Script# project for today. I’ll read about building the Script# library and Vista Sidebar Gadget and will post them in my blog. For the time being, I do have a few disappointments in using Script#. However, I will look more information about this project and I will share the conclusion with you.. If you are also learning this project like me, please let me know. We can probably discuss more about this project.. Thanks…

More Information about Script# ~

How-to convert DVD to iPod: PQ DVD to iPod Video Converter Software. DVD to MP4 Download PQ DVD to iPod Video Converter Software. One click to convert unlimited number of DVD movies, TV shows, online videos to iPod Nano, Touch …

Free Awesome ProgressBar in C#

SQL Server 2005 Circular Progress Bar

Download : http://www.codeproject.com/vb/net/sql2005circularprogress.asp

Author : ateece

A progress disk similar to that in SQL Server 2005

Download : http://www.codeproject.com/cs/miscctrl/ProgressDisk.asp

Author : Amr Elsehemy

Status List - Vista Style

Download : http://www.codeproject.com/useritems/Status_List.asp

Author : Shahpour

Extended .NET Controls

Download : http://www.codeproject.com/cs/miscctrl/exdotnet.asp

Author : Johnny Hooyberghs

Never-ending Progress Bar (C#)

Download : http://www.codeproject.com/cs/miscctrl/C_NeverEndingPBar.asp

Author : GregOsborne

Building a Progress Bar that Doesn’t Progress

Download : http://msdn.microsoft.com/msdnmag/issues/04/10/AdvancedBasics/default.aspx

Author : Duncan Mackenzie

What is TypeForwardedToAttribute?

Note: The actual class name is TypeForwardedToAttribute. (not TypeForwardedToAttributes )

TypeForwardedToAttribute class is new class in .NET framework 2.0. It helps you to move the existing classes (types) from one assembly to another without breaking to the existing application.

Before this feature is not available in .NET framework, it’s too much work if we wanna move the existing classes to another assembly for any reason because it can’t be done without recompiling the existing applications which are using that assembly. For example, there are one class called Class1 in assembly1. There are one window application called WinApp which is using that assembly “assembly1″. We wanna move that class “Class1″ from assembly1 to another assembly called “assembly2″. In order to do that, we have to remove that class from assembly and add it to assembly2. Then, we have to add this new assembly as a reference to WinApp. Then, we have to recompile this application again. It’s gonna be the problem if we don’t have the source code of WinApp. Even we have the source code, it’s like too work to do.

Now, things has changed. TypeForwardedToAttribute has come for this need. I will show you how this class is useful with the following demonstration (or steps)

  1. Create a new class library called “ClassLibrary1″ in Visual Studio .NET 2005.(There will be one class called Class1 already included in this class library.)
  2. Write one public method (eg: Method1() ) in that class “Class1″.
  3. Write one piece of code to show the messagebox when this method is invoked.
  4. Add Window application in Solution Explorer
  5. Add ClassLibrary1 as a reference to Window application
  6. Add one button on winform.
  7. Invoke the method from Class1 in the click event of this button. (eg: ClassLibrary1.Class1.Method1(); )
  8. Build and Run the application. (Check whether the messagebox is shown or not in button’s click.)
  9. End the running.
  10. Remove the window application. (we already ensure that this window application is working fine with ClassLibrary1.Class1.Method1(); If you wanna ensure more, you can run and test the executable file of window application under bin/debug folder. )
  11. Add new class library project called “ClassLibrary2″ in Solution Explorer.
  12. Move Class1 from ClassLibrary1 to ClassLibrary2. (You should note that the name of namespace must not be changed. )
  13. Add ClassLibrary2 as a reference to ClassLibrary1 project.
  14. Open the assembly.cs in ClassLibrary1 project (this file is under the properties folder of project file.)
  15. Add the following code in assembly.cs of ClassLibrary1
    [assembly: TypeForwardedTo(typeof(ClassLibrary1.Class1))]
  16. Recompile the ClassLibrary1 and ClassLibrary2. ( it’s not necessary to recompile the window application which is using ClassLibrary1. )
  17. Copy the ClassLibrary1.dll and ClassLibrary2.dll from bin/debug/ folders.
  18. Place them into bin/debug folder of window application.
  19. Then, run the exe file (eg: windowapplication.exe) and check whether the messagebox is shown or not. (I’m sure that your window application works just fine and you will see the msgbox. :) )

So, We dont need to touch Window application for adding ClassLibrary2.dll. Window application keep using ClassLibrary1. When window application requests the type to ClassLibrary1 then ClassLibrary1 will forword to ClassLibrary2 by using TypeForwardedToAttribute. So, it’s not necessary to recompile the window application.. It makes the developers’ lift easier. :)
Okay. That’s all from my side. What do you think? If you have any question for this class or my explanation or the steps mentioned in my article, please feel free to let me know.

Thanks.

AssemblyVersion - BuildNo Limitation

I was trying to compile a new build of our project today morning. We used to give the build no of our project’s assembly in YYMMDD format. (Build No “70112″ for 12th January,2007). So, I changed the version no of assembly to “2.2.70112.2″ [<major version>.<minor version>.<build number>.<revision>] (More Info) before compiling the project.

When I tried to compile, I got the following error.

Error emitting ‘System.Reflection.AssemblyVersionAttribute’ attribute — ‘The version specified ‘2.2.70112.2′ is invalid’

I was so surprised about it. I thought, we can give any number as we like for the version of our assemblies. Then, I googled it and I came to know that there are a lot of people who are facing the same problem. and I also found the reason why this error occur and how we should fix this problem.

Why this problem?

This article said,

Binary version number for the file. The version consists of two 32-bit integers, defined by four 16-bit integers. For example, “FILEVERSION 3,10,0,61″ is translated into two doublewords: 0×0003000a and 0×0000003d, in that order. Therefore, if version is defined by the DWORD values dw1 and dw2, they need to appear in the FILEVERSION statement as follows: HIWORD(dw1), LOWORD(dw1), HIWORD(dw2), LOWORD(dw2).

Solution

This article “Fixing invalid version number problems with the AssemblyInfoTask” said,

The arrival of 2007 bought a flurry of e-mails to the MSBuild team from people having trouble with the AssemblyInfoTask. The symptom is simple to describe - the builds start to fail with the following error:

Error emitting ‘System.Reflection.AssemblyVersionAttribute’ attribute — ‘The version specified ‘1.0.70102.1′ is invalid

The fix to get builds going again is to change the date format used to generate the build number to something other than the default “yyMMdd”. The date formats are in Microsoft.VersionNumber.target, located in %program files%\MSBuild\Microsoft\AssemblyInfoTask, and there are two of them (one for file version and one for assembly version). You can use any format you want. Within Visual Studio we’re now using 01MMdd.

Note that you may have to go in and hand-edit your assemblyinfo.* files to change their version number back to a default starting point of 1.0.0.0 to get your builds going again.

However, I don’t think it’s a solution since we are not able to use the way that we already used to it.
So, Be careful when you are assigning the version of your build. “[assembly: AssemblyVersion("65534.65534.65534.65534")]” is maximum.

References ~
AssemblyFileVersions: 2.0.0.071005 is bad, but 2.0.0.061005 is good
Why are build numbers limited to 65535?
Fixing invalid version number problems with the AssemblyInfoTask