Saturday, February 16, 2013

Crystal Report in Silverlight 5


Long time ago, Visual Basic and Visual Studio have crystal report many version with it. People are saying that since 1993. Crystal Report is available as a separate download from the SAP web site. Crystal Reports for Visual Studio 2010 will continue to be free, with no registration required. You can directly download crystal report exe file from here.


Introduction:

In this article, I will show you simple report creation process with screenshots. A picture is worth more than a thousand words, so I always believe in an article with screenshots. Here I will explain some system to view crystal report. I am going to run the below 5 systems.

  1.  Simple Crystal Report by Using ADO.NET with data set.
  2.  Generate Crystal Report with data set.
  3.  Generate Crystal Report with multiple data table in data sets.
  4. Generate Crystal Report by XML

Let's start by creating a new website in VS2010. See the following screen:
As per figure 1 and 2, create a new Silverlight application in VS2010 and name it as per your choice. Now I am going to discuss data base structure below

   Figure 1

Press OK Button to Create a New Project Name 'CrystalArticle'

    Figure 2

Firstly you have to create a data base table that is name you may choose any thing. The data base table looks like this as figure 3 or you may down load script from my uploaded script file.


   Figure 3

Now you can write some data into table by this script or manually like as figure 4

    Figure 4


But in the attached project, I am getting data from the XML file. I have saved all the data from table to XML. So you can easily use the attached project. Next Dataset (xsd file) creation.
There are so many ways to pass the data to Crystal Report. Here I am using Dataset (xsd file) to bind Crystal Report. In my point of view, this is the best way to bind. So, next step is Dataset (xsd file) creation.
Go to CrystalArticle.Web->ClientBin -> Right click on the Project -> Add New Item. Figure 5 shows the Dataset creation.
   Figure 5
Once you click on Add button, it will ask one confirmation message. Just click yes. Now you can see thedsTestCrystal.xsd dataset file opened in Visual Studio. Here you need to create one Data Table with all the columns names you need to shown in Crystal Report. To Create Data Table, see the below Figure 6.
    Figure 6
Now you can see Data Table created in the Dataset. Next, we need to add the columns names need to shown inCrystal Report. Please note that this Data Table column names and data types should be the same as your table in database. If you are getting any data type property mismatching error, just think that this is the problem. To Create Column names, see the below Figure 7.

    Figure 7
Add all the columns one by one and set the correct data type. Here by default, data type is string. If any columns have different data type, we need to change manually. In this project, I am using ‘Product_Qty’ column data type as Decimal. So to change the data type, see the below Figure 8.
    Figure 8
Dataset (dsTestCrystal.xsd) creation has been done. Now we need to design Crystal Report.
That's it. XSD file creation has been done. Now we will move to create Crystal report design.
Just click on the Solution Explorer -> Right click on the project name and select crystal reports. Name it as per your choice and hit the add button.
Figure 9 will show you the creation process of Crystal reports.

Figure 9
Click on the add button and one .rpt file will be added to the solution. And also, it will ask for the report creation type of how you want to create the report. Figure 10 will show you a screenshot.

Figure 10
Just click ok button to proceed. It will lead you to figure 11:



    Figure 11
Under project data, expand ADO.NET Datasets and select DataTable1 and add to the selected table portion located at the right side of the windows using > button.
Now click on the Finish button and it will show the next screen (Figure 12):


   Figure 12
Once report file is added, you can see Field Explorer on the left side near server explorer.
Expand Database Fields, under that you will be able to find Datatable that we have created earlier. Just expand it and drag one by one filed from Field Explorer to the rpt file under detail section.
Now the report design part is over. Now we have to fetch the data from database and bind it to dataset and then bind that dataset to the report viewer.
Let's go step by step.
First Drag a CrystalReportViewer control on aspx page from tool box as per below screen:


    Figure 13
Now we will fetch the data, pass data to the dataset and then add that dataset to the Crystal Report. Now you have to create a single aspx page like Report.aspx
    Figure 14
Below is the C# code which will do the job into Report.aspx page code behind:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


