Saturday, October 17, 2009

Expression Blend 3 Sketch Flow : New era in Prototyping … – Part 1

First of all, wishing my all blog readers a very Happy Diwali and wonderful year ahead ! Now its almost a month since I am writing something here, I was totally occupied with Community sessions for last two months, now got some time finally to be here with you all again !

Expression Blend 3 is nothing new for us, I have already talking about it since it was in Preview stage at the time of MIX09 around months of March, you can find more here :

http://pendsevikram.blogspot.com/2009/03/silverlight-3-explore-power-of-blend-3.html

Indian Software giant Infosys also made note of this article and they refer on their blog too : (Thanks Infosys !)

http://www.infosysblogs.com/microsoft/2009/03/blend_3_and_sl_3_preview_avail.html

Today, I am going to talk more on Blend 3 Sketch Flow feature which I never touch in past over here. Offcourse there are several resources on net available on Sketch Flow, but as usual here I will make it simple and straight for you without any confusing technical terms and also I will share right resources on net to refer.

To start Expression Blend 3 Sketch Flow, It is very important to first understand “Why you need Sketch Flow?”, This question may be already there in your mind,let me give you pictorial view of Design-Developer Application Cycle to make my point in front of you :

pic1

pic2

pic3

(Picture taken from http://lore.ua.ac.be/Teaching/SE3BAC/SoftwareSpecCartoon.gif   for just example purpose, it carries its respective copyright to its owner)

Well ! Above picture tell us that there is something went wrong in cycle. In above case, we will focus more on Designer and Developer part. Most of the time we have Best Industry designers with us and Best Industry Application Developers with us, but if there is no flow or smooth communication among them and their work, above things are common observations.

Microsoft as usual took lead to bring down the gap among Designer and Developers and they came up with Expression Blend, We all know now, how Blend and Visual Studio are tightly integrated, You do something there in Blend, you can see changes in Visual Studio and vice-versa.

For Designers, there is always challenge to build interactive prototypes for customers so as to give feel of application to customer in reality, Typically before tools like Blend Sketch Flow, we use to either build POCs (Again we need to put Man efforts in this activity) or we use to build designs in Excel or word, Drawback of this was, it does not helps to exactly put forth our point in front of client since they might not be that interactive and realistic which can give feel of application which we plan to build. Outcome of this is something like the picture above I have shown, You design something, Due to lack of awareness or right tools, something different gets designed and output is totally different than required !

Let me introduce Expression Blend 3 Sketch Flow which will give solution to all above concerns we raised above. All you need is to grab bits of Expression Blend 3 with Sketch Flow which you can find on Expression portal (Do you need url ?)

Once you install, it will show you following templates :

newsketchflow

Now you need to choose “Silverlight 3 SketchFlow Application” template along with your language choice. Then you can see following things :

1. SketchFlow Map :

sketchmap

2. SketchFlow Animation :

sketchanimation

3. Main Designer Window :

loginxaml

So, these are the three main blocks we need to look into more seriously as far as our prototyping is concern. By default you will get one screen and to add rest of it, you can do it via traditional way of adding new xaml pages or you can now take help of Sketch Flow map here like this :

skmap

You can see highlighted menu there above, each icon have its own meaning, let’s see one by one :

new This is for to “Create a Connected Screen”, A New Screen which you can then further connect with the existing screen.

new1 This is for “Connect to existing Screen”, All you need is to just drag-drop the arrow to the target screen to associate. It will represent connection by means of unidirectional blue color arrow.

newcomp This is for “Create and Insert a Component Screen”, Another good feature where you can add particular component which you feel is potential in your design workflow.

visualtag This is “Change Visual Tag” and very useful to highlight particular screen with some colors, This is given so as to set the priority screens or to highlight important screens or screen with important or same functionality etc. There is no generic guideline for this, however its purely matter of choice of designer !, Available colors are :

colorchoice

Now we are all set to design our prototype screens, So now its time to hunt for Controls, A normal way is we go to either toolbox or do it via XAML or take help of Asset Manager. Let me share this with you, for Sketch Flow, you have a set of unique Sketch Flow Controls which are similar to your traditional Silverlight Controls, Only difference is that they are especially made different as far as appearance is concerned and they look like someone drawn them with Pencil, Pencil shade looks to each control. Since we are building prototype (Which may turn into final design once client approved), it is good to go for Sketch Flow controls.

Point to be noted here is, Sketch Flow controls can have styles and effects like your other controls and last but not least, you can even write the corresponding C#/VB.NET code with them. So now go to Assets Tab and check for Sketch Controls like this :

assets

Note that each control is having extension as “-Sketch”, This is how you can differentiate among normal controls and sketch controls. Now all you need is just drag drop them on your designer and you are good to go !, Well you need to have Microsoft.Expression.Prototyping.SketchControls.dll on your system which you will get once you install Blend 3 Sketch Flow. If you are not able to see the controls for Sketch Flow, you can refer this thread which I started when I was stuck in early preview stages of Blend 3 Sketch Flow(http://social.expression.microsoft.com/Forums/en-US/blend/thread/5babede8-9cf6-4e1f-b968-1576cebb3e88), If that don’t help you, you can post your query on Expression forums and you will get support there by lot of expertise from Microsoft and from other experts.

Well now once you drag-drop controls on designers, then you may have questions like what to do next? Simple answer is just wait for one more day for my Part 2 article where I will cover how navigation works,what all things you can do,how to run this etc and in Part 2 or maybe even in Part 3, I will talk about exporting features, Documentation Features and much more ..so be here everyday to see more insightful visit of Blend 3 Sketch Flow.

I hope you like this Part 1 and it will help you to start your prototype work, Offcourse your designs will be way good than me since I am developer Silverlight MVP and have very average design sense :) ..but still I am sure in coming parts of this article, I will give you some very good inputs which will help you for months to come ahead.(The way Microsoft coming with its versions, I guess “Months” is a perfect word !!)

Do let me know your feedback and be ready for more in Part 2 and ahead..

Vikram.

Tuesday, September 15, 2009

Silverlight 3 DataGrid : Beyond Databinding …

First of all, Thank You all for your wonderful response for my last series on Silverlight 3 RIA Services for your LOB applications. When Silverlight 3 RTW was in place, before that time when it was in Beta, I wrote a series of articles on various capabilities in Silverlight 3 which includes DataForm,DataGrid and much more like pulling and pushing real data via WCF services to Database and vice-versa in very effective way.I am happy to tell that those articles still getting massive hits which I came to know recently from analytics. Thanks once again for your feedback.

Well, Today I am going to discuss few things which you generally “may” not have found in books or other places but which are equally important in terms of day to day business apps. Recently while doing few POCs, I got lot of feedbacks and common questions from customers about DataGrid which I am trying my best to address those in this article. I am though not much going to talk on PageCollectionView, Sorting and Grouping, I might cover those things in upcoming articles.

1. How Do I change Color of DataGrid Header ?

Well, for Background color you need to very much depend upon VSM (Visual State Manager) since directly Background property to header is not available. However with Style you can set/override foreground color of Header Text like this : (I am giving quick solution where I am talking about applying styles in limited scope and not globally)

xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"

First you need to incorporate above namespace. The you can declare resource like this :

<UserControl.Resources>                         
    <Style TargetType="primitives:DataGridColumnHeader" x:Name="Vikram">
            <Setter Property="Foreground" Value="Red"/>                
    </Style>
</UserControl.Resources>

Then next step is to apply this Style to actual column like this:

<data:DataGridTextColumn Binding="{Binding FirstName}" HeaderStyle="{StaticResource Vikram}" Header="FirstName" />

And output will look like this :

HeaderStyle

2. Adding “Hand” Cursor to Header via Styles and without any code :

Some of you dropped me mail asking this requirement, Well this is certainly interesting and out of the box, Since Hand cursor should get displayed on Header part only and not on Rows, If you write like :

private void dg_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

This line of code is not going to help us to get the desired result and hence this time also we are going to take help of Styles directly. Point to be note here is that, if you try to set Cursor property from XAML, your attempts will fail since it does not expose such property. So write style like this below :

<UserControl.Resources>                         
<Style TargetType="primitives:DataGridColumnHeader" x:Name="Vikram">
<Setter Property="Cursor" Value="Hand"/>                               
</Style>
</UserControl.Resources>

Then again apply that style to Column Header as shown above.Note that, once you apply this Cursor, It might take some time/small delay to actually show Hand Cursor only on column header. This will help to display cursor Hand only on Column and not on rest of grid or rows.

3. No Data Display :

Most of the Third-Party Grids like Telerik etc, do provide features like No Data Display Template( I saw such thing for ASP.NET Grids from Telerik), Well it make sense to have such templates especially when you have your ItemSource or e.Result (Output from Service) as null.By default no such template is though available, what I am doing here is explicitly building a class with single property like this :

public class nodata
{
        public string Display { get; set; }        
}

Take little more effort to build a method where we can set message like this :

public List<nodata> NoDataDisplay()
{ 
    List<nodata> ndt = new List<nodata>();
    ndt.Add(new nodata() { Display = "No Data to Display.." });            
    return ndt;
}

Then final logic goes like this :

if (dg.ItemsSource == null)
{
    dg.Columns.Clear();
    dg.ItemsSource = NoDataDisplay();

   DataGridTextColumn textColumn = new DataGridTextColumn();
   textColumn.Header = "FirstName|LastName|Age|Email|SIG|WebCastDate|WebCastTime";
   textColumn.Binding = new Binding("Display");
   dg.Columns.Add(textColumn);

   dg.Height -= 245;
   dg.Width -= 250;

}
else
{
   dg.ItemsSource = GetSIGHeads();
}

Output will look like this :

NormalGrid

And if there is no data then :

NoDataDisplay

When I was scratching the Internet to get solutions on this, I hardly come across any for such requirement. So I went ahead and build my own logic. So I request you all to evaluate it and let me know if there is any better way to do it. Offcourse I will make your suggestion public giving full credit to you :)

