Friday, November 20, 2009

How to read RSS and atom feed

Before .Net 3.5 we had to go for separate framework to read the feeds and parse it. In that case we need to refer the framework in our project and install that assembly in Bin or GAC. We need to parse RSS and atom feeds separately. But now, with .Net 3.5, life has become much easier.
With the namespace 'System.ServiceModel.Syndication' it is just few lines of code to read and parse the feeds either RSS or Atom. Just have a look on the code:
string Link;
string Copyright;
StringBuilder rssFeed= new StringBuilder();
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
String Title = feed.Title.Text;
if (feed.BaseUri != null)
{
       Link = feed.BaseUri.ToString();
}
else
{
       Link = feed.Links[0].Uri.ToString();
}
if (feed.Copyright != null)
{
      CopyRight = feed.Copyright.Text;
}
rssFeed.Append(“Title: ”+Title);
rssFeed.Append(“Link: “+Link);
rssFeed.Append(“\nCopyRight: “+CopyRight);
foreach (var item in feed.Items)
{
    string title = "";
    string description = "";
    string link = "";
    DateTime PublishDate;
    String AuthorName;
    String AuthorUri;
   if (item.Title != null)
   {
        title = item.Title.Text;
   }
   if (item.Content != null)
  {
    description = ((System.ServiceModel.Syndication. TextSyndicationContent)(item.Content)).Text;
   }
   else
   {
         if (item.Summary != null)
         {
               description = item.Summary.Text;
         }
    }
    if (item.Links != null && item.Links.Count > 0)
    {
          link = item.Links[0].Uri.ToString();
          for (int i = 1; i < item.Links.Count; i++)
          {
                 link += "\n" + item.Links[i].Uri.ToString();
           }
     }
     if (item.PublishDate != null)
    {
         PublishDate = item.PublishDate.DateTime;
     }
     if (item.Authors != null && item.Authors.Count > 0)
    {
           StringBuilder Authors = new StringBuilder(item.Authors[0].Name + ",");
          StringBuilder AuthorsUri = new StringBuilder(item.Authors[0].Uri + ",");
         for (int i = 1; i < item.Authors.Count; i++)
        {
                Authors += "\n" + item.Authors[i].Name + ",";
                AuthorsUri += "\n" + item.Authors[i].Uri + ",";
      }
     AuthorName = Authors;
      AuthorUri = AuthorsUri;
   }
    rssFeed.Append(“\n\nLink: ”+link);
    rssFeed.Append(“\nTitle: ”+title);
   rssFeed.Append(“\nDescription: ”+ description);
   rssFeed.Append(“\nPublishDate: ”+ PublishDate.ToString();
   rssFeed.Append(“\nAuthorName: ”+ AuthorName.ToString();
   rssFeed.Append(“\nAuthorUri: ”+ AuthorUri.ToString();
}

Saturday, September 19, 2009

Asynchronous Event Handling

Asynchronous Event handling
Why need Async Event Handling?
Let’s consider an example that you need some data in your application. So you call a method GetData(…) and it will give you the data. But untill you get the data your UI Thread is blocked. So you need something like that you call the method GetData(…) and return, and when data is done an event is raised to the UI that OK I am done and you process the data.
So here are the simple steps for Asynchronous event handling:
Suppose that I had a class “Myclass” which contains a mehod “GetDatawhich I want to call asynchronously, So that it raise an event when it get all the data without blocking main thread.
Step 1: Create MyEventArgs.cs
First decide what you parameters are needed after Get Data Return. These are the properties in MyEventArgs class. Suppose that we need a UserState, Result, and if any exception occurs then Error. So my class will look like this:
public class MyEventArgs
{
public object Result { get; set; }
public Exception Error { get; set; }
public object UserState { get; set; }
}
Above the class I define a delegate eventhandler like this:
public delegate void MyEventHandler(object sender, MyEventArgs e);
Step 2: Create MyEventController.cs
For asynchronous handling we create a delegate for the method. It has the same parameters as in Myclass’ s GetData method. If the GetData has some out parameters then we can also use them. If not then no need to define out parameter.:
public delegate object MyEventDelegate(string param1,out Exception Excep);
Now define a controller class like this:
public class MyEventController
{
public event MyEventHandler MyEventComplete;
MyEventDelegate _MyEventDelegate;
MyClass myClass;
public MyEventController()
{
myClass = new MyClass ();
_ MyEventDelegate = new MyEventDelegate(MyMethod);
}
private void OnMyEventComplete(MyEventArgs e)
{
if(MyEventComplete !=null)
{
MyEventComplete(this,e);
}
}
public void GetData(string param1, object UserState)
{
Exception Excep = null;
object[] _AsyncUserStats = new object[1];
_AsyncUserStats[0] = UserState;
_MyEventDelegate.BeginInvoke(param1, out Excep, new AsyncCallback(MyMethodCallBack), _AsyncUserStats);
}
private object MyMethod(string param1, out Exception exception)
{
return myClass.GetData(param1,out exception);
}
private void MyMethodCallBack(IAsyncResult ar)
{
Exception Excep = null;
AsyncResult aresult = (AsyncResult)ar;
object Result = ((MyEventDelegate)aresult.AsyncDelegate ).EndInvoke(out Excep, ar);
object[] _AsyncUserState = ar.AsyncState as object[];
MyEventArgs result = new MyEventArgs()
{
Error=Excep,
Result =Result,
UserState = _AsyncUserState[0],
};
OnMyEventComplete(result);
}
}
Let’s see what happens in the controller class. It define an event MyEventComplete which will be raised when GetData complete. For this we define a function “OnMyEventComplete” which raise the event when we get all the data. It also defines an object of the delgate we define above “MyEventDelegate”. In the constructer we register the method (MyMethod here) with the delegate which we want to call. In this method we actually call the GetData of MyClass.
Now look at the GetData of MyController class. This is the method which we call when we want to get the data. In this method we call the BeginInvoke of the delegate. In the BeginInvoke it accepts the same parametrs as in the GetData metod of MyClass and two extra parameters of type AsyncCallback and object or object[]. The AsyncCallback contains the method which will be called when it gets the data. The syntax for implementation of this callback method is :
private void MyMethodCallBack(IAsyncResult ar)
And in the MyMethodCallBack we get the result and raise the event by calling OnMyEventComplete method.
So the flow is like this:
clip_image002

In the UI we create a class of the controller and call the GetData of controller. Event “MyEventComplete” will be raised when get Data complete. Before calling the method you have to register the event like this :
MyEventController _myController= new MyEventController();
_myController.MyEventComplete += new MyEventHandler (myController_MyEventComplete);
void myController_MyEventComplete(object sender, MyEventArgs e)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
{
/////.. event is raised and we get the result in the e.Result
}));
}
Since this event complete is returned in another thread we neet to use Dispatcher like above.
And when we need the data we use _myController.GetData(….);

