Wednesday, November 21, 2012

File Attachment and saving on serving in Silverlight, Using Relay Command in MVVM Structure

Add Relay Command in View Model


///
/// Rlc Command for Attach Command
///
public RelayCommand rlcAttach
{
  get
  {
     return new RelayCommand(AttachCommand);

   }
}

Property for FilesList to upload
///
/// Property for List of Files To upload
///
public List<FileInfo> FilesToUpload
{
     get { return lstFilesToUpload; }
     set
     {
                lstFilesToUpload = value;
                RaisePropertyChanged("FilesToUpload");
     }
}


Method getting file information in List FilesToUpload
///
/// Method for go to Attach Command
///
protected void AttachCommand()
{
try
      {
                  OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            //.doc, .xls, .csv, .txt
            fileDialog.Filter = "Word 2003 Format (*.doc)|*.doc|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|Excel Files (*.xlsx)|*.xlsx|Excel Files 2003 Format(*.xls)|*.xls|Word Files(*.docx)|*.docx|All Files(*.*)|*.*";
            if (fileDialog.ShowDialog() == true)
            {
                    FilesToUpload = fileDialog.Files.ToList();
            }
      }
      catch (Exception ex)
      {
         //MessageBox.Show(ex.Message);
      }

          
}


Finally Method To send Files over the server using file handler in Web Project.
///
/// Method for go to Save Command
///
protected void SaveCommand()
{
    try
    {
      foreach (FileInfo file in FilesToUpload)
      {
          //Define the Url object for the Handler
          String ApplicationURL =    System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString();
          String UploderHandlerURI = ApplicationURL.Substring(0, ApplicationURL.LastIndexOf('/') + 1) + "UploadFileHandler.ashx";
          UriBuilder handlerUrl = new UriBuilder(UploderHandlerURI);
          //Set the QueryString
          handlerUrl.Query = "InputFile=" + file.Name;
          FileStream FsInputFile = file.OpenRead();
          //Define the WebClient for Uploading the Data
          WebClient webClient = new WebClient();
          //An async class for writing the file to the server
          webClient.OpenWriteCompleted += (s, evt) =>
          {
               UploadFileData(FsInputFile, evt.Result);
               evt.Result.Close();
               FsInputFile.Close();
          };
          webClient.OpenWriteAsync(handlerUrl.Uri);
          Attachments.Add(file.Name);
         }
       }
       catch (Exception)
      {
                //MessageBox.Show(ex.Message);
      }
}

Supporting Method UploadFileData in above lines....
///
/// The Below Method read the data from the input file stream
/// and write into the out stream
///
///
///
private void UploadFileData(Stream inputFile, Stream resultFile)
{
    byte[] fileData = new byte[4096];
    int fileDataToRead;
while ((fileDataToRead =inputFile.Read(fileData, 0, fileData.Length)) != 0)
   {
                resultFile.Write(fileData, 0, fileDataToRead);
   }
}



File Handler in Web Project...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace DistributionExpress.Web
{
    ///
    /// Summary description for UploadFileHandler
    ///
    public class UploadFileHandler : IHttpHandler
    {

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

            using (FileStream fileStream = File.Create(context.Server.MapPath("~/FilesServer/" + filename)))
            {
                byte[] bufferData = new byte[4096];
                int bytesToBeRead;
                while ((bytesToBeRead = context.Request.InputStream.Read(bufferData, 0, bufferData.Length)) != 0)
                {
                    fileStream.Write(bufferData, 0, bytesToBeRead);
                }
                fileStream.Close();
            }
        }

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




Allowing only Decimal values in Text Box Csharp


You can handle this in keyPress event of Text Box as in following way....


private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      if (!char.IsControl(e.KeyChar)
                    && !char.IsDigit(e.KeyChar)
                    && e.KeyChar != '.')
      {
               e.Handled = true;
      }

            // only allow one decimal point
     if (e.KeyChar == '.'
                && (sender as TextBox).Text.IndexOf('.') > -1)
     {
               e.Handled = true;
     }
}

Tuesday, September 18, 2012

Handling xaml not found error while navigating to non-existing xaml form