4.Columns do get resized but not fully..How to reduce width to make them almost invisible.

Well, for some of my clients following was the situation :

DragCol1

This is the normal layout of grid, now in next situation, if user drag particular column, see what happens :DragCol2

Observe this carefully, User dragging LastName from left to right, As the default behavior it get shrink,But you can see it does not get shrink fully, so it becomes annoying a lot and looks like a stuck up column. So simple work around is to set MinWidth=0 and story ends ! For sample below I have set MinWidth of FirstName to 0 so here is the output :

<data:DataGridTextColumn Binding="{Binding FirstName}" HeaderStyle="{StaticResource Vikram}" Header="FirstName" MinWidth="0" />

DragCol3

Now you can see that there is not stuck up and you can drag any field and almost till respective on right or left will be overlapped.

5. Add Hyperlink to Cell..A Hyperlink and not Hyperlink Button !

Interesting ! a hyperlink and not hyperlink button, so idea is to just click on it and navigate, Any code behind event is not expected. Our job is to make it simple and workable in minimum workarounds and efforts, Solution :

<data:DataGridTemplateColumn>
  <data:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
          <HyperlinkButton Content="Click Me" TargetName="_blank" NavigateUri="http://www.silverlight.net">
           </HyperlinkButton>
       </DataTemplate>
   </data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>