protected void Page_Load(object sender, EventArgs e)
{
    ReportDocument rptDoc = new ReportDocument();
    dsSample ds = new dsSample();
    DataTable dt = new DataTable();

   
    dt.TableName = "Crystal Report Example";
    dt = getAllOrders(); 
    ds.Tables[0].Merge(dt);
 
    rptDoc.Load(ReportName));
  
    rptDoc.SetDataSource(ds);
    CrystalReportViewer1.ReportSource = rptDoc;
}

You can see the report by silverlight button click and you paste the code below into button click
var filePath   "http://" + Application.Current.Host.Source.Host + ":" + Application.Current.Host.Source.Port + "/ClientBin/Report.aspx";
Uri myURI = new Uri(HtmlPage.Document.DocumentUri, filePath);HtmlPage.Window.Navigate(myURI);

Tuesday, February 12, 2013

Comparing WCF Data Services and WCF RIA Services


Windows Communication Foundation (WCF) provides all the support you need to build distributed service-oriented data access solutions. You can certainly work with WCF directly to create custom services and expose data from an Entity Data Model (EDM) with the ADO.NET Entity Framework, or from any other data access layer (DAL) of your choosing. To take this “raw” approach, you need to start with the basics, or what is commonly referred to as the ABC’s of WCF: Addresses, Bindings, and Contracts. You must create service, operation, and data contracts, and then configure your service model with appropriate endpoint addresses and compatible bindings to be reachable by clients. Services are usually stateless, so you must also handle client-side change tracking and multi-user conflict resolution entirely on your own. The learning curve can be quite steep, after which you will still need to expend a great deal of effort to make it work.
Alternatively, you can turn to one of the two later technologies that Microsoft has built on top of WCF. These are WCF Data Services and WCF RIA Services, and they represent two very different approaches for building data-oriented services. Both provide abstractions that shield you from many underlying WCF particulars, so you get to spend more time focusing on your application and less time on plumbing. For one thing, you don’t need to code WCF contracts or manage change tracking on the client; all that gets done for you. With WCF RIA Services (and Silverlight), you don’t even need to create and update service references; Visual Studio generates code automatically via a special link that keeps your client and WCF RIA Services projects in sync at all times.
Both WCF Data Services and WCF RIA Services can solve many of the same problems, so it is only natural to question which one to use. The answer extends a bit beyond the standard “it depends on your scenario” response, since WCF RIA Services offers a lot more than just data access functionality. It also features client-side self-tracking entities, client-side validation, automatic server-to-client code generation, and more. In this blog post, I’ll discuss both platforms at a high level to help guide you in making the right choice.

WCF Data Services

