Articles → LIGHT SWITCH 2011 → Upload And Download File In Lightswitch 2011

Upload And Download File In Lightswitch 2011






Software Requirement




  1. Visual studio 2010 is installed on your machine.
  2. Visual Studio 2010 service pack 1 is installed on your machine.
  3. Microsoft Visual Studio Light switch 2011 is installed on your machine.

Prerequisite Knowledge




  1. What is lightswitch?
  2. How to create buttons?
  3. What is button’s Execute() method?
  4. What is dispatcher and why we use it?
  5. How to create lightswitch screens?
  6. Basics about web applications in .net.

Creation Of File Table




Picture showing the sample table in lightswitch application designer
Click to Enlarge




Add A New Editable Grid




Picture showing adding a new screen of type Editable Grid Screen
Click to Enlarge



Picture showing the design screen of the editable grid screen
Click to Enlarge


Remove Content Field From Grid






Picture showing the editable grid screen with extra fields removed
Click to Enlarge


Add Upload, Download And Save Data Buttons






Picture showing adding the Upload, Download and Save button in the screen designer
Click to Enlarge



Picture showing the editable grid screen after adding buttons
Click to Enlarge


Add Silverlight Child Window




Picture showing adding a new item after changing the solution explorer view to file view
Click to Enlarge





Picture showing adding the UploadControl.xaml file inside the project
Click to Enlarge


Write Xaml Code In Silverlight File


<controls:ChildWindow x:Class="LightSwitchApplication.UploadControl"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
            Width="400" Height="120">
	<Grid x:Name="LayoutRoot" Margin="2">
		<Grid.RowDefinitions>
			<RowDefinition />
			<RowDefinition/>
		</Grid.RowDefinitions>
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="Auto"></ColumnDefinition>
			<ColumnDefinition></ColumnDefinition>
		</Grid.ColumnDefinitions>
		<TextBox Height="30" HorizontalAlignment="Right" Name="FileTextBox" VerticalAlignment="Top" Width="200" 
                 IsHitTestVisible="False" Margin="5" IsTabStop="False" />
		<Button Content="Browse" Height="30" HorizontalAlignment="Left" Name="BrowseButton" Margin="5"
                VerticalAlignment="Top" Width="75" Click="BrowseButton_Click"  Grid.Column="1"/>
		<Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="30" Margin="5" HorizontalAlignment="Right" Grid.Row="1" />
		<Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="30" Margin="5" HorizontalAlignment="Left" Grid.Row="1" Grid.Column="1" />
	</Grid>
</controls:ChildWindow>




Picture showing the UI  of UploadControl.xaml file after adding controls
Click to Enlarge




Add Properties In Xaml Code Behind




public FileStream Stream { get; set; }
public string FileName { get; set; }



Add Button Click Events In Code Behind In Silverlight


private void OKButton_Click(object sender, RoutedEventArgs e) {
  this.DialogResult = true;
}

private void CancelButton_Click(object sender, RoutedEventArgs e) {
  this.DialogResult = false;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e) {
  OpenFileDialog openFileDialog = new OpenFileDialog();

  if (openFileDialog.ShowDialog() == true) {
    this.FileTextBox.Text = openFileDialog.File.Name;
    FileStream myStream = openFileDialog.File.OpenRead();
    Stream = myStream;
    FileName = System.IO.Path.GetFileName(this.FileTextBox.Text);
  }
}





Add Code In Upload Button Click In Lightswitch Project


partial void Upload_Execute() {
  Dispatchers.Main.BeginInvoke(() => {
    UploadControl ctrl = new UploadControl(); // line 1
    ctrl.Closed += new EventHandler(ctrl_Closed); // line 2
    ctrl.Show(); // line 3
  });
}

Byte[] content;
string fileName;
void ctrl_Closed(object sender, EventArgs e) {
  // Write your code here.
  UploadControl ctrl = (UploadControl) sender;
  Byte[] b;
  using(BinaryReader br = new BinaryReader(ctrl.Stream)) {
    b = br.ReadBytes(Convert.ToInt32(ctrl.Stream.Length));
  }

  content = b;
  fileName = ctrl.FileName;
}







Add Code On Save Button In Lightswitch Project


partial void SaveData_Execute() {
  LightSwitchApplication.File f = this.DataWorkspace.ApplicationData.Files.AddNew();
  f.FileContent = content;
  f.FileName = fileName;
  this.DataWorkspace.ApplicationData.SaveChanges();
}





Add Download.Aspx Webform File In Lightswitch Project




Picture showing adding a new item in the project
Click to Enlarge



Picture showing download.aspx is added in the project
Click to Enlarge


Add Download.Aspx Entry In Project File




Picture showing the unload project option for unloading the project file
Click to Enlarge



Picture showing the option for editing the project file
Click to Enlarge



Picture showing adding an entry of download.aspx in the project file
Click to Enlarge



Picture showing the Reload Project option for reloading the project
Click to Enlarge



Picture showing the confirmation message to reload the project
Click to Enlarge




Add Dlls In Lightswitch Project




Picture showing adding the System.Windows.Browser dll in the Client project and System.Configuration dll in the ServerGenerated project
Click to Enlarge


Add Download Button Click Code In Lightswitch Project




partial void Download_Execute() {
  // Write your code here.
  int fileId = this.Files.SelectedItem.Id;
  Dispatchers.Main.Invoke(() => {
    HtmlPage.Window.Navigate(new Uri(string.Format("{0}",
      String.Format(@ "Download.aspx?id={0}",
        fileId)), UriKind.Relative), "_new");
  });
}





Connection String In Web.Config File




Picture showing the _IntrinsicData connection string in web.config file
Click to Enlarge




Add Code In Webform’S Page Load


protected void Page_Load(object sender, EventArgs e) {
  if (Request.QueryString["id"] != null) {
    int id = Convert.ToInt32(Request.QueryString["id"]);
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["_IntrinsicData"].ConnectionString;
    conn.Open();
    DataSet ds = new DataSet();
    SqlDataAdapter adap = new SqlDataAdapter("select * from Files where Id = " + id, conn);
    adap.Fill(ds);
    if (ds != null) {
      HttpResponse response = HttpContext.Current.Response;
      response.Clear();
      response.ClearContent();
      response.ClearHeaders();
      response.Buffer = true;

      response.AddHeader("Content-Disposition", "attachment;filename=\"" + ds.Tables[0].Rows[0]["FileName"] + "\"");
      response.BinaryWrite((byte[]) ds.Tables[0].Rows[0]["FileContent"]);

      response.End();

    }
    conn.Close();
  }
}



Output


Picture showing the output of Upload and download file in Lightswitch 2011
Click to Enlarge

Picture showing the output of Upload and download file in Lightswitch 2011
Click to Enlarge

Picture showing the output of Upload and download file in Lightswitch 2011
Click to Enlarge

Picture showing the output of Upload and download file in Lightswitch 2011
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, June 2, 2012

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250