and output will be like this :

Hyperlink

So you can redirect to any desired URL which you want and also you can specify location either same window or in new window by setting TargetName attribute. This is helpful to show Popup kind of window and render ASPX in it. But if you want to pass certain parameters to it, better watch out HTML DOM and limitations to do so before you directly take this as solution.

6. A Jazzy looking button is possible to be put in Grid?

Yes !, all you need to do it is to make use of Expression Design and Design a Jazzy button like this :

Delete

and then just add following code, Offcourse you will get event too for that button to write your code.

<data:DataGridTemplateColumn HeaderStyle="{StaticResource ColHead}">
  <data:DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
        <Button x:Name="btnSave" Click="btnSave_Click">
           <Button.Template>
              <ControlTemplate>
                 <Image Source="Delete.png" Height="30" Width="80"/>
              </ControlTemplate>
           </Button.Template>
        </Button>
     </DataTemplate>
  </data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>

In such cases, be careful about Height and Width since they matter a lot in overall look and feel of the Grid.

7. How will you add Row Details ?

It can be simply added by following XAML Code :

<data:DataGrid.RowDetailsTemplate>
   <DataTemplate>
      <StackPanel Orientation="Horizontal" Background="AliceBlue">
          <TextBlock Width="200" Text="{Binding Email}" />
      </StackPanel>
   </DataTemplate>
</data:DataGrid.RowDetailsTemplate>

Since we have taken TextBlock, Advantage is that we can Wrap big amount of text and also apply various styles to the same. It is generally used to display the Description or Metadata of the particular row, It will be look like this :

RowDetails

Some Unsolved Mysteries for me for Silverlight DataGrid :

1. How to Merge two or more columns where we bind it with some collection?

2. Why there is always / most of the time a blank column look like dummy column getting bind to gird either on left or right, for most of the cases its on right side like this :

Unsolved Mystry

No Intellisense in CellTemplate ?? a Bug or Known Bug??

intellisense

Well, People address this issue as No Intellisense, actually you do get intellisense here but it is like almost not getting anything, ask me why? Simple answers is that this intellisense carries nothing interms of Standard Controls which we are looking ahead to embed it in the same. So work around is to whatever control you want to have inside it, declare it explicitly outside grid and do a copy-paste,what else can be done? :)