Microsoft designed WCF Data Services as a thin layer over Entity Framework that exposes data-centric services to client applications. Out of the box, you can quickly build WCF Data Services over an Entity Data Model with virtually no effort. Custom providers for WCF Data Services for data sources other than Entity Framework are available; however, considerable additional effort is required to implement them. You can think of WCF Data Services as universal Web Services built just for data, although it can be easily extended with custom service operation methods. The platform is based on the industry standards of Representational State Transfer (REST) and the Open Data Protocol (OData), which means that these services are consumable by virtually every type of client in the world.
REST provides a uniform interface for querying and updating data. It is based on HTTP, meaning that client requests are issued in the form of GET, POST, MERGE, and DELETE actions — standard verbs understood by all HTTP clients. Any REST query can be invoked with an HTTP GET request by expressing all the elements of the query in a properly formed Uniform Resource Identifier (a URI, which is a more general term than Uniform Resource Locator [URL]). You can even test the service with an ordinary browser; simply type the properly formed URI directly into the address bar and you will receive the Atom Publishing Protocol (AtomPub) response (an XML dialect very similar to the Really Simply Syndication [RSS] feed format). The POST, MERGE, and DELETE verbs correspond respectively to insert, update, and delete operations supported by the service, and the payload (parameters, data, and other metadata) for these operations is passed in HTTP headers.
Just as REST enables universal data access via HTTP, the Open Data Protocol (OData) establishes universal data structure via standard serialization formats (see http://www.odata.org). All clients can handle plain text formats such as JavaScript Object Notation (JSON) and of course XML, and so OData defines standard response formats based on both formats. JSON provides a compact structure suitable for many basic types of services, while XML forms the basis for the more verbose AtomPub feed format. AtomPub is the default serialization format in WCF Data Services, because it effectively leverages the hierarchical nature of XML to describe the rich structure of data and metadata in an Entity Data Model.
The WCF Data Services client libraries for Windows/WPF, ASP.NET, Silverlight, and Windows Phone 7 include a special LINQ provider, commonly known as LINQ to REST. This provider automatically translates client-side LINQ queries into an equivalent OData URI, meaning that you don’t need to learn the OData URI syntax if you are building Microsoft clients over WCF Data Services (just use good old LINQ). The client libraries automatically deserialize the AtomPub feed response from WCF Data Services into ready-to-use objects. They also provide a stateful context object that can track changes on the client for pushing updates back to the server, although your code needs to explicitly notify the context about objects as they are changed.

WCF RIA Services

WCF RIA Services is, well, richer than WCF Data Services (and also newer). Indeed, the R in RIA means rich, although the full TLA (Three-Letter Acronym) can stand for Rich Internet Application or Rich Interactive Application—depending on who you’re talking to. Since its earliest days, WCF RIA Services was designed to work best with Silverlight, although it now also supports OData, SOAP, and JSON to reach a wider range of clients as well. You can build WCF RIA Services over any data access layer, including Entity Framework and LINQ to SQL. You can also use Plain Old CLR Objects (POCOs), in which case you handle the persistence yourself using your data access technique of choice, even conventional ADO.NET (raw readers and command objects, or DataSets). In any case, you expose WCF RIA Services by coding domain service classes that support CRUD operations, as well as other custom service operations. You also maintain a special metadata class for each entity that auto-magically surfaces on the client for effortless end-to-end validation across the wire.
When WCF RIA Services is used with Silverlight, you don’t need to create and update service references; Visual Studio generates code automatically via a special link that keeps your client and WCF RIA Services projects in sync at all times. Like a service reference, this link binds the two projects together, only a WCF RIA Services link couples them much more tightly than an ordinary service reference does. Public changes on the service side are reflected automatically in corresponding classes on the client side every time you perform a build, so you never need to worry about working against an outdated proxy in the client project simply because you forgot to manually update a service reference.
The WCF RIA Services link greatly simplifies the n-tier pattern, and makes traditional n-tier development feel more like the client/server experience. With the link established, Visual Studio continuously regenerates the client-side proxies to match the domain services on each build. It also auto-generates client-side copies of shared application logic you define in the services project, simply by looking for classes you’ve defined in files named *.shared.cs, or *.shared.vb. The link enforces automatic client-side validation and keeps validation rules in sync between the the domain services and the client at all times. Furthermore, client-side entities are completely self-tracking; you do not need to manually notify the context object of every change to every entity, as you are required to do with the WCF Data Services client library.

Comparing WCF Data Services and WCF RIA Services

The following table summarizes several key differences between the two platforms.
WCF Data ServicesWCF RIA Services
Supported ClientsResource-based API, supports all clients via deep REST and OData support.Domain-based API, most tailored for use with Silverlight, but supports other clients via SOAP, JSON, and OData.
Supported Data Access LayersTargets EF. Other DALs are supported, but greater effort is required.Supports EF, LINQ to SQL, and POCO (custom persistence layer).
Client DevelopmentRequires you to notify the context for change tracking.Supports self-tracking entities, synchronized client/server logic, and much more (particularly with Silverlight).
Service DevelopmentInstant, code-less, extensible REST services out of the box (with EF); “free CRUD.”Requires you to code CRUD operations manually in domain service classes.
From this comparison, it looks like WCF RIA Services is more attractive for Silverlight clients than non-Silverlight clients—regardless of which data access layer is used. Conversely, it shows that WCF Data Services is more appropriate for use with Entity Framework than it is with other data access layers—regardless of which client is used. But let’s examine things in a bit more detail.
If your scenario uses EF on the back end and targets Silverlight on the front end, then you are in the best position. Both WCF frameworks pack a huge win over writing traditional WCF services “by hand.” Your decision at this point is based on whether you simply require services to provide data access (that is, you primarily need CRUD support), or if you are seeking to leverage additional benefits. Another consideration is whether you are targeting Silverlight as the client exclusively or not.
Of the two, WCF Data Services is relatively lightweight, and requires almost no effort to get up and running. So it’s the better choice if you primarily require data access functionality in your services, particularly if you want to keep your service open to non-Silverlight clients as well. WCF RIA Services is more robust, and offers numerous additional features. This makes it a very compelling choice for the development of rich client applications. Although it began as a platform almost exclusively designed for Silverlight, support is steadily emerging for other client platforms via OData, SOAP, and JSON, as well as self-tracking entity libraries now available for jQuery. However, it requires the effort of creating domain service classes to support CRUD operations.
Finally, both frameworks are extensible, and both can be secured by traditional authentication and authorization techniques. They are also both capable of integrating with the ASP.NET Membership provider for role management and personalization.
What if you are using neither Silverlight nor Entity Framework? Well, then your work will be cut out for you whatever choice you make. With WCF Data Services, you will need to implement either the Reflection or Streaming provider, or write your owncustom provider. And with WCF RIA Services, you will not get to fully enjoy all the benefits of the framework, but you will still need to write domain services and metadata classes. After careful consideration, you may well conclude that neither choice is appropriate, and decide instead to stick with tried and true WCF services, coding your own service contracts, data contracts, binding configurations, change tracking, validations, and so on.

Summary

Both WCF Data Services and WCF RIA Services can represent huge savings in development effort. Which one you choose (or whether indeed you choose to use either) depends a great deal on your data access layer of choice and the types of clients you intend to reach. This post tells you what you need to know to intelligently distinguish between them.
My upcoming book, Programming Microsoft SQL Server 2012, has an entire chapter dedicated to this topic. Look forward to extensive coverage and code samples for complete data access solutions using both platforms. The release date is just a few short months away, so stay tuned!

Monday, February 4, 2013

XML and Binary File Read Write


public static bool WriteXML<T>(string fileName, IEnumerable<T> objList)
        {
            DataContractSerializer x = new DataContractSerializer(new ObservableCollection<T>().GetType());
            FileStream writer = new FileStream(fileName, FileMode.Create);
            x.WriteObject(writer, objList);
            writer.Flush();
            writer.Close();
            writer.Dispose();
            return true;
        }

        public static void ReadXML(string fileName)
        {
            /*here object means your business object*/
            FileStream fs = new FileStream(fileName, FileMode.Open);
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, null);
            DataContractSerializer ser = new DataContractSerializer(typeof(Object));

            // Deserialize the data and read it from the instance.
            Object deserialized = (Object)ser.ReadObject(reader, true);
            reader.Close();
            fs.Close();
        }

        public bool CreateXML<T>(List<T> objList, string fileName)
        {
            string path = fileName + ".xml";
            XmlSerializer x = new XmlSerializer(new List<T>().GetType());
            StreamWriter writer = new StreamWriter(path);
            x.Serialize(writer, objList);
            writer.Flush();
            writer.Close();
            writer.Dispose();
            return true;
        }

        public void ReadXML(string fileName)
        {
            DataSet ds = new DataSet();
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
            ds.ReadXml(fs);
            fs.Close();
            fs.Dispose();
        }

public bool CreateBinaryDataFile<T>(List<T> objList, string xmlFileName)
        {
            using (FileStream str = File.Create(xmlFileName))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(str, objList);
                str.Flush();
                str.Close();
                str.Dispose();
            }
            return true;
        }

        public bool ReadBinaryDataFile(string xmlFileName)
        {
            string myXMLfile = @"D:\" + xmlFileName;
            List<object> _IssueList = new List<object>();
            using (FileStream str = File.OpenRead(myXMLfile))
            {
                BinaryFormatter bf = new BinaryFormatter();
                _IssueList = (List<object>)bf.Deserialize(str);
                str.Flush();
                str.Close();
                str.Dispose();
                return true;
            }
        }