Friday, August 28, 2009

.NET RIA Service

.Net RIA Services bring together the ASP.NET and Silverlight platforms. It provides a pattern to write application logic that runs on the mid-tier. It integrates with Silverlight components on the client and ASP.NET on the mid-tier. Get more information about RIA services from http://www.nikhilk.net/NET-RIA-Services-Vision-Architecture.aspx.
In this blog we see how to create a simple .NET RIA Service enabled project. It only provides a brief overview of.Net RIA Services.
Step 1: First Create a new Silverlight Project as:pic1
Step 2: Then enable .Net Ria Services like this:
clip_image004[1]
Step 3 : Now to mid-tier i.e., on RiaTest.Web project add a new item and select the Data category as follows:
clip_image006[1]
we will access the Northwind database using the Entity Framework. We choose 2 tables from the northwind for this application.
clip_image008[1]
Step 4 : After building project create a DomainService on the mid-tier. A DomainService is a class that exposes entities and operations for a specific data domain. It is also where the developer adds application logic. To create a Domain Service Add new item to the mid-tier and in the Web category add DomainService class as follows:
clip_image010
Step 5 : Now we select only one table Orders , we will not set Enable Editing for the table because we want only read only table. Generate metada will create metadata of table on client.
clip_image012
It will generate a class as follows:
clip_image014
It has following characteristics:
· It is derived from LinqToEntitiesDomainService, an abstract base class built into the .NET RIA service framework3.
· It is bound to NorthwindEntities1 class we created earlier
· A single GetOrders() query method is generated because we select only Orders table
· This.Context.Orders in GetOrders() will give all the order in table.
· OrderService is marked with [EnableClientAccess] indicating it is visble on client tier
When we build project and click on Show all files on client tier we see some Gnerated code as:
clip_image016
This is the client proxy class which is generated from the Domain service class which we create on mid-tier.
Step 6 : Now in MainPage.xaml add a data Grid named “MyGrid” as follows:
image
Don’t forget to include System.Controls.Data.dll in references.
Step 7 : Now in MainPage.xaml.cs add 2 references :
· System.Windows.Ria.Data
· RiaTest.Web
Now create an object of OrderContext and then load entities of Orders and set the itemsource of the datagrid.
image
When you run the project you see all the orders in the data grid.

Monday, March 30, 2009

Data Binding of ListBox in Silverlight

In this post I'll show how to use data binding with the listbox in silverlight. Suppose that you have a class Person which contains ID, Name, Address like this:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now i have a List lstPerson. And i want to show Name in the ListBox.
So in the .xaml I define a listbox as:
<ListBox x:Name="ListBoxPerson">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ForeignKeyName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

And now in .xaml.cs i define the itemSource of the ListBox as ListBoxPerson.ItemSource=lstPerson;
So, this is so simple to use data binding in ListBox.

Friday, January 30, 2009

Omega.SDSClient new release

This blog is about Omega.SDSClient by Cerebrata Software Pvt. Ltd. Now its new version is released. After login it displays the quick help tab which gives information like how to use context menu, buttons.


In this new version it supports new features like:
  • Hiding/Unhiding selected authorities
  • Hiding/Unhiding selected containers
  • Deleting bulk containers.

In this new version authorities and containers are presented in a treeView. One can use Shift+LeftMouse Click to see the context menu operations. One can select a container and see all the entities of the container in a Tab. From the tab one can add another Flexible or Blob Entity. Delete, Update the Entity,View the blob Entity.


Context Menu for authority


Context Menu for container

When authorities are checked then one can perform bulk operation to hide all the selected authorities. Also there is an option to unhide the already hidden authorities.




Similarly if containers are checked then one can perform bulk operation to hide all the selected containers, delete the selected containers. Also there is an option to unhide the already hidden containers.


These are the buttons or icons used in this version.