Normal Validations of Data in TextBox :

Before saying good bye for today, I would like to also drop a code snippet which many of you have ask me over mail, It is how one can validate certain fields especially Data entered in TextBox. In my old DataGrid article and DataForm article I have address this issue, but what if the TextBox is not part of those control and is independent?

Solution goes like this : I assume one layout where user suppose to enter his Birthdate, Logic to validate the Date part is what I am going to discuss here, the date is real birthdate or not is not part of our discussion.

if (!Regex.IsMatch(txtdob.Text, @"^([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"))
{
      // An Invalid Date format was entered
      registerStatus.Text = "Invalid Date.Follow mm/dd/yyyy";
      txtdob.Select(0, txtdob.Text.Length);
      txtdob.Focus();
}

Do I need to tell more about Regex? I am sure you will be able to do it with multiple types of expressions like for Email, SSN etc. I am using RegisterStatus as error label to set-reset error messages and catching focus on the same control after error and highlighting it with Select( ), This is how it is simple to validate normal textbox controls,which may be part of your Data Entry or Registration of Users kind of applications.

We a talk a lot about small things in DataGrid which we never explore here before and we spend ample of time to bind data by various way. I hope information above will be useful for you and as usual your feedback is most welcome ! I am soon dropping few most post here which will address day to day problems which developers normally face especially if they don’t have any knowledge on Silverlight. So keep checking this place for lots of new things coming with much more interesting topics.

Vikram.

Saturday, August 22, 2009

Silverlight 3 : RIA Services for your LOB Applications – Part 3

I hope the first two part of this series are useful for your development on RIA Services. There is lot more can be done in that. I will recommend you to go once through RIA Services documentation for more information.

In first two parts we understood the basic structure of Silverlight Business Application Template, Then we move ahead with Adding Views and Data binding mechanisms in it. As far as Authentication is concern, Silverlight Business Application Template supports Forms and Windows Authentication, By default its Forms authentication, All Web developers know that, we can set this in Web.Config file under <authentication/> tag by setting its mode attribute.

For your application, the client side configuration is generally placed inside the App.xaml file like this :

<Application.ApplicationLifetimeObjects>
        <app:RiaContext>
            <app:RiaContext.Authentication>
                <appsvc:FormsAuthentication/>                
                <!--<appsvc:WindowsAuthentication/>-->
            </app:RiaContext.Authentication>
        </app:RiaContext>
</Application.ApplicationLifetimeObjects>

For rest of the part for authentication, you already have Views corresponding to Login and User Registration, For accessing various authentication and doing rest of the operation you have three files under your Services folder in Web Project as AuthenticationService,UserInformation,UserRegistrationService. Here UserRegistrationServices internally use Membership model of ASP.NET, If you have your own authentication mechanism (Most of the apps have their own User-Role Model stored in SQL or respective Database) can sync with the corresponding data maybe by means of domain service class again.( Well I am still evaluating which is easy and best, So might be in coming days, I will re-post this authentication part here again). So this is the overall general view about Silverlight Line of Business Applications with RIA Services (Silverlight Business Application Template in our case).

What about existing Applications? What about Reporting ?

I as a Consultant and MVP in community use to get loads of feedback and questions mails from all of you, which is always encouragement to me.

Some of you told me that, They already have something similar in Silverlight 2 (Not RIA, but their own navigation and Architecture,maybe some other patterns or MVVM etc.), Some said they will be happy to upgrade to Silverlight 3 and this template,but some might not. Most of the developers said that they need something like SiteMap or MenuBar control in Silverlight for navigation, especially the developers who working on version 2. I have one link to share with you all where my fellow MVP friend from Mumbai,India his name is Dhaval Faria wrote an article on Menus in Silverlight, you should check this :

http://www.learnitonweb.com/Articles/ReadArticle.aspx?contId=7&page=1

I have already talked a lot on Datagrid and DataForms in past, so do check those articles which can help you to build better views with those controls.

Media and Images :

Views can be enrich by Media and Images, Many of people told me that they fail to find good demos on Image carousels, So Here is one of the best I found so far with source code :

http://www.gleblanc.eu/Blog/post/PlaneProjection-for-3D-effects-Part-III-carousels.aspx

Charting :

Charting is core area of any LOB application, For more deep dive into charting, visit :

http://blogs.msdn.com/delay/archive/2009/04/24/my-new-home-page-extended-updated-collection-of-great-silverlight-and-wpf-charting-resources.aspx

