Archive

Archive for October, 2009

Covert PowerPoint Slides to Images

October 9th, 2009 Anuraj P No comments

Today one of my colleague comes with a problem; he want to display a Powerpoint presentation in his Sharepoint site. But we didn’t got any direct way to display it. They we tweaked the code, to export the Slides to images and display it using the a custom slideshow web part, like the AjaxToolkit slideshow control.

I am attaching the code to export all the slides from a Power Point to Images

string ExportLocation = "C:\\Sample";
Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
ppApp.Visible = MsoTriState.msoTrue;
ppApp.WindowState = PpWindowState.ppWindowMinimized;
Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;
Microsoft.Office.Interop.PowerPoint._Presentation oPres = oPresSet.Open("C:\\ScreenShots.ppt",
            MsoTriState.msoFalse, MsoTriState.msoFalse,
            MsoTriState.msoFalse);
ppApp.ShowWindowsInTaskbar = MsoTriState.msoFalse;	//Hiding the application; But it will be displayed always
try
{
    Slides objSlides = oPres.Slides;	//Getting all the slides
    for (int i = 1; i < objSlides.Count - 1; i++)
    {
        string file = Path.Combine(ExportLocation, string.Format("{0}.{1}", objSlides[i].Name, "jpg"));
        oPres.Slides[i].Export(file, "jpg", 800, 600);
    }
}
finally
{
    ppApp.Quit();	//Closing the Powerpoint application. Sometimes it won't work too.
}

Thanks to ArunKumar, for providing the code snippet.

How to Store and Retrieve files from SQL Server Database

October 7th, 2009 Anuraj P No comments

The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for the client. So I thought it will nice to brush-up the ASP.Net skills.

Here is the code. I am using SQL Server 2008, but I am not using FileStream for the current project, I already wrote a post to how to
manage files with FileStream feature. In this post I am using nvarchar(MAX) datatype for storing the file content.

Table Design

CREATE TABLE [dbo].[tblFiles](
	[FileId] [uniqueidentifier] NOT NULL,
	[Filename] [nvarchar](255) NOT NULL,
	[FileContent] [varbinary](max) NULL
)

And the I set FileId default to newId() and FileContent default to NULL

ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileId]  DEFAULT (newid()) FOR [FileId]
GO
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileContent]  DEFAULT (NULL) FOR [FileContent]
GO

I wrote the code in C#. I am having a Asp FileUpload control and a button to upload the file, and a Repeater control with two controls, a label for displaying the filename and hyper link control for downloading the file.

<body>
<form runat="server">
<asp:FileUpload runat="server" ID="fileUploadImage" />
<asp:Button runat="server" ID="cmdUpload" Text="Upload File" OnClick="cmdUpload_Click" />
<asp:Repeater runat="server" ID="rptrFiles">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <asp:Label runat="server" ID="lblFilename" Text='<%# Eval("FileName")%>' />
            </td>
            <td>
              <asp:HyperLink runat="server" Target="_blank" ID="lbtDownload" Text="Download" NavigateUrl='<%# "Download.aspx?File="  + Eval("FileId").ToString() %>' />
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
</form>
</body>

Uploading the File to the Database
Code behind

protected void cmdUpload_Click(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(this.fileUploadImage.FileName);
    byte[] fileContent = this.fileUploadImage.FileBytes;
    using (SqlConnection connection = new SqlConnection("Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("INSERT INTO tblFiles(Filename, FileContent) VALUES(@Filename, @FileContent)", connection))
        {
            SqlParameter fileNameParameter = new SqlParameter("@Filename", System.Data.SqlDbType.NVarChar, 255);
            fileNameParameter.Value = fileName;
            SqlParameter fileContentParameter = new SqlParameter("@FileContent", System.Data.SqlDbType.VarBinary);
            fileContentParameter.Value = fileContent;
            command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
            command.ExecuteNonQuery();
        }
    }
}

And here is code to bind the repeater from the Database

DataTable dtFiles = new DataTable("Files");
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT FileId, FileName FROM tblFiles", "Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb"))
{
    adapter.Fill(dtFiles);
}
this.rptrFiles.DataSource = dtFiles;
this.rptrFiles.DataBind();

Download / Read the file from Database
And to download / read the file from Database, I am passing the File unique id to another page(download.aspx).I this page I am checking for the File querysting and based on that reading filecontent from Sql and writing it to Asp.net output stream. You can get more information about how to download files from IIS in this post.

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["File"] != null)
    {
        string fileId = Request.QueryString["File"];
        using (SqlConnection connection = new SqlConnection("Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=Sample"))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("SELECT Filename, FileContent FROM tblFiles WHERE FileId = @FileId", connection))
            {
                command.Parameters.AddWithValue("@FileId", fileId);
                SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    reader.Read();
                    byte[] content = reader["FileContent"] as byte[];
                    string filename = reader["FileName"].ToString();
                    Response.Clear();
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                    Response.AddHeader("Content-Length", content.Length.ToString());
                    Response.OutputStream.Write(content, 0, content.Length);
                    Response.End();
                }
            }
        }
    }
}

Please write to me if I missed something. Happy Programming .

Microsoft Community Tech Days

October 6th, 2009 Anuraj P No comments

Kerala Microsoft Users Group is organizing the Microsoft Community Tech Day in Trivandrum on 24th Oct 2009.

K-MUG Logo

Agenda

  1. 08:30AM – 09:15AM – Registration
  2. 09:15AM – 09:25AM – Welcome Speech
  3. 09:25AM – 09:45AM – Key Note Session
  4. 09:45AM – 05:00PM – Technical sessions

Technical Sessions

  1. Windows Azure & Clouds
  2. SQL Server tips
  3. Coding for Fun (Twitter, Orkut, Facebook, GTalk etc from .NET C#)
  4. SketchFlow for prototyping
  5. Windows Presentation Foundation (WPF)
  6. LINQ
  7. Writing Secure Code

For more details visit
http://k-mug.org/content/ctd09.aspx

Free Registration either at http://communitytechdays.com/(if you have live id)
or
http://www.eventbrite.com/event/418804656

Note: There can be some changes in Agenda based on the last minute updates