Articles → LIGHT SWITCH 2011 → Upload and download file in Lightswitch 2011

Upload and download file in Lightswitch 2011














































Software requirement











Prerequisite knowledge

















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 the file download.aspx in the project

Click to Enlarge




Click to Enlarge


Add download.aspx entry in project file





Click to Enlarge




Click to Enlarge




Click to Enlarge




Click to Enlarge




Click to Enlarge




Add dlls in lightswitch 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





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



Click to Enlarge


Click to Enlarge


Click to Enlarge


Click to Enlarge


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250