Reporting :

Currently control like ReportViewer is not available with Silverlight, We all know, how important is Reporting feature in any LOB apps, though right now Silverlight is not having any control for reporting, still there are few vendors who came with their own solutions on this issue, Telerik is one of them, I recently come across another one as Magenic, Look what they have in their Webcast : (Search for Reporting in Silverlight in the list)

http://www.magenic.com/Default.aspx?tabid=635

Do you feel ReportViewer control should be there in toolkit? Then you can vote for it here :

http://silverlight.codeplex.com/WorkItem/View.aspx?WorkItemId=1794

I guess this much resources are more than enough to start your Line of Business Application Development. I will be back soon with more on Development and Designing too.

Vikram.

Friday, August 21, 2009

Silverlight 3 Windows 7 GA Countdown for all Windows lovers around the world.

While writing this post..I recollect famous quote “People everywhere love Windows”

My friend and MVP from Pune,India, Anand Khanse who own one of the Best and Big Windows forums in Windows World as “The Windows Club” (Former WinVista Club) was actually looking for some small Blog widget kind of thing to display as a Windows 7 GA Countdown, He tried out few, but then he saw few nice artworks in Silverlight on Web and he then directly decided to do this Silverlight. He called me up and we started this work.But like yours..our passion is also Windows, so we decided to execute this project publicly so that all Windows lovers like you can also share a part !

I made this in Silverlight ( Do I need to tell its Cross Browser? ;-) )

Screenshot :

Capture

You can find this on my blog at Topmost right side. You want it??

You want it, you get it !! :) I made it as simple <IFRAME> so that you can plug it anywhere on web as you want !

Visit for Code : (..and the Best Windows Forums too !! )

http://www.thewindowsclub.com/windows-7-countdown-timer-in-silverlight

Also Anand being a real Techie on Windows platform, He also famous for his all time famous tool which he made publicly available here : (Works for Windows 7 too !)

http://www.thewindowsclub.com/ultimate-windows-tweaker-v2-a-tweak-ui-for-windows-7-vista

Thanks once again to Windows Club Team and Anand Khanse, Also Thanks to all users who already started displaying this counter on their sites and many more thanks to MVPs and MVP Program for all encouragement !

Hats off to Windows4all !! :

A Silverlight Masterpiece is here which runs Out-of-Browser too !!

http://www.windows4all.com/

I have no idea who build it, but I should say its more than a Wonder ! great work !!

Well, I will be soon with my Part 3 on RIA Services, so be here and keep visiting this place for more and more..

Vikram.

Saturday, August 15, 2009

Silverlight 3 : RIA Services for your LOB Applications – Part 2

First of all I wish all my Indian friends a very Happy Independence Day !

In my last article, we talked about What are RIA Services and what Silverlight Business Application template is capable of doing. Today in this part, I am going to show you, how easily you can get data to your views and make a data drive application. Binding Gird,DataForms etc. These topics I have already covered in my old articles in much more depth, So I will just show you the way of doing it easily so as to make you feel comfortable with this project template.

Our first job is to add a View and make it visible over Template. You can add a View by just right clicking on View Folder and say Add New Item and Simply Add Silverlight Control like we do normally in our Silverlight Projects. Once we done it we can see the newly added Employee View like this :

employee

Now we will add a DataGrid control to it so as to bind some data from Database once we click on Employee Tab, so XAML code is like this :

<TextBlock Style="{StaticResource HeaderTextStyle}" HorizontalAlignment="Left"
           Margin="8,8,0,19" Width="212" Text="Employee List" TextWrapping="Wrap"/>      
        <data:DataGrid x:Name="empGrid" Grid.Row="1"/>

Once you have grid in place then next step is to add Data, We are going to add ADO.NET Entity Model for this like we did in past for several occasions. So all you need is to just right click on your Web Project and Add New Item as ADO.NET Entity Data Model like this :

edmx

Now we have Data Model in place, but still how to query our data and fetch it is still a question, So now for that we will add up “Domain Service Class”. Domain Service Class basically builds metadata type like structure for you, So once you associate your Tables to it, It will create CRUD Methods (i.e Basic Data Operations like Insert,Update,Delete) for you automatically like this :

domainservice

dmnsvrc

So you will find following things in Domain Service Class which are generated automatically for you like this :

