in

Community Blogs

Blogs of different SQL/Developers Community Members

This Blog

Syndication

DamirDobric

rujan 2011 - Posts

  • How to include jQuery Mobile in Monodroid project?


    When working with jQuery Mobile applications you will have to include jQuery Mobile related assets in the javascript or HTML file.
    Following HTML snippet shows how to do that:

    <!DOCTYPE html>

    <html>

           <head>

           <title>DAENET’s Monodroid jQuery Mobile Demo</title>

          

           <meta name="viewport" content="width=device-width, initial-scale=1">

     

           <link rel="stylesheet" href="jQueryMobile/jquery.mobile-1.0b2.min.css" />

           <script type="text/javascript" src="jQueryMobile/jquery-1.6.2.min.js"></script>

           <script type="text/javascript" src="jQueryMobile/jquery.mobile-1.0b2.min.js"></script>

    </head>

     

    <body>
    <a href="http://daenet.de" data-role="button" data-theme="a" data-icon="star">Theme a</a>
    <a href="http://daenet.de" data-role="button" data-theme="b" data-icon="delete">Theme b</a>
    <a href="http://daenet.de" data-role="button" data-theme="c">Theme c</a>
    <a href="http://daenet.de" data-role="button" data-theme="d">Theme c</a>
    <a href="http://daenet.de" data-role="button" data-theme="e">Theme c</a>

    <body>

    To make this working, you will have to add all jQuery related staff to assets folder.

    image

    This is in fact all you have to do to make it running. Unfortunately this example will not work on Android, but it will work on Windows Phone, Windows 8 and common desktop based web application. When you start the code shown above, you will see following result:

    image

    This means that jQuery has not been loaded correctly.The reason for that is that Android asset loading routines are case-sensitive. If you carefully take a look on the
    name of jquery-mobile asset folder you will find this name: “jquerymobile” (see picture above).

    All include files use name jQueryMobile:

    <link rel="stylesheet" href="jQueryMobile/jquery.mobile-1.0b2.min.css" />

    To make it working change all of them as shown below:

    <link rel="stylesheet" href="jquerymobile/jquery.mobile-1.0b2.min.css" />

    <script type="text/javascript" src="jquerymobile/jquery-1.6.2.min.js"></script>

    <script type="text/javascript" src="jquerymobile/jquery.mobile-1.0b2.min.js"></script>

    Start application again and this is the result:

    image

    Recap: If you are implementing the HTML5 application which should support all platforms, you should build everything case-sensitive.

  • HTML5 for Windows Phone 7.1+ - Episode II : Browsing HTML content

    As already mentioned in the previous post  (Episode I) Windows Phone 7.1 has built in Internet Explorer 9. Because this version is the almost e one as IE9 desktop edition, WP is able to render HTML5 content. Comparing to Chrome is the HTML5 support score still not high, but some of important features like geo-location, canvas etc. works well. As long Widows Phone is executing the HTML5 application which is hosted on some web server, it is not a big deal to open IE on phone and to navigate to the URL of the HTML5 web application.

    Browsing application as web page


    In general you will probably want create you own Silverlight APP, which will browse the same page. In this case you will use the WebBrowserControl and point its source to the wanted page. When you create the new Windows Phone Application, just add the WebBrowserControl as a child of the ContentPanel.

    image

    Additionally put following code in Main_Loaded (or somewhere else) and explicitly navigate to application-uri.

     void MainPage_Loaded(object sender, RoutedEventArgs e)
     {

          webBrowser1.Navigate(new Uri("http://daenet.de/myhtml5app.htm", UriKind.Relative));

     }

    If all works fine, the application will be rendered in the browser control. Following picture shows the application built with jQuery Mobile.

    If this is what you want to achieve you are done.Unfortunately, by default one real APP should be installed on device. This is because there are many scenarios in which network is not required at all. In this case your browser control cannot connect to the application hosted somewhere else. Additionally, if you deploy your HTML application to device it will behave as real Silverlight application. You can use marketplace, updates, purchasing etc., etc.. By using of one HTML web application only application shell will be included in proposed application life cycle. If you don’t care about this just ask yourself one question: “How are you going to prevent users to use your web application if they didn’t purchase the app?”. image

    Browsing application from string content

    Anyhow, if the goal is to bring the Web Application to the phone to became the real APP you need to do much more. Because of the way how Windows Phone deal with files which belong to the APP, there are bunch problems which we have to solve, to make this working.

    Fortunately, WebBrowserControl provides two additional methods (ways) to execute HTML based page. First method is by using NavigateToString(htmlPage).
    This method will force the control to render and execute the code in htmlPage.

    image_thumb3

    This is very simple and it works fine. At least as long you app is very small app. Imagine, you have to put all you code in simple string. Then you have to reference additional scripts or some jQuery add ins shared usually across different folders under application root. Theoretically this would work, but preparing of such application would require a tool which do all tricky staff. No question about debugging.

    Browsing application from device

    As already mentioned the goal in this post is to make real APP deployed on the phone which will for sure pass market place verification process. At the beginning you have to be aware of one thing. Currently there is no way for WebBrowserControl to navigate to HTML file which is located somewhere in file system at the phone.

    Imagine you would put all HTML, javascript and media content in some project folder like HTML. If you select build action for each file under HTML folder to “Copy Allways” files will be copied to output folder, but they will not become the part of deployment. Remember you need all content to be a part of XAP.
    Another solution would be to embed files as content. This would make files a part of XAP, but  the method
                                                     Navigate(new Uri(“Button.htm”));
    wouldn’t have any effect.
    So what to do? I figured out that Navigate work if the navigating file is placed in isolated Storage. So I implemented a peace of code which takes make file from application folder copy it to Isolated Storage.
    Interstingly, there is a method GetResourceStream()which is able to grab the stream of a file located in the appllication’s installation folder. Following example shows how to do that:

    StreamResourceInfo streamInfo = Application.GetResourceStream(fileResource);

    Stream fileStream = streamInfo.Stream;

    image

    Now, I have implemented the method which copies this stream to Isolated storage:

      private static void copyFile(IsolatedStorageFile isoFile, string webResourceFileName, Stream webResourceStream)
      {
               webResourceFileName = createRequiredDirectory(isoFile, webResourceFileName);


                using (IsolatedStorageFileStream isoFileStream = isoFile.OpenFile(webResourceFileName, FileMode.Create))
                {
                   
    byte[] buffer = new byte[1024];

                    int readBytes;

                    do
                    {
                        readBytes = webResourceStream.Read(buffer, 0, buffer.Length);
                        isoFileStream.Write(buffer, 0, readBytes);
                    }
    while (readBytes > 0);
                   

                    isoFileStream.Flush();

                    isoFileStream.Close();
                }
    }

    I do not want to comment all hidden details here, but this is the principal how to do it. One more thing is important here. The things are getting more complicated, when you have to build a real application. Real application will probably require some libraries shared in folders. For example jQuery Mobile use subfolders to store style sheets and images.
    If you have all this, you will have to copy all files to exactly the same position as in output folder (in fact project folder). I did it and all worked fine with WP6.5 widgets (mobility day 2009 – Zagreb), HTML5, jQuery and jQuery Mobile.

    Last but not least, I implemented a small library called Daenet.WidgetLibrary, which has one public static method LoadHtmlStaff(). This method has to be called at the beginning of you application. The method will copy all files under the folder HTML to exactly same folder structure in isolated storage.
    All other you have to do is, drop the Web Browser control in Silverlight application and navigate to the start page.
    Following code shows the native shell application in Silverlight for Windows Phone

    public MainPage()
    {

                WidgetLibrary.LoadHtmlStaff();

                InitializeComponent();

     

                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }

     

            void MainPage_Loaded(object sender, RoutedEventArgs e)

            {
           

                webBrowser1.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(webBrowser1_NavigationFailed);

                webBrowser1.Navigate(new Uri("RootPage.htm", UriKind.Relative));
    }


    Your HTML application will be started

    by invoking webBrowser1.Navigate(new Uri("RootPage.htm", UriKind.Relative));

    Hope this helps you a bit to start up with Windows Phone as a real host of HTML applications. At the end note, I’m not a real friend of HTML staff, but it opens you the way to target new platforms with one code.
    The assembly Daenet.WidgetLibrary will be downloadable after my session at Mobility Day 2011.


    Damir Smile


  • HTML5 for Windows Phone 7.1+ - Episode I : HTML5 Support

    As long “Windows 8” is moving to BETA build, many Microsoft related developers have started to think about HTML5-story. One of frequently asked questions across world wide web is “Will Windows Phone MANGO support HTML5?”. As a computer freak you will probably expect the answer of type boolean (true/false). If you ever have read the novel The Hitchhiker's Guide to the Galaxy you will definitely remember the magic integer result 42. If you didn’t read it here is the short recap.
    With this story, I wont to express that HTML support is a number between 0 an 450 (according to http://html5test.com/). Windows Pone Mango integrates in fact the IE9, which supports HTML5 with score 141 at this day.

    image To be sure that this Windows Phone Mango also support HTML 5 I just run the test from MANGO image and the result was the same like in a case of IE9 desktop version (figure on left).It seems that Windows Phone Mango will really support HTML5 like big desktop brother IE9 does it.
    After you know that, the next logical question would be like “how about other browsers?”. Without knowing what this score does mean, it is interesting to compare IE with other browsers.
    Following picture shows all desktop browsers at glance.
    image

    As you see the Chrome supports today most of HTML5 features. Next picture shows the current state of upcoming browsers, which are currently in BETA stage.

    image

    Following picture shows the score for common Mobile Browsers:

    image

  • Microsoft, here is what we need!

    This post is related to all Microsoft decision makers who think about future of Windows Development platform.
    If you want to make “Developers, Developers, Developers” happy, this could be the way:

    image

    The picture should symbolically shows what could be the best way for community to target JavaScript and HTML platform by using existing .NET development skills and tools. Of course, not everything will be possible or easy to implement, but we should try. After more than 20 years of development, I have tried more or less almost all Microsoft technologies.The approach shown at picture above could help us build the development  platform which merges all best lessons learned from all technologies.
    For example, if I have some peace of code in C# build as library, I could compile it to javascript.js file which could act as library. Additionally, why not to use the same approach in a case of Silverlight applications. By downloading SL-application we could decide what to stream back to browser: XAP or JavaSccript application.
    The most important in this approach is that JavaScript would be used as assembly language,

    With this approach both .NET and JavaScript developers will be happy, because both groups can, but don’t have to leverage addition tools and skills.
    Moreover, today number of technologies which one developer has to learn is increasing dramatically. Unfortunately  the life-cycle of technologies is getting shorter. This could dramatically degrade the quality of software, after we all have invested lot of work in last decade to make software better.

    Last, but not least:

    Hello, hello, hello
    Is there anybody in there?
    Just nod if you can hear us,
    developers, developers, developers.
    . . .
    Comfortably Numb Lyrics - Pink Floyd

  • Windows 8 “client version” will support Hyper-V

    The new Windows "client" OS named “Windows 8” will support virtualization technology  originally released for Windows Server. Mathew John program manager on Microsoft’s Hyper-V team has authored this post. More about this on Build next week. We're getting ready for BUILD full time right now!!

    image  image

    HyperV09062011_low_ch9.mp4

  • AppFabric Applications - Episode VII: Distributed Task Scheduler

    The Task Scheduler Service is one of external services provided out-of-the-box by AppFabric Applications. It is implemented as stateful (see Episode III) service that allows you to remotely trigger scheduled tasks. The task  is wrapped up by class  DistributedTask and can operate at defined times or regular intervals. The task-service triggers a callback defined within the task on the specified schedule.
    This service is useful to schedule any task I reliable manner. In typical scenario you would use some kind of service hosted for example in Service Control Manager or simply define the schedule task in operative system which would execute some code. It is interesting that everybody use such scenarios, but we often do no think about scaling such task by building of fall-back mechanism. Imagine you have to perform tasks such as sending out a daily report or updating statistics every hour. How this would simple requirement would be implemented to run on two or more machines in parallel? I’m glad to hear any suggestion related to this problem.

    Here is the solution which is still in design, but it gives an idea about, how this could work in the near future. Distributed Task is by definition scaled over multiple nodes. it is implemented as stateful service and has ability to synchronize its state between instances on all nodes. Exactly this synchronization is design challenge by implementing task pattern. Fortunately, AppFabric Applications offers Stateful-Services. That means, Task Scheduler is implemented on top of stateful service.

    Following picture shows the architecture of Task Scheduler. When the task is started it is span across multiple machines. This is defined by ScaleoutCount on container level.

    image

    Once the start time is reached the Task Scheduler will send the message to endpoint which has been previously configured. First message is sent to the Execution Endpoint when task is triggered. Second endpoint receives second message which is send after the task is completed. The implementation of task could be implemented in Execution Endpoint.

    Following code shows how to start one task which starts immediately and recurs every 25 seconds. The task registers also both callback endpoints.

    TaskSchedulerClient client = ServiceReferences.CreateImport1("Tasks");

    DistributedTask taskToCreate = new DistributedTask();

    taskToCreate.ExecutionEndPoint =
    new HttpCallbackEndPoint(new Uri(executionUrl));


    taskToCreate.
    CompletionEndPoint =

    new HttpCallbackEndPoint(new Uri(completionUrl));


    taskToCreate.
    Recurrence =
    TaskRecurrence.FromSeconds(25);

    taskToCreate.StartAfterTimeUTC = DateTime.UtcNow;

    taskToCreate.Payload = UTF8Encoding.UTF8.GetBytes("payload");

    I implemented this code in Default.aspx.cs file of sample ASP.NET Web Application. My callback endpoints are registered as Completion.aspx and Execution.aspx pages.

    image   image

    Following example shows how to grab the URI-s of all pages hosted in this Composite Application:

    var uriBuilder = new UriBuilder(Request.UrlReferrer.Scheme, 
                         Request.UrlReferrer.Host, Request.UrlReferrer.Port);
     

    ServiceGroupDefinition serviceDef = Service.ExecutingService.GetDefinition().ServiceGroupDefinition;


    string
    virtualDir = webServiceGroupDef.VirtualDirectory;

     

    string executionUrl = uriBuilder.ToString() + virtualDir + "/Execution.aspx";

    string completionUrl = uriBuilder.ToString() + virtualDir + "/Completion.aspx";

    Steve has also described how to implement Task Scheduling based on Windows Azure classic programming model.

  • NRW Conference 2001 – AppFabric Applications Agenda

     

    AppFabric Introduction

    Windows Server AppFabric short overview

    Windows Azure AppFabric overview

    Programming Models

    NET classic model

    Windows Classic Azure

    AppFabric ComApps new Model for Cloud

    AppFabric Applications Deep Dive

    Composing Applications

    Services, Groups and Containers

    Custom Services

    Demos






    image

  • AppFabric Appliactions: Episode VI - Implementing Custom External Service

    As already mentioned in previous posts AppFabric Applications  helps you to create an application by composing of services. Most technical people assume that service is a Web Service. Similarly, most managers assume that the service is an application which provides some functionality to consumers. In context of AppFabric Applications service can be almost any kind of application. The only constrain is that the application exposed as a service must provide some kind of endpoint. Technically this can be anything as long you are enough creative to invent required endpoint.

    AppFabric applications by definition does not care about technical implementation of your service. This is reasonable, because the service is external to AppFabric Applications toolset. External service can even be another AppFabric Application which exposes some endpoint. That means AppFabric Applications is not responsible to deploy or to monitor external service. All AppFabric Applications needs to know is basically how to consume the external service. In theory consuming of an external “thing” is done via some proxy type. So, if you want to integrate your external service, you will have to provide the proxy type implementation, which is responsible to deal with external service.
    For example, in this post I have an external service named CustomServiceSample. To make it visible to AppFabric Applications, I have “invented” the proxy type called CustomService. Once the composed application is running some component will invoke some method on CustomService (note this is the proxy class) and this method will take a care about interaction with the service. The test application which I have used in this post implements one Code-service which consumes my CustomService.

    image

    To implement the Custom External Service you need to implement two things:

    a) Visual Studio Package VSIX
    b) Custom Service Extensibility Artifacts

    Before we start I recommend also to take a look at this great article posted by Alan.

    The sample implementation described in this post can be downloaded here.

    Create Visual Studio Package

    Remarks: Visual Studio 2010 SP1 SDK required.

    Visual Studio package is required to integrate you custom service in Visual Studio. As you will se later, there are few extensibility artifacts which enable Visual Studio to interact with your service at design time.Create new project and select Other Project types | Visual Studio Extensibility | Visual Studio Package.
    Click ok, then next.

    image       image
    Then choose the language, peek the signing key and optionally enter some package description (recommended).
    image     image

    At the next dialog do not check any of menu, tool and custom editor. AppFabric Application does not need them. Now uncheck test staff. 

    image     image

    Click finish and following will appear. In this dialog click remove content.

    image

    Then Press button Add Content, select MEF Component and your project as shown at the next picture:

    image

    You can now build the solution. After all open output folder and double-click VSIX file, click on Install and finally on Close.

    imageimageimage

    To see if all worked fine restart all instances of VS and go to Tools | Extension Manager. Following should appear.

    image

    Because you know now, how to create the VS - MEF package, remove it and restart visual studio.

    Create Custom Service Extensibility Artifacts

    To implement the custom external service you need to implement four interfaces in the VS MEF package (VSPackage1):

    1.Service Proxy
    First of all you have to decide how to communicate with your service. Whatever your decision is, implement it in this class. The class in this post which implements the service proxy is called CustomService.
    Following code is the full implementation of the CustomService class.

    public class CustomService
    {
           
    private int Prop1 { get; set; }|


            private string Prop2 { get; set; }

            public CustomService(int prop1, string prop2)

            {
                Prop1 = prop1;
                Prop2 = prop2;
            }


            public int DoIt()
            {
                ++Prop1;
               
    Debug.WriteLine(String.Format("{0} - {2}"
    , Prop2, Prop1));
               
    return Prop1;
            }
        }


    When developer wants to consume the service it will do something like this.

    CustomService svc = ServiceReferences.CreateImport1();

    svc.DoIt();

    As you see the implementation of the service doesn’t invoke any external service. AppFabric Applications has no glue about this. Because of that, the implementation of the service can support various implementations like:

    - Consume External Service.
    - Implement all logic internally like in my sample. Note that this pattern will not scale at all.
    - Consume with external service which is itself composite application. In fact, this post also describe how to integrate existing AppFabric Application as the custom service.


    2. ExternalServiceMetadata
    It provides design time information which describe important properties of your service. These are Friendly Name of the service, its description, the icon which will represent the service in Visual Studio, the qualified name of service proxy class and the list of all other artifacts (i.e. assemblies) which are required to run the proxy.
    The class is the abstract one and it looks like shown below:

    public abstract class ExternalServiceMetadata

        {

            public static readonly Dictionary<string, object> DefaultDiagramProperties;

     

            protected ExternalServiceMetadata();

     

            public static DrawingBrush DefaultExternalServiceIcon { get; }

            public static DrawingBrush DefaultSelectedExternalServiceIcon { get; }

            public virtual string Description { get; }

            public Dictionary<string, object> DiagramProperties { get; }

            public abstract string FriendlyName { get; }

            public virtual DrawingBrush Icon { get; }

            public virtual List<string> ProxyArtifacts { get; }

            public virtual string ProxyTypeName { get; }

            public virtual List<string> ReferenceAssemblies { get; }

            public virtual DrawingBrush SelectedIcon { get; }

     

            public virtual ICustomTypeDescriptor GetExportManifestTypeDescriptor(ICustomTypeDescriptor reflectTypeDescriptor);

            protected internal virtual void InitializeExternalService(ExportManifest service);

        }


    The mandatory method is FriendlyName. VS uses this value to show the name of the service in the list of installed services.
    Description provides a more information about the service which also appear in the list of service when the service is selected.
    Icon defines the icon which will represent the service. If you override this property you should also override SelectedIcon too. This one is shown when the user selects the icon.

    ProxyTypeName is the type name of the proxy class (CustomService)

    ReferencedAssemblies contains the list of all assemblies which your service proxy require. Note that the service will be deployed in the cloud and the machine might not have all required references.
    My sample implementation looks like:

    [ExternalServiceExport(typeof(CustomServiceExportDefinition))]
       
    public class CustomServiceMetadata : ExternalServiceMetadata
        {
           
    List<string> m_ProxyArtifacts = new List<string
    >();

           
    List<string> m_ReferencedAssemblies = new List<string
    >();


           
    public override string
    FriendlyName
            {
               
    get { return "CustomServiceSample"
    ; }
            }

           
    public override string
    Description
            {
               
    get
                {
                   
    return "Demonstrate how to build the Custom Service"
    ;
                }
            }

           
    public override System.Windows.Media.DrawingBrush
    Icon
            {
               
    get
                {
                   
    return
    drawIcon();
                }
            }

           
    public override string
    ProxyTypeName
            {
               
    get
                {
                   
    return typeof(CustomService
    ).AssemblyQualifiedName;
                }
            }

           
    public override List<string
    > ReferenceAssemblies
            {
               
    get
                {
                   
    if
    (m_ReferencedAssemblies.Count == 0)
                    {
                        m_ReferencedAssemblies.Add(
    typeof(CustomServiceExportDefinition
    ).Assembly.Location);
                    }

                   
    return
    m_ReferenceAssemblies;
                }
            }


           
    public override List<string
    > ProxyArtifacts
            {
               
    get
                {
                   
    if
    (m_ProxyArtifacts.Count == 0)
                    {
                        m_ProxyArtifacts.Add(
    typeof(CustomServiceExportDefinition
    ).Assembly.Location);
                    }

                   
    return m_ProxyArtifacts;
                }
            }
    }

    3. ServiceExportDefinition
    This is the abstract class which defines any property which can be set on your service within Visual Studio. The instance of this class will be used on runtime when the service endpoint have to be imported by calling ServiceReference.CreateImport(). Additionally this class provide a property which defines the type which will act as service proxy. (In this post CustomService) .
    The class is also the abstract one and it looks like shown below:

    public abstract class ServiceExportDefinition

        {

            protected ServiceExportDefinition();

     

            [Browsable(false)]

            public NamedEndPoint CanonicalAddress { get; internal set; }

            [Browsable(false)]

            public string Category { get; set; }

            [Browsable(false)]

            [OverridableProperty]

            public string CertificateName { get; set; }

            [Browsable(false)]

            public NamedEndPoint ClaimedListenAddress { get; internal set; }

            [Browsable(false)]

            public string ExportingServiceName { get; }

            protected abstract Type ExportType { get; }

            [Browsable(false)]

            public bool IsExternal { get; set; }

            [Browsable(false)]

            public bool IsLocked { get; }

            [Browsable(false)]

            [OverridableProperty]

            public NamedEndPoint ListenAddress { get; set; }

            [RefreshProperties(RefreshProperties.Repaint)]

            [Browsable(false)]

            public string Name { get; set; }

            [DataMember(EmitDefaultValue = false)]

            [Browsable(false)]

            public string[] OverridableProperties { get; internal set; }

            [Browsable(false)]

            [DataMember(EmitDefaultValue = false)]

            public string[] OverridablePropertiesOnlyDuringProvisioning { get; internal set; }

            [Browsable(false)]

            public KeyedCollection<string, Artifact> ProxyArtifacts { get; }

            [Browsable(false)]

            [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

            public Type ProxyType { get; set; }

            [OverridableProperty]

            [Browsable(false)]

            public NamedEndPoint PublishedAddress { get; set; }

            [Browsable(false)]

            public string QualifiedName { get; }

            protected internal Collection<ResourceUsagePolicy> ResourceUsagePolicies { get; }

            [Browsable(false)]

            public Uri SelfLink { get; }

            [Browsable(false)]

            public TransportType TransportType { get; set; }

            [Browsable(false)]

            [OverridableProperty]

            public ServiceExportVisibility Visibility { get; set; }

     

            public override string ToString();

            public bool TryGetParentDefinition<TDefinition>(out TDefinition parentDefinition) where TDefinition : class;

            protected virtual void Validate(ValidationContext context);

        }

    Most important property in this class is ExportType. This property should return the type which implements the custom service proxy.
    Here is my implementation:

    public class CustomServiceExportDefinition : ServiceExportDefinition
        {
          

            protected override Type ExportType

            {
               
    get { return typeof(CustomServiceExport); }
            }

     

            private int m_Prop1 = 11;

     

            public int CustomServiceProp1
            {
               
    get
                {


                    return m_Prop1;
                }
               
    set
                {
                    m_Prop1 =
    value;
                }
            }


            private string m_Prop2 = "Hello";

     

            public string CustomServiceProp2
            {

                get
                {
                   
    return m_Prop2;
                }


                set
                {
                    m_Prop2 =
    value;
                }
            }
        }

    4. CustomServiceExport
    Ween ServiceReference.CreateImport() is invoked on runtime within some service, the method CustomServiceExport.Resolve() is invoked implicitly to create the instance of the service proxy (CustomService). This abstract class delivers the instance of the proxy which will be used to communictae with the external service.

    To explain how all this works, let’s create some CompApp and add the new service reference as shown at following sequence diagrams. First of all, when working with services in AppFabric Applications there are three major steps relevant for topic of this post:

    I  – Add the service
    II – Add the reference to service
    III – Deploy the service
    IV – Run the service

    Each step listed above utilize different extensibility points. Here is how all approximately works:

    Add Service

    image

    The picture shows a diagram of some composed application. If you want to add a new service just click on “Add Service”. As next, the dialog with all registered services will appear.

    image

    As you see the list contains a CustomService named “CustomServiceSample”, which is implemented by me. When developer click on “Add Service” the VS AppFabric Application package will instantiate the implementation of your ExternaServiceMetadata class. By using of that instance VS will first obtain the service description, then the name of the service and finally the icon. This all is needed to make you service appear in the list shown above. Following sequence diagram shows how this work  at the moment.

    image

    Add the reference to service
    At some time the developer will add the reference to custom service.

    image

    When developer clicks on “Custom1” (see picture above) AppFabric Package will again use the instance of ExternalServiceMetadata to obtain the type of the proxy.

    image

    Note that sequences describe above are a bit simplified.I didn’t describe sequences which goes through build process etc. I also didn’t use real object names in the sequence life time. My intension is to describe only sequences relevant to deeply understand how one service in AppFabric Applications works.

    Deploy the service

    During this step all deployment relevant artifacts are collected.

    Run the service

    When the host decides to start the application the container will ask ServiceExportDefinition to provide the type of the service proxy by reading property ExportType. After that the instance the service (service which consumes custom external service) is started and depending on service code at some time the proxy instance will be created. Objects in green represents the code of you AppFabric application which contains the service consumer of custom service. You will invoke CreateImport on auto-generated object ServiceReferences. This class is generated when developer adds the service reference. Finally, the method Resolve of custom implementation of ServiceExport will be called. This is the place where the instance of custom service proxy is created.

    image

     

    Hope this helps.

  • Task Schedule Service exception on BeginDeleteTask

    When working with Task Schedule Service you might get following exception when invoking BeginDeletTask:

    ArgumentException: Value Cannot be null.

    image

    This exception is thrown by executing of following code:

    protected void Button2_Click(object sender, EventArgs e)
            {
               
    DistributedTask task = getTask();

     

                TaskSchedulerClient client = ServiceReferences.CreateImport1("Tasks");
        

               
    IAsyncResult asyncResult = client.BeginDeleteTask(task, cb => { }, null);


                client.EndDeleteTask(asyncResult);
          

            }

        

            private DistributedTask getTask()
            {
               
    TaskSchedulerClient client = ServiceReferences.CreateImport1("Tasks"
    );
               
    IAsyncResult asyncResultAllTasks = client.BeginGetAllTasks(cb =>
                {       
          

                    Debug.WriteLine("");
               

                }, null);

                ReadOnlyCollection<DistributedTask> tasks = client.EndGetAllTasks(asyncResultAllTasks);
              

                 return tasks.Count > 0 ? tasks[0] : null;
            }

    To workaround this issue, insert the yellow line in th code which stops distributed the task.:

    protected void Button2_Click(object sender, EventArgs e)
    {
       DistributedTask task = getTask();

       TaskSchedulerClient client = ServiceReferences.CreateImport1("Tasks");

       task.SelfLink = new Uri(client.EndpointAddress.AbsoluteUri);

       IAsyncResult asyncResult = client.BeginDeleteTask(task, cb => { }, null);

       client.EndDeleteTask(asyncResult);

    }

  • Introduction to AppFabric Applications

    Few weeks ago Microsoft has published the first public CTP related to Application Composition under the name AppFabric Applications. This CTP bundles a set of very interesting scenarios and related which are very important for  all enterprise developers, architects in area of .NET and also BizTalk server.
    Here is the jump list to five articles:

    Episode   I -  Programming Model 
    Episode II – Services and Groups
    Episode III – Stateful Services
    Episode IV – SQL Service
    Episode  V – Deployment

    I will present this topic at following conferences in 2001:

    AppFabric Applications at
    NRW Conf 2011
    09.Sept.2011 Wuppertal

    AppFabric and WCF sessions at
    Advanced Developer Conference
    26.-27. Oktober 2011 in Frankenthal

    AppFabric Applications, queues, topics and more at
    Prio Conference
    02. - 03. November 2011 in Meistersingerhalle Nürnberg

    AppFabric Applications deep dive hosted by
    .NET User Group Frankfurt
    17.Nov.2011 18.30-22.30 Microsoft - Bad Homburg

    Fee invited
    Damir Smile

  • Different behavior of jQuery.unload() in IE and Chrome

    When working with jQuery .unload() function you might figure out that Internet Explorer and Chrome behave differently.
    For example, assume you have defined following handler, which explicitly closes window, when user double-click some element.

      $("document").ready(function () {

     

            $("#el").dblclick(function () {

                window.close();

            });

      $(window).unload(function () {

        
          alert(“unload called”)   

     

        });

    In a case of IE the unload method will be properly invoked. Unfortunately if you use Google Chrome you will figure out that unload() will not be called when Chrome hosted page is opened first time. After you open the same page second time the Chrome will properly invoke the unload function.
    Open means something like:

    window.showModalDialog(uri, window,
    "resizable=yes,scrollbars=yes,status=no, dialogWidth:20px");

    To workaround this issue you need to do following:

    $("document").ready(function () {

        $("#el").dblclick(function () {

           $(window).unload();

           window.close();

    });


    Remarks: If you close the window by clicking on “X” (not by invoking window.close()) all will work properly.
    Posted ruj 02 2011, 02:50 by anonymous
    Filed under:
Copyright of SQL/Developers Community
Powered by Community Server (Commercial Edition), by Telligent Systems