European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European Silverlight 4 Hosting :: Create Custom Control in Silverlight 4

clock October 20, 2011 06:51 by author Scott

In this tutorial, I will show you how to create custom control in Silverlight. First of all, we need to create a Silverlight project. Assume, you already know about it. Just for your reference, create a new project. From the left panel, select Silverlight and chose "Silverlight Application" from the right panel. Give a proper name for your application and solution. Click ok to continue.

Then, once it is done, you need to created a Custom Control. In this example, we will just create a default control without any additional customization. See this image below



To do this, right click on your Silverlight project, from the context menu select "Add" and from the second level context menu click "New Item". This will open the "Add New Item" dialog box.

As shown in the below screen shot, select "Silverlight Templated Control" and give you proper name to the control. Remember that, the "Silverlight Templated Control" is the template for Custom Silverlight control.



Click "Add" button to add the custom control into your project. Once the control creation is done, you will notice two things in the solution explorer. Expand the "Solution Explorer" and there you will find the following things:

1. A "Themes" folder containing a file called "Generic.xaml". This is the default resource file for all of your styles for your controls.

2. A "MyControl.cs" file, which is nothing but the class of your custom control. The class name is the control name.

Note that, if you create multiple controls the IDE will create multiple class files for you with the name of the control. But the resource file will be same. All styles and templates of your control will go into the same file.



The above screenshot will give you better visibility of the files that has been created in our demo application.

Here we will discuss about the class of the Custom control. You will get detailed knowledge on the class in later part of the series. For now just know, every control by default derives from base class called “Control”. You may change the base class to other control depending upon your requirement.

Have a look into the basic code that has been generated for you by the IDE:

using System.Windows.Controls; 

namespace CustomControlDemo
{
    public class MyControl : Control
    {
        public MyControl()
        {
            this.DefaultStyleKey = typeof(MyControl);
        }
    }
}

You will see the above code in the constructor. It takes the control style from the resource file and set it as the default style of the control. More on the class, we will discuss later.

You will find the basic template of the custom control in the Generic.xaml file. Open the file and you will find the below style inside the ResourceDictionary: 

<Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyControl">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
 

The first line describes the TargetType of the style. The second line declares the Template of the control. Third line sets the value of the template. The child of the value is your ControlTemplate. You can design your control template here.

One thing I want to tell you here is that, this is the default template of any control. You can add more style values before starting the template declaration. We will discuss this later.

Let us add the custom control that we created to our main page. To do this, you need to add the XMLNS namespace in the XAML. In our case, it is the project name. Once you declare the namespace, you will be able to access the control easily.

<UserControl x:Class="CustomControlDemo.MainPage"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:d=http://schemas.microsoft.com/expression/blend/2008
    xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
    xmlns:CustomControlDemo="clr-namespace:CustomControlDemo" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Grid x:Name="LayoutRoot" Background="White">
        <CustomControlDemo:MyControl
            Width="200"
            Height="200"
            Background="Yellow"
            BorderBrush="Red"
            BorderThickness="1"/>
    </Grid>
</UserControl>
 

The above code will explain you everything. There we added our custom control named "MyControl" with proper declaration of height and width. If you don't specify the height and width, it will take the whole screen of the application (only for our example).

If you run the application, you will not see anything rather than the blank screen. This is because the control has default transparent background. Hence, we added a background color, border brush and border thickness to the control in the above code.



Once you run the application now, you will see the above UI in your browser. The rectangle is the custom control that we created in this sample. If you modify the control template, it will change the UI here automatically.



European WCF Hosting :: RIA Services and Authentication

clock October 12, 2011 08:22 by author Scott

Authentication is the third in a series of posts covering the key concepts of RIA Services using the Book Club application to digger deeper and go beyond the basics. Links to the first two posts on validation and authorization as well as an overview of the application/source code are at the end of this post.

Authentication Overview

Like authorization, RIA Services provides a higher level programming model, and out-of-the-box, but extensible solution. Authentication answers the question:

"Do these credentials represent a valid user?"