[EnableClientAccess()]
   public class NwdDomainService : LinqToEntitiesDomainService<NorthwindEntities>
   {

       // TODO: Consider
       // 1. Adding parameters to this method and constraining returned results, and/or
       // 2. Adding query methods taking different parameters.
       public IQueryable<Employees> GetEmployees()
       {
           return this.Context.Employees;
       }

       public void InsertEmployees(Employees employees)
       {
           this.Context.AddToEmployees(employees);
       }

       public void UpdateEmployees(Employees currentEmployees)
       {
           this.Context.AttachAsModified(currentEmployees, this.ChangeSet.GetOriginal(currentEmployees));
       }

       public void DeleteEmployees(Employees employees)
       {
           if ((employees.EntityState == EntityState.Detached))
           {
               this.Context.Attach(employees);
           }
           this.Context.DeleteObject(employees);
       }

}

However this is not at all sufficient if we talking about LOB applications since we many time need customize fetch data based on our own queries, So to handle this, IQueryable<> interface is provided to us, This takes Context as type, so in our case it is like IQueryable<Employees>. So for our own custom query we make use of this along with Linq as and when required, So for example if I want to order my data by region while loading the Grid, I can write my own method in this class like this :

public IQueryable<Employees> GetEmployeesByName()
{
         return this.Context.Employees.OrderBy(e => e.Region);
}

Still if you want exact meaning of IQueryable<> :

 

Provides functionality to evaluate queries against a
specific data source wherein the type of the data is known

But since all this logic is present in Domain Service Class, so we can’t directly bind it unless we create instance of it in our respective Views, So now lets move ahead to Employee View where I have already taken one data grid, Now to bind that I will use following code :

void EmployeeListing_Loaded(object sender, RoutedEventArgs e)
{
      NwdDomainContext nwd = new NwdDomainContext();

      nwd.Load(nwd.GetEmployeesByNameQuery());

      empGrid.ItemsSource = nwd.Employees;           
}

Remember, you need to add the respective reference else it will not allow you to access data. Load() will take care of loading data fired by particular method which we wrote in Domain Service Class and then we will simple bind this to grid and after executing this we will get output like this :

finalgrid

This is how you can bind your data simply and make use of any control, All you need is Design the View and write corresponding method in Domain Service Class which is capable of doing many things (For More info : Please go through RIA Services Documentation)

You try this new thing out and let me know your feedback, Since this is new template for many one, One might feel that why to go for this if we can do this anyhow in Silverlight project without any template,But once you start doing customization then you will realize the power of RIA Services and Total Time saved by using this template. Though I am done over here with the basic use of this Template, Still I am adding one more part to this series which will be sort of discussions and what all things can be done including Reporting in Silverlight, I will also share some good resources which are already made ready by enthusiastic people like you, So keep looking for final part which will fulfill all the things we need in real LOB applications.

Vikram.

Wednesday, August 12, 2009

Silverlight 3 : RIA Services for your LOB Applications – Part 1

Silverlight 2 onwards, there was a boom in web application creation using Silverlight since its media capabilities got big attention from everyone. Then onwards its Charting tools and other rich looking tools created buzz in community as well as people started using it as Web Parts in their Microsoft Sharepoint portals.

There are already several good resources available on Internet which talks about Silverlight Line Of Business Applications (LOB), I am giving here my few cents or you can call it is my first hands on with it. I am now talking about Silverlight Business Application Project Template in detail. People sometime get confuse between RIA Services and Silverlight Business Application, well Business Application template is a way or method to implement it in your business apps, The normal definition of RIA given on Microsoft site where you download template is like this :

Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

I am not going to draw any complex architectural diagram since objective of this post is to implement it rather than understand.( If you ask me why..well anyone who understands what is Tier Architecture can guess what this stuff all about), Basically it gives you Views (Remember Views in MVC ?), It allows you to Add your Silverlight pages as Views, You also can incorporate Data Model with it with help of ADO.NET Entity Data Model, You can then do CRUD Operations on it with Help of Domain Service Class. You can implement Authentication to it either with Role Provider/Membership Model or with your own model of authenticating users.

So what all you need to try this out? Simple answer is download RIA Services Preview from here :

http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en

Once you done with Installation, all you need to do is to Start instance of Visual Studio and go to File –> New and Select the Silverlight Business Application Project,like this :

SLBusinessApp

If you check out Solution Explorer, you will find following structure :

RIASolution