In some cases in your silverlight application the link is present for non-existing or old xaml view form. which does not exist in actual or removed after any updation. In this case while nevigating to this form silverlight runtime exception will occur. To handle this exception you need to add NavigationFailed event for the frame.

In Xaml:

<sdk:Frame  Height="175" HorizontalAlignment="Left" Margin="48,92,0,0" Name="frame1" VerticalAlignment="Top" Width="293" BorderBrush="#006C1313" NavigationFailed="frame1_NavigationFailed" />

In Xaml.cs


private void frame1_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
            e.Handled = true;
            this.frame1.Navigate(new Uri("/Testview/ErrorPage.xaml", UriKind.Relative));
}

How to navigate the frame to another view in another silver-light project under same solution

You can navigate from one view to another view in different silver-light project under same solution by using the following code.



private void button1_Click(object sender, RoutedEventArgs 
{



this.frame1.Navigate(new Uri("/MyNewSDXProject;component/TestViews/MyTestUC.xaml", UriKind.Relative));
}


Xaml will look like this:


<UserControl x:Class="SilverlighProjectTestingApp.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:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
  
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="48,47,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <sdk:Frame  Height="175" HorizontalAlignment="Left" Margin="48,92,0,0" Name="frame1" VerticalAlignment="Top" Width="293" BorderBrush="#006C1313" NavigationFailed="frame1_NavigationFailed" />
    </Grid>
</UserControl>


Tuesday, April 17, 2012

Updating any Object through Linq Query



public class TestClass
{
    public String RollNo { get; set; }
    public String Name { get; set; }
    public String ClassName { get; set; }
}
ObservableCollection<TestClass> aaa = new ObservableCollection<TestClass>();

aaa.Add(new TestClass() {
RollNo = "1602", Name = "Khalid Rafique", ClassName = "A" });

aaa.Add(new TestClass() {
RollNo = "1702", Name = "Jamal Ali Khan", ClassName = "A" });


Method1

var result = aaa.Where(c => c.RollNo == "1702");
foreach (TestClass tc in result)
{
tc.Name = textBox4.Text;
      tc.ClassName = textBox1.Text;
}

Method2

aaa
    .Where(c => c.RollNo == "1702")
    .Update(m =>
                {
                  m.Name = textBox4.Text;
                  m.ClassName = textBox1.Text;
                });


Following is the class having extensible Method of Linq update.

public static class LinqExtensableMethods
{
public static void Update(this IEnumerable source, params Action[] updates)
{
    if (source == null)
      throw new ArgumentNullException("source");

    if (updates == null)
      throw new ArgumentNullException("updates");

       foreach (T item in source)
       {
                foreach (Action update in updates)
                {
                    update(item);
                }
       }
   }
}

Method3

var result =  ocTextClass .Where(c => c.RollNo == "1702").ToList().ForEach(tc => tc.Name=TextBox.Text);

Monday, April 16, 2012

Creating Cut, Copy, Paste Context menu for all textboxs in silverlight using Style in App.xaml

This article will provide you the help for creating Cut, Copy, Paste Context menu for all textboxs in silverlight using Style in App.xaml. This style will work for every Textbox that you will add in any form of your application..

App.xaml


xmlns:my="clr-namespace:YourApplicationNameSpace"



<Application.Resources>
  <Style TargetType="TextBox">
     <Setter Property="my:ControlCustomBehaviors.SetMenu" Value="true" />
  Style>
Application.Resources>

ControlCustomBehaviors.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;


namespace YourApplicationNameSpace
{

public class ControlCustomBehaviors : Behavior<Control>
{

#region Set Context Menu
public static DependencyProperty SetMenuProperty =
          DependencyProperty.RegisterAttached("SetMenu",
                                              typeof(object),
                                              typeof(ControlCustomBehaviors),                                            new PropertyMetadata(null, SetMenuProp));
       
private static TextBox tBox;
private static void SetMenuProp(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
 tBox = d as TextBox;
 CreateMenu();


 tBox.MouseRightButtonDown += new    MouseButtonEventHandler(AssociatedObject_MouseRightButtonDown);

 tBox.MouseRightButtonUp += new MouseButtonEventHandler(AssociatedObject_MouseRightButtonUp);

 tBox.SetValue(ContextMenuService.ContextMenuProperty, _contextMenu);

}

public static object GetSetMenu(UIElement obj)
{
    return (object)obj.GetValue(SetMenuProperty);
}
public static void SetSetMenu(DependencyObject obj, object txtbox)
{
     obj.SetValue(SetMenuProperty, txtbox);
}

private static ContextMenu _contextMenu;
private static MenuItem _copy;
private static MenuItem _cut;
private static MenuItem _paste;

private static void CreateMenu()
{
  _contextMenu = new ContextMenu();
  _cut = new MenuItem();
  _cut.Header = "Cut";
  _cut.Click += new RoutedEventHandler(cut_Click);
  _contextMenu.Items.Add(_cut);

  _copy = new MenuItem();
  _copy.Header = "Copy";
  _copy.Click += new RoutedEventHandler(copy_Click);
  _contextMenu.Items.Add(_copy);

   _paste = new MenuItem();
   _paste.Header = "Paste";
   _paste.Click += new RoutedEventHandler(paste_Click);
   _contextMenu.Items.Add(_paste);
  }
  static void paste_Click(object sen, RoutedEventArgs e)
  {
    tBox.SelectedText = Clipboard.GetText();
    _contextMenu.IsOpen = false;
     tBox.Focus();
  }
  static void cut_Click(object sen, RoutedEventArgs e)
  {
     Clipboard.SetText(tBox.SelectedText);
     tBox.SelectedText = string.Empty;
     _contextMenu.IsOpen = false;
     tBox.Focus();
  }
  static void copy_Click(object sen, RoutedEventArgs e)
  {
      Clipboard.SetText(tBox.SelectedText);
      _contextMenu.IsOpen = false;
      tBox.Focus();
  }

  static void AssociatedObject_MouseRightButtonUp(object Sender,  MouseButtonEventArgs e)
        {
  if (Clipboard.ContainsText() && tBox.IsReadOnly == false && tBox.IsEnabled == true)
  {
     _paste.IsEnabled = true;
  }
  else
  {
   _paste.IsEnabled = false;
  }
  if (string.IsNullOrEmpty(tBox.SelectedText))
  {
    _cut.IsEnabled = false;
    _copy.IsEnabled = false;
  }
  else
  {
    _cut.IsEnabled = true;
    _copy.IsEnabled = true;
  }
  _contextMenu.IsOpen = true;
   tBox.Focus();

  }
  static void AssociatedObject_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
 {
    tBox = sender as TextBox;
    e.Handled = true;
 }
 #endregion

}
}

Friday, April 13, 2012

How to find the nth Highest Salary from Employee Table

You can find out the nth Highest Salary from the Employee Table by using following systax

select top 1 * from testEmp
where Emp_Id not in
(select top (n-1) Emp_Id from testEmp order by salary desc)
order by salary desc

Let Suppose following is you table

Emp_Id
Employee_Name
Salary
1602
Khalid Rafique
40000
1650
Jamal Ali Khan
45000
1530
Farhan Khan
29000
1533
Abid sultan
33000
1535
Atiq Khan
38000
1730
Rashid Ali
21000

if you want to find 2nd highest salary, you need to have to write the following query

select top 1 * from testEmp 
where Emp_Id not in
(select top (2-1) Emp_Id from testEmp order by salary desc)
order by salary desc

Result:
Emp_Id
Employee_Name
Salary
1602
Khalid Rafique
40000


if you want to find 3rd highest salary, you need to have to write the following query
select top 1 * from testEmp 
where Emp_Id not in
(select top (3-1) Emp_Id from testEmp order by salary desc)
order by salary desc


Result:
Emp_Id
Employee_Name
Salary
1535
Atiq Khan
38000

if you want to find 4rd highest salary, you need to have to write the following query

select top 1 * from testEmp 
where Emp_Id not in
(select top (4-1) Emp_Id from testEmp order by salary desc)
order by salary desc


Result:
Emp_Id
Employee_Name
Salary
1533
Abid sultan
33000