Credentials might be user name and password, or any other piece of data that can be used to verify that the user is who he/she says they are. Generally, a side-effect of authentication is to produce a representation of the user, usually represented as an IPrincipal, as well as establishing an authenticated session for the client to use in making subsequent requests.

RIA Service defines an authentication service as a domain service that implements IAuthetication<TUser> where TUser is application's notion of a user that brings together identity, roles and settings that span across client and server.

RIA Services also provides an out-of-box implementation based on the standard asp.net membership, roles and profile infrastructure services. If you use the business application template, this is all setup for you by default. However RIA Services also lets you implement your own authentication service when you want to use your own custom credential store, or a different authentication mechanism such as OpenID.

This post covers using authentication and the User object on client and server, as well as building a custom forms authentication service that works against the application's data model.

Using Authentication on the Client

I created an inplace-LoginControl with a number of visual states (Unauthenticated, CredentialInput, Authenticating and Authenticated) as shown here.



Authentication functionality is accessed through a class called WebContext on the client. WebContext represents the functionality provided by the home web server to the client application. This is how WebContext is initialized in the application:

public partial class WebContext {

    partial void OnCreated() {
        Authentication = new FormsAuthentication() {
            DomainContext = new AuthenticationContext()
        };
    }
}

The FormsAuthentication implementation uses a DomainContext to work against the corresponding DomainService implementing IAuthentication on the server. We'll see this service implementation below.

Looking at LoginControl implementation, the authentication-related functionality is invoked when the Submit and Logout buttons are clicked:

private void OnSubmitButtonClick(object sender, RoutedEventArgs e) {
    LoginParameters loginParameters =
        new LoginParameters(userNameTextBox.Text, passwordBox.Password);

    WebContextBase.Current.Authentication.Login(loginParameters,
        delegate(LoginOperation operation) {
            if (operation.HasError || (operation.LoginSuccess == false)) {
                MessageBox.Show(...);
                operation.MarkErrorAsHandled();
                return;
            }

            // Use the resulting User object
            userLabel.Text = "Welcome " + WebContext.Current.User.DisplayName;
        }, null);
}

private void OnLogoutButtonClick(object sender, RoutedEventArgs e) {
    WebContextBase.Current.Authentication.Logout(/* throwOnError */ false);
}

The resulting User object can be used imperatively as shown in the code above, or declaratively via data-bindings.

Using Authentication on the Server

The User object can also be used on the server, for example by other domain services. Here is a snippet of code from the BookShelfService:


[RequiresAuthentication]
public class BookShelfService : LinqToEntitiesDomainServiceEx<BookClubEntities> {
    private User _user;

    public BookShelfService(User user) {
        _user = user;
    }

    public IQueryable<Book> GetBooks() {
        return ObjectContext.Books.Where(b => b.MemberID == _user.MemberID).
                                    OrderByDescending(b => b.AddedDate);
    }

    public override void Initialize(DomainServiceContext context) {
        base.Initialize(context);

        // This allows authorization rules to get access to the current user
        AuthorizationContext customAuthContext =
            new AuthorizationContext(context);
        customAuthContext.Items[typeof(User)] = _user;

        AuthorizationContext = customAuthContext;
    }
}

The domain service has been marked with the authorization rule stating the service requires authentication. Consequently, RIA Services will ensure that there is a valid IPrincipal whenever this service is invoked. However, the service also requires a User object to be passed in into constructor, so it can use it when retrieving shared by the current user, or when initializing an AuthorizationContext to pass along the User in into authorization rules.

In order to pass in custom values through the constructor, one needs to implement a custom DomainServiceFactory. The default one only works for domain services with default parameterless constructors. In the application, I have implemented a simple domain service factory, that uses hardcoded logic, but in a larger application, the general idea is to use an IoC container and call into that from the custom DomainServiceFactory.

internal sealed class DomainServiceFactory : IDomainServiceFactory {
    private IDomainServiceFactory _defaultFactory;

    public DomainServiceFactory(IDomainServiceFactory defaultFactory) {
        _defaultFactory = defaultFactory;
    }