App.xaml and MainPage.xaml files were there always, what’s new you have is three folders as “Assets”,”Libs”,”Views”, Assets folder contains one Styles.xaml file which holds all Style information for the given template and you can customize it if you want (Remember Themes/CSS in ASP.NET ?). Libs will contain all the references which you add, like here since I am making use of DataGrid control, you can find the corresponding DLL file inside it. Views is most important folder in this structure since it contains all the UI, You can see that About,Error,Home,Login,LoginWindow and Password Control are already present in Views by default. EmployeeListing is View added by me, how to add Views that also is simple, just right click on Views->Add New Item and just add Silverlight User Control like the way you use to add it in our normal Silverlight project template. Well, without adding any template if you run you will see following output :

default

If you observe the Address bar carefully while running the output, you don’t need to think much on how it works, you will come to know its nothing but Navigation Framework provided by Silverlight, So its built-in this template to provide smooth navigation among the views. You can see Tab like arrangement for navigation like this :

navigation

Once clicking on this you will be thrown to corresponding Views like this :

content You can change or revamp the View completely as per your choice, What Silverlight Business Application gives you is basic structure to start with and it has all requirements built-in which any business applications are in need like View model and navigation framework and added now with Authentication too, with the login link on top you can invoke Login and User Registration view which is also built-in, like this :

login

register

So if you check out Main.xaml page, you will see the respective code snippets which will allow you to customize it like shown below :

Navigation Support Block :

<Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}">
           <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}"
                             Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
               <navigation:Frame.UriMapper>
                 <uriMapper:UriMapper>
                   <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
                   <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
                 </uriMapper:UriMapper>
               </navigation:Frame.UriMapper>
           </navigation:Frame>
   </Border>

Header Customization Block :

<Border x:Name="BrandingBorder" Style="{StaticResource BrandingBorderStyle}">
         <StackPanel x:Name="BrandingStackPanel" Style="{StaticResource BrandingStackPanelStyle}">

           <ContentControl Style="{StaticResource LogoIcon}"/>
           <TextBlock x:Name="ApplicationNameTextBlock"
            Style="{StaticResource ApplicationNameStyle}"
            Text="Vikram's Line Of Business Application"/>

         </StackPanel>
       </Border>

Look at the Code, you can see how it imports LogoIcon as Static Resource, so you for your application can directly replace it with your company logo, its simple to do.

Adding View to Tab look like layout :

<Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
         <StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">
           <HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}"
            NavigateUri="/Home" TargetName="ContentFrame" Content="home"/>
           <Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>
           <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}"
            NavigateUri="/About" TargetName="ContentFrame" Content="about"/>
           <Rectangle x:Name="Divider2" Style="{StaticResource DividerStyle}"/>
           <HyperlinkButton x:Name="Link3" Style="{StaticResource LinkStyle}"
            NavigateUri="/EmployeeListing" TargetName="ContentFrame" Content="Employee"/>
        </StackPanel>
       </Border>

So, by this time you must have got idea how simple and useful is this, but I know most of you will not be that satisfied unless “Real Data” don’t come in picture, I know this so, have some patience for a while and I will show you how simple is to add data to it by much more flexible and easy way, well is it Linq-to-SQL ? ADO.NET ? WCF? Entity Framework?, keep guessing..I will be back soon with Part 2.

Before going away, If you or your designer don’t like the look and feel of this template, Tim Heuer have written a simply amazing article on Templates and he made it available via his blog, so don’t just go back to work without checking his grand post here :

http://timheuer.com/blog/archive/2009/07/09/free-silverlight-application-themes-silverlight-3.aspx

meanwhile if you have any feedback, I am awaiting.

Vikram.

Saturday, August 1, 2009

Silverlight 3 : Implement Charting – Content is in Marathi

I am happy as I am doing this as part of experiment or first initiative to talk on Silverlight in my regional language, I request to my friends who understand English that this post is replica of my old post on Charting which you can refer here :

http://pendsevikram.blogspot.com/2008/10/silverlight-2-charts-building-charts.html

Only Idea behind this to introduce Silverlight Technology in regional language. Well, out of interest, if you want to know more about Marathi, here you go :

http://en.wikipedia.org/wiki/Marathi_language

I will soon back with much more stuff..yes in English ! :)

Silverlight 3 : Implement Charting – Content is in Marathi

