Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Monday, December 12, 2011

Silverlight Event

In Silverlight MSDB always says that the event are bubbled
Taken from MSDN
http://msdn.microsoft.com/en-us/library/cc189018%28v=vs.95%29.aspx

WPF supports an analogous "tunnelling" routing strategy, whereby the root of a page / object tree has the first chance to handle a routed event, and the event then "tunnels" down the object tree toward its event source. Silverlight does not use "tunnelling" routed events. Events in Silverlight either follow the "bubbling" routing strategy (and are referred to as routed events) or do not route at all. There are also other API-level differences in routed event behaviour between Silverlight and WPF.

Which means that in silver light there is no tunnelling.....

But with the below sample I am trying to show a bug in Silverlight Datagrid
when we subscribe the events for the selected item event.

In the below example , I have created a Data Grid which subscribe the selected item event, and the data grid have 2 columns .One is defined as DataGridTemplateColumn and another is a DataGridTextColumn.In the DataGridTemplateColumn I have placed a checkbox and subscribe the click event ...

Turn on the debugger and see when we clicked on the check box .....Which event got fired.....






                  




                       









namespace SilverlightApplication1
{
   public partial class MainPage : UserControl
    {
      public MainPage()
        {
          InitializeComponent();
          this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

     void MainPage_Loaded(object sender, RoutedEventArgs e)
      {
       List lstTest = new List();
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "1" });
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "2" });
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "3" });
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "4" });
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "5" });
       lstTest.Add(new Test { CheckFlag = true, StringCaption = "6" });
       dgTest.ItemsSource = lstTest;
      }

   private void dgTest_SelectionChanged(object sender,SelectionChangedEventArgs  e)
    {

     }

  private void CheckBox_Click(object sender, RoutedEventArgs e)
   {

    }
}
public class Test
 {
  public bool CheckFlag { get; set; }
   public string StringCaption { get; set; }
 }
}

Looking into this and try to understand this whether this is a bubbling or not ..

Tuesday, September 7, 2010

Download a file in Silverlight from the server

For downloading a file form  the server we have several ways .The following  example i have used the traditional asp.net handlers ie the ashx.

All that what we have to do when downloading a file from silverlight is that
we need to navigate to handler that have created for the download.

The  following code sippnet shows the handler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;

namespace SLMemoryLeakSample.Web
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    public class FileDownload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
            context.Response.ContentType = "application/ms-Excel";
            context.Response.WriteFile("New Microsoft Office Word Document.docx");
            context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
As you can see the the code that have written inside the Process Request basically  we just write the file into the output stream so that the file will be available in the client

Now step is the real magic of the silvelight especally the HyperLink button we have something called the NavigateUri which actually  call this handler

We can set the TagetName property to what ever you want from the avaiable .If we didnt set the target property name we will probably  get an error since the silverlight expects another xaml page

Enjoy coding............................

Monday, September 6, 2010

Writting a file throught Silverlight .

The following code sipnet shows how we can open a file dialog from
the Silverlight Applcation and write to the server .
This is done via in conjection with the Asp.net handlers.


 private void FileUpLoader()
      {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        bool? retVal = openFileDialog.ShowDialog();

        if (retVal != null && retVal == true)
          {
            UploadFile(openFileDialog.File.Name,openFileDialog.File.OpenRead());
            tblStatus.Text = openFileDialog.File.Name;
          }
        else
          {
             tblStatus.Text = "Please select a file";
          }
       }




 private void UploadFile(string fileName, Stream data)
        {
            UriBuilder uriBuilder =
             new UriBuilder("http://localhost/SLMemoryLeakSample.Web/FileUploader.ashx");
            uriBuilder.Query = string.Format("filename={0}", fileName);

            WebClient webClient = new WebClient();
            webClient.OpenWriteCompleted += (sender, e) =>
            {
                WriteStream(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            webClient.OpenWriteAsync(uriBuilder.Uri);
        }



 private void WriteStream(Stream input, Stream output)
        {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }


The FileUploader.ashx will be as following


 public class FileUploader : IHttpHandler
    {

        #region FileUploader
        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"].ToString();

            using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    fs.Write(buffer, 0, bytesRead);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        } 
        #endregion
    }

Enjoy Coding ............................................

Wednesday, June 23, 2010

How To: Dispose a Module in PRISM

There have been several questions about disposing Module in Prism at CodePlex. Moreover, several workarounds have been proposed.
The fastest workaround was to extend the CloseView() method at the Presenter (of the View we want to dispose) as follows:
Public void OnCloseView()
{

if (View is IDisposable)
{
((IDisposable)View).Dispose();
//Disposes the view.
}
}
We need to implement IDisposable interface in all the controls so that when we close the view we can able to free up all the resource from the module which will avoid memory leak. Since the freeing up of resources is not done automatically when we close a view .In situation like when the module uses the Dispatcher Timer and if the timer is not closed say for instance, then we can free up the Dispatcher Timer using the IDisposable.

Please, remember that you must consider when and where to dispose (if you don’t want to dispose at every time). Besides, if you place this handler in the first position (regarding handlers order), you won’t be able to cancel the disposal, so I recommend using this carefully and, of course, consciously!
- Cheers, ;)