    public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context) {
        if ((domainServiceType == typeof(BookShelfService)) ||

            (domainServiceType == typeof(BookClubService))) {
            User currentUser =
                Authentication.GetUser<User, AuthenticationService>(context);

            DomainService domainService =
                (DomainService)Activator.CreateInstance(domainServiceType,
                                                        currentUser);
            domainService.Initialize(context);

            return domainService;
        }

        return _defaultFactory.CreateDomainService(domainServiceType, context);
    }

    public void ReleaseDomainService(DomainService domainService) {
        if ((domainService is BookShelfService) ||
            (domainService is BookClubService)) {
            domainService.Dispose();
        }
        else {
            _defaultFactory.ReleaseDomainService(domainService);
        }
    }

    public static void Setup() {
        // Call this from Global.asax.cs in the Application's Start event handler
        if (!(DomainService.Factory is DomainServiceFactory)) {
            DomainService.Factory =
                new DomainServiceFactory(DomainService.Factory);
        }
    }
}

Notice the use of the helper class, Authentication, that allows you to correctly instantiate the authentication service on the server, invoke it and retrieve the User object corresponding to the current authenticated principal. This helper class is in the RIAEssentials framework (link below). The resulting User object is passed in when constructing BookShelfService.

Book Club Data Model

Before we see the actual Authentication service implementation It is worth taking a quick look at the data model behind the Book Club application:




As you see, one of the tables is the Member table. It is intrinsically tied to various other tables by virtue of multiple associations. It also contains information about the user, such as display name, last login date, joined date etc. As such, I'd like my authentication implementation to use this Member table from my data model directly.

The User Object

One of the key things to think about in your application is what constitutes the User object than spans across client and server. What is the state you want to expose to the client for visualization purposes, and what is the state you want to have quick access to within the context of an authenticated session? These are the questions to ask.


The UserBase object provides the ability to track Name and Roles. The User object in the application is defined as follows to add additional properties:

public class User : UserBase {
    public string DisplayName { get; set; }
    public int MemberID { get; set; }
}

I added DisplayName, so it can be used on the client in the UI. I also added the MemberID, so this information can be used on the server on subsequent requests (for example, when doing authorization to ensure a user can only update a book they own - see the authorization post for that example). The User object will be populated from the Member entity from the data model.

Implementing Authentication

Authentication builds on the same domain services infrastructure you use to define your operations/tasks in your application. There are two approaches to implementing authentication:

1. Derive from the out-of-box AuthenticationService base class. This provides a default implementation that leverages the asp.net membership, roles and profile infrastructure.

2. Implement IAuthentication on your domain service and do whatever you like based on your unique scenarios when implementing Login, Logout and other methods of the interface. This is especially useful if you're not using the asp.net infrastructure services or want to use some custom auth mechanism.

In my case, I want to use my own DAL and its notion of members, so I am going to build my own custom authentication service. However, I don't really want to implement the intricacies of forms authentication, which aren't specific to my application, such as setting up HTTP cookies. I only want to write the parts that interact with my data model (very much in spirit with the rest of RIA Services - focus on your application logic, and not the on-wire or service plumbing).

I am going to use a base class called FormsAuthenticationService which implements the guts of forms authentication, and is provided as part of the RIAEssentials framework, that you can easily reuse in your own applications. With that handy base class, here is all I have to do is implement ValidateCredentials, and produce a valid User object using my data model:

[EnableClientAccess]
public class AuthenticationService : FormsAuthenticationService<User> {

    protected override User ValidateCredentials(string name, string password, string customData) {
        User user = null;
        using (BookClubEntities bookClubObjectContext = new BookClubEntities()) {
            Member member =
                bookClubObjectContext.Members.Where(m => m.MemberAlias == name).
                                              FirstOrDefault();

            if ((member != null) &&
                Authentication.ValidatePassword(password, member.PasswordHash)) {
                user = new User() {
                    Name = name,
                    MemberID = member.MemberID,
                    DisplayName = member.MemberName
                };

                if (member.LoginDate != DateTime.UtcNow.Date) {
                    member.LoginDate = DateTime.UtcNow.Date;
                    bookClubObjectContext.SaveChanges();
                }
            }
        }

        return user;
    }
}