थोड़े Silverlight बद्दल :
Silverlight हे सर्व वेब-ब्राउजर वर चालणारे Plug-in आहे, तसेच हे विविध Operating Systems वर ही वापरता येते, गेली अनेक वर्षे Microsoft ASP.NET च्या मदतीने आपण अनेक प्रकारचे प्रकल्प कार्यान्वित करत आलो आहोत, काही वर्षांपूर्वी त्याला AJAX ने ही चांगलाच हातभार लावला आहे, आता त्याच धर्तीवर Microsoft आपल्याला Silverlight बरोबर एक पाउल पुढे नेत आहे. पूर्वीची बहुचर्चित Rich Internet Application (RIA) Development आता Silverlight च्या मदतीने सहज शक्य आहे. मला खात्री आहे की नजीकच्या कालावधीत आपणास याचा अनुभव नक्कीच येइल, त्याच Silverlight बद्दल मी आज थोड़े मराठीतून बोलणार आहे, हा माझा पहिला प्रयत्न आहे आणि मला खात्री आहे की तो ही Silverlight प्रमाणेच नजीकच्या काळात यशस्वी होइल.

सिल्वरलाईटच्या मदतीने आजकल एखादे परिपूर्ण संकेतस्थल तयार करणे एवढे अवघड राहिले नाही आहे. आज मी आपल्याला एक छोटेसे उदहारण देत आहे, Silverlight Toolkit च्या मदतीने आता हे काम सोपे झाले आहे, तुम्ही हे Toolkit http://www.codeplex.com/Silverlight या संकेतस्थळहून Download करू शकता. तुम्ही Silverlight चे एक नविन Project सुरु करा, प्रथम आपण XAML Code कड़े पाहू.या उदाहरणाकरीता आपणास प्रथम ToolBar वरून अथवा System.Windows.Controls.DataVisualization.Toolkit चा आधार घेउन Chart Control घेणे आवश्यक आहे.

XAML Code :

<Grid x:Name="LayoutRoot">
        <StackPanel>
            <chartingToolkit:Chart x:Name="MyPieChart"
                             Title="My First Silverlight 3 Graph"
                             Width="400" Height="300">
                <chartingToolkit:PieSeries 
                                   IndependentValueBinding="{Binding Name}"
                                   DependentValueBinding="{Binding Sales}">
                </chartingToolkit:PieSeries>
            </chartingToolkit:Chart>
      </StackPanel>      
    </Grid>

C# Code :

namespace SL3_ChartingDemo
{
    #region Namespaces
        using System.Collections.Generic;
        using System.Windows;
        using System.Windows.Controls;
        using System.Windows.Controls.DataVisualization.Charting;
    #endregion
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            #region Calling GetProductSales() to Bind Pie Chart
                GetProductSales();
            #endregion          
        }

        #region Public Method GetProductSales()
            public void GetProductSales()
            {
                List<ProductSales> PieData = new List<ProductSales>();
                PieData.Add(new ProductSales() { Name = "Vikram Pendse", Sales = 10.5 });
                PieData.Add(new ProductSales() { Name = "Mahesh Mitkari", Sales = 20.2 });
                PieData.Add(new ProductSales() { Name = "Vikram Bapat", Sales = 30.2 });
                PieData.Add(new ProductSales() { Name = "Mayur Tendulkar", Sales = 40.1 });

                PieSeries pieSlice = MyPieChart.Series[0] as PieSeries;
                pieSlice.ItemsSource = PieData;

                MyPieChart.LegendTitle = "Activity in this Month in %";
            }
        #endregion

        #region ProductSales Class Declaration
                public class ProductSales
                {
                    public string Name { get; set; }
                    public double Sales { get; set; }
                }   
        #endregion
    }
}

आपण पाहिले की किती थोडक्यात Code लिहून आपण कोणताही आलेख दाखवू शकतो, इथे मी Pie या पद्धतीचा आलेख दाखविला आहे, याच पद्धतीने आपण Bar, Line इत्यादि प्रकारचे आलेख दाखवू शकतो. तुम्ही जर नीट पाहिलेत तर तुम्हाला एक गोष्ट लक्ष्यात येइल ती अशी, की मी Pie Chart साठी लागणारी माहिती ही C# मधून पुरवत आहे, त्यासाठी मी List<Type> चा वापर केला आहे, तसेच मी PieSeries या Class चीही मदत घेतली आहे व List मधील माहितीचा आधार घेण्याचा संकेत देत आहे. अशा प्रकारे सर्व क्रिया झाल्यावर आपणास खालीलप्रमाणे आलेख आपल्या Web Page वर पहावयास मिळेल.

SLMarathi

वरील आलेख पाहून आपणास Silverlight च्या ताकदीचा एक अनुभव आलाच असेल, याप्रमाणेच आपणास दैनंदिन व्यवहारात लागणारी अनेक Applications Silverlight मधून सहज शक्य आहेत. आपणास माझा हा लेख कसा वाटला ते जरुर ई-मेल करून सांगा.

विक्रम.