Also note how the validation method tracks the last login date, which is something that is captured within the data model.

In the initial version of the Book Club app, the code was [incorrectly] storing passwords in the database. In reality it was a detail that I had yet to get to. Since I am now writing about authentication, I have fixed this. The database stores password hashes, rather than passwords in clear text. This required a small schema update, so you'll need to recreate the database and run the BookClub.sql SQL script before you run the code.

Any application code that uses the authentication service only depends on the contract defined by IAuthentication (whether it is the server, or the client), giving you freedom to implement what it means to authenticate and produce a User object as you desire.

Authentication over HTTPS

If you use forms authentication or even basic authentication (i.e. anything that transfers a user name/password as clear text from client to server), you would be advised to use HTTPS.

This takes a little bit of setup, i.e. setting up an HTTPS site binding, that goes beyond the scope of this post. However RIA Services makes it easy to declaratively indicate that a particular domain service should only be exposed to the world using a secure endpoint, once you've handled the server configuration.

[EnableClientAccess(RequiresSecureEndpoint = true)]
public class AuthenticationService : FormsAuthenticationService<User> {
}



European Silverlight 4 Hosting :: WCF 4.0 Automatic Formatting with Jquery Ajax

clock October 10, 2011 06:49 by author Scott

at this time I am going to look at Automatic Formatting in WCF 4.0.That is one of the great addition in WCF Web HTTP programming model(WCF RESTful). By using this feature it’s dynamically determine the format for the service operation. Previously, if consumed JSON and XML format for the same operation of the service then must have defined two different operations with explicitly annotated RequestFormat parameter of the WebGetAttribute and WebInvokeAttribute attributes.

For getting json format in WCF 3.5

[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetJsonData();

For getting Xml format in WCF 3.5

[OperationContract]

[WebGet(RequestFormat = WebMessageFormat.Xml)]
string GetXmlData();

Now we have option either go with explicit as above or go with new automatic way .By default Automatic format selection is disable due to backwards compatibility and when it’s enabled, it would automatically get the best format in which to return the response. WCF infrastructure actually checks the type which is contained the request messages of Accept Header. The first priorities for media types, if it’s not found in Accept Header than its checks the content-type of the request message and if content-type would not give the suitable response than it would be used default format setting which is defined by RequestFormat parameter of the WebGetAttribute and WebInvokeAttribute attributes and at the last if there is no any default format setting than it would be used value of the DefaultOutgoingResponseFormat property.

1. Priorities of media types in request message’s Accept Header.
2. The content-type of the request message.
3. The default format setting in the operation.
4. The default format setting in the WebHttpBehavior.

Automatic format selection depends on AutomaticFormatSelectionEnabled property. It can be enabled programmatically or using configuration, for getting the clarification I would like to show example of it with Jquery, using  jquery I will be getting the different  format by calling the same operation of the service, for keeping it simple I am enabling the AutomaticFormatSelectionEnabled through standard endpoints, so let’s start it.

First I am going to create an empty web application JqueryWithWCF and hosting it at IIS.



I am going to add following items in the solution.

- WCFService item named 
RestfulService.svc
-
html page named 
jqueryPage.htm
- jquery scripts
file



We have to add System.ServiceModel.Web
 reference for working with WCF RESTful services.



Now let’s look at the
IRestfulService.cs code

namespace WCFRestfulService
{
    [ServiceContract]
    public interface IrestfulService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/data")]
        string GetData();
    }
}

I added ServiceContract attribute at intrface to expose the service and OperationContract attribute for expose the operation out of the world ,now we have to add WebGet attribute with property name UriTemplate=”/data”, it means, it can be called using UriTemplate property name.

Look at the RestfulService.cs code

namespace WCFRestfulService
{
    public class RestfulService : IrestfulService
    {
        public string GetData()
        {
            return "WCF 4.0 has introduced
            a new property \"automaticFormatSelectionEnabled\"";
        }
    }
}

There is nothing special I did, just implemented IRestfulService interface and return a string.

Here is very key part for enabling the Automatic formate, we have Three different ways to enable the automaticFormatSelectionEnabled ,

1. Using Coding with ServiceHost object we can enable it.
2. Using webhttp behavior option
3. Using the standard endpoints

I am going with standard endpoints, because in standard endpoints we don’t need to configure each and every attribute , it has already configured the some attribute build in , so here is the configuration



As we can see in the above, I have commented behavior and serviceHostEnviroment tag, because we don’t need to service metadata and I have add the standard endpoint with “automaticFormatSelectionEnabled” attribute with value true.

That’s it, we have made a restful service and we can get the JSON or XML format by using single operation.

Now we have to put code at jqueryPage.htm page , here is the code of the page

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        ul{
            border:1px solid black;
            overflow:hidden;
            width:270px;
        }
        li {
            list-style-type:none;
            float:left;
            padding:5px;        
        }
    </style>
    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () {

            // javascript object for getting all the jquery objects
            var pageElements = {
                actionButton: $('#btnAction'),
                xmlRadio: $('#rdoXml'),
                jsonRadio: $('#rdoJson'),
                xmlLabel: $('#lblGetXml'),
                jsonLabel: $('#lblGetJson'),
                isXML: true,
                dataTypeValue: 'XML'                
            };

            // set the button value on page load
            SetButtonValue(pageElements.xmlRadio, pageElements.xmlLabel,
                           pageElements.actionButton);

            //click event of xml radio button
            pageElements.xmlRadio.bind('click', function () {
                pageElements.isXML = true;
                SetButtonValue(pageElements.xmlRadio, pageElements.xmlLabel,
                           pageElements.actionButton);
            });

            //click event for json radio button
            pageElements.jsonRadio.bind('click', function () {
                pageElements.isXML = false;
                SetButtonValue(pageElements.jsonRadio, pageElements.jsonLabe
,

                           pageElements.actionButton);
            });

            //click event of the action button
            pageElements.actionButton.bind('click', function () {

                if (!pageElements.isXML) {
                    pageElements.dataTypeValue = 'JSON';
                } else {
                    pageElements.dataTypeValue = 'XML';
                }

                //jquery ajax method for getting the result
                $.ajax({
                    type: 'GET',
                    url: '/WCFRestfulService/RestfulService.svc/data',
                    contentType: 'application/json; charset=utf-8',                    
                    dataType: pageElements.dataTypeValue,
                    processdata: true,
                    success: function (msg) {                        
                        AjaxSuccess(msg, pageElements.isXML);
                    },
                    error: function (msg) {
                        alert(msg.error);
                    }
                });
            });
        });

        //it will call when the ajax hit successful
        function AjaxSuccess(result,isXML) {
            if (isXML) {
                alert($(result).find('string').text());
            } else {
                alert(result);
            }
        }

        //set button value on click on radio buttons
        function SetButtonValue(elem,label,button) {
            var buttonAction = $('#btnAction');
            if (elem.is(':checked')) {
                button.val(label.text());
            }
        }
    </script>
</head>
<body>    
    <div>
        <ul>            
            <li>
                <input type="radio" name="rdobutton" id="rdoXml"
                 value="Get XML" checked="checked" /></li>
            <li id="lblGetXml">Get XML</li>

            <li>
                <input type="radio" name="rdobutton" id="rdoJson"
                 value="Get JSON" /></li>
            <li id="lblGetJson">Get JSON</li>
        </ul>
        <input type="button" id="btnAction" value="" />
    </div>
</body>
</html>

I have created two radio buttons and a input button, when we hit the button it will call the jquery ajax method and check the pageElements.isXML Boolean value, if its false than JSON format called otherwise XML. For getting the proof i am using firebug, here is the result of firebug when we check radio button with Get XML and Get JSON.



I hope so you enjoyed the post . J



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in