Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Jan 11, 2012

Reading the Custom Properties of MS Office Word 2007 & 2010 documents

Earlier, we have discussed about reading the Summary and Custom Properties of Word 2003 using DSO DLL.
Here are the articles references

As already mentioned in the above articles, DSO dll is a 32 bit and also it has OLE property reader class, which can read only the office 2003 documents.
The same DSO file cannot be used for reading the properties of 2007 & 2010. This is because, word 2003 stores the properties in OLE type and hence DSO has capabilities to read the properties. But word 2007 and 2010 stores in XML formats.

Want to know how the office 2007 & 2010 stores the properties in XML formats?
Change the extension of word 2007 or 2010 documents from .docx to .zip. Now extract the contents.
You will see many xml files inside that folder.
Now open the folder -> docProps folder -> 3 files will be there                     
 1.  App.xml – it stores the document’s summary properties
     2.   Core.xml – it stores the document’s summary properties
     3.   Custom.xml – it stores the document’s custom properties
The below snap shot shows the custom.xml file of a word 2007 document
It is possible to read the custom properties of word document using Office DLLs (which is deployed when you install a MS office in a machine).
But how to read the properties without using Office DLLs?
Hence, we will go for an open source dll provided by Microsoft called Open Office XML SDK 2.0.
The same can be downloaded from the below link
It has the capabilities to read the xml properties from the MS office documents.

Code snippet for reading custom the properties of word 2007 & 2010

public Dictionary<string, string> WDGetCustomProperties(string filename)
{
using (var package = WordprocessingDocument.Open(filename, false))
{
var properties = new Dictionary<string, string>();
var customProps = package.CustomFilePropertiesPart;
foreach (var property in package.CustomFilePropertiesPart.Properties.Elements<CustomDocumentProperty>())
{
                    if (property.Name == "Name")
                        Name = Convert.ToString(property.InnerText);
                    if (property.Name == "Expertise")
                        ExpertiseIn = Convert.ToString(property.InnerText);
                    if (property.Name == "Place")
                        Place = Convert.ToString(property.InnerText);
}
 return properties;
}
}
Note: Don’t forget to declare the 3 variables used for storing the values in theabove code.
Hence, this article shows you how to read the custom properties of the word 
2007 & 2010 documents.
To know how to create the custom properties in the Word 2007 & 2010 read 
this article.
Hope this helps You! Please free to comment.

Jan 6, 2012

Creating and Deploying a Visual Web Part using Microsoft Visual Studio 2010

To know about the Basics of Visual web part, read this article before knowing how to create and deploy the visual web part using visual studio 2010.
We will create a Visual web part for uploading the document to the SharePoint document library.
At the end of this article, we will learn
     1.How to create and deploy a Visual Web part
     2.How to programmatically upload a document to the SharePoint Document library

Open the Visual Studio and create a Visual Web Part project as shown below

When you click OK, you will see a pop-up window which will ask for the SharePoint site where the web part is going to be deployed as shown below. Hence give the proper URL of the SharePoint site. Also select the option Deploy as a farm solution because, visual web part is not a sandboxed solution

Once clicked Finish, you will see the project created with all the necessary files (assembly, .ascx files, feature to be deployed, .web part file) for a web part in the solution explorer as shown below

Click on the .ascx file and in the design mode, drag and drop the controls (FileUpload Control and Button) as shown below and complete the design part
I have added a JavaScript code which we used in this article for validating the file being uploaded is only .doc and .docx file.

Now, we will go for the coding the functionality of the web part. I have added a code in the Button1_Click event (Upload) of the web part as shown below

In the above code, give the proper name of the Document Library. I have used the default document library “Documents”.
Now Build the application and check for the errors. Once the build is successful, our web part is ready to be deployed in the SharePoint site.
It is very easy to deploy the visual web part. See the screenshot below.

That’s it. We have deployed our solution to the SharePoint site, which we have mentioned during creating the project.
Now, we will use the web part in our share point page.
Go to the SharePoint page -> Edit Page -> Insert web part -> Categories -> Custom -> Select the web part created (in our case I have named visualwebpart1)

Once added, we will see our web part designed in the SharePoint site page.

I will select a file and click upload. The file will get uploaded into the document library mentioned in the code.

Once Clicked Upload, the document is uploaded into the document library as shown below.

That’s it! We are done. We have learned to create and deploy the visual web part in SharePoint 2010.


Dec 23, 2011

Programmatically Creating Site Backup in SharePoint

In the previous article, we have discussed about creating and restoring the SharePoint site using stsadm command.
In this article, we will see how to take the backup of the site using SharePoint Object Model.The below is the code that will create the backup of the site and log the information in a log file.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SiteBackUp
{
    public class SiteBackup
    {
        static void Main(string[] args)
        {
         siteBackup("http://servername:portnumber","SharePointSiteBackup");   
        }
        public static void siteBackup(string siteURL,string fileName)
        {
            try 
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using(SPSite objSite=new SPSite(siteURL))
                    {
                        using(SPWeb objWeb=objSite.OpenWeb())
                        {
                            bool currentSiteStatus=objSite.AllowUnsafeUpdates;
                            objSite.AllowUnsafeUpdates=true;
                            bool currentWebStatus=objWeb.AllowUnsafeUpdates;
                            objWeb.AllowUnsafeUpdates=true;
                            string comment = objWeb.Title+"- Creating Backup is completed";
                            SPSiteCollection siteCollection=objSite.WebApplication.Sites;
                            objSite.ReadOnly=true;
                            string time=DateTime.Now.ToString("dd-MM-yyyy");
                            string backupName= "D:\\SiteBackup\\Backup" + fileName+"_"+time+".bak";
                            siteCollection.Backup(siteURL,backupName,false);
                            objSite.AllowUnsafeUpdates=currentSiteStatus;
                            objWeb.AllowUnsafeUpdates=currentWebStatus;
                            if(objSite.ReadOnly==true)
                            {
                               objSite.ReadOnly=false;
                               siteBackupLog(comment);
                            }                        
                         }
                    }
                });
            }
            catch (Exception ex)
            {
                SPSite site = new SPSite(siteURL);
                if (site.ReadOnly == true)
                    site.ReadOnly = false;
                siteBackupLog(ex.Message);
            }
        }
        public static void siteBackupLog(string message)
        {
            string PathName = "C:\\SiteBackup logs\\";
            PathName = PathName + "Backuplog-" + DateTime.Now.ToString("dd-MM-yyyy") + ".log";
            StreamWriter sw = new StreamWriter(PathName, true);
            sw.WriteLine(message + " - " + DateTime.Now);
            sw.Flush();
            sw.Close();
        }
    }
}

Hence, we can automate creating backup of the SharePoint site using code. Also, the whole code created in visual studio can be downloaded here.
Happy Coding!

Dec 20, 2011

Creating a Simple Silverlight Application in Microsoft Visual Studio 2010

In the previous article ,we have discussed about the basics of Silverlight and In this article, we will discuss how to create a simple silverlight application using Microsoft Visual Studio 2010.
Go to Visual Studio File ->New Project
                                           
Select Visual C# in projects -> Silverlight Application (I have used .Net Framework 4.0)
Now, you will see a pop-up window like this
This windows gives the options for the user to create a new web application within the solution so that, we can test the silverlight application created here.
Here in our project, SampleSilverlightApplication.web is the web application created and we also select the silverlight version here.
Once clicked OK, a new silverlight application will be created as shown below
You will two projects created in the solution one is to design and code the application and the other is to test the application.
MainPage.xaml contains the design part of the application and MainPage.xaml.cs is the code behind where you will write the business logic.
In the right side, you will see the ToolBox which consists of Silverlight Controls which you can use for designing the application.
Now drag and drop a Label and Button in the design part and Right Click on the control -> Properties to view the properties of the control


I have changed the properties of label and button

In the .cs file, you will see the NameSpaces for the silverlight application in specific has been added.
Now, we will write the code behind for the button event as
Private void button1_click (object sender, EventArgs e)
{
MessageBox.Show(“This is a simple silverlight Application”);
}

Now save the code and debug the application. The application will render in the web application created in the initial steps.

Important Note: Once you debug the code, you will find solution package with the extension .xap in the Client Bin folder which is present in the Web Application.

This package consists of all the functionalities which is created in the application. 
When you click on the “Click this” button you will see a MessageBox pop-up with the message showing message “This is a simple silverlight Application”





That’s it we have learned how to create a simple silverlight application using Microsoft Visual Studio 2010.
See also, how to deploy the created silverlight application SharePoint 2010 in this article.
The full code can be downloaded from here.

Dec 15, 2011

Creating Custom properties in Word 2003

In the articles Part I,Part II and Part III we have discussed about how to read the custom properties of word 2003 using  DSO dll in C# .Net.
In this article we are going to see about creating a bookmark and set the custom properties for the Microsoft Word 2003.
Steps
1. Open the Microsoft Word 2007 and create a new word document.
2. For creating the Bookmark, we need Forms option in the Microsoft Word Menu.
3.  Right click on the Menu bar and you will see forms options and check the option you will see the forms menu
4.   Then click the Textbox option (will be having a symbol ”ab”)

5.  Insert a text box and mouse click to see the properties.
6.   Now in the Bookmark option give the property name (here I gave it as CompanyName )

7. Now go to File Menu->properties-> Custom properties tab as shown below

8.  Now in the Name field give the Name (I gave as TestCompany) and check the Link to Content so that you will see the bookmark created and link the content we have created (CompanyName)
9. Now you will see the added property as below.

10. Click Add and now the properties are set. If you type a value in the document, the value must be assigned and you can see in the properties as shown below.
So, once the properties are set we can read the values using c# .Net.
Enjoy! 




Dec 12, 2011

SlideShow with Thumbnails using Silverlight for SharePoint

I would like to share a link which shows how to create a Slide Show for SharePoint using Silverlight in Microsoft Visual Studio 2010.


Dec 11, 2011

Reading Custom Properties of Word Document

Part III
Read the Introduction about this article Part I
Read about reading the summary properties of word document in this article Part II
In this post, we can see what is the code for the reading the custom properties of the word document.
public static void GetDocumentCustomProperties(string filename)
{
            OleDocumentPropertiesClass doc = new OleDocumentPropertiesClass();
            doc.Open(filename, true, dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
            //Reading and writing the custom properties to a file
            StreamWriter sw1= new StreamWriter(@"D:\FileRead_Custom.txt");
            CustomProperties obj_CustomProp = doc.CustomProperties;
            foreach (CustomProperty custom_prop in obj_CustomProp )
            {
                sw1.WriteLine(custom_prop.Name   "    "   custom_prop.get_Value());
            }
            sw1.Close();
            doc.Close(false);
}
Hope this helps you!

Reading Summary Properties of Word Document

Part II
Read the Introduction about this article Part I
In this post, we can see what is the code for the reading the summary properties of the word document.
public static void GetDocumentSummaryProperties(string filename)
{
            DSOFile.OleDocumentPropertiesClass doc = new DSOFile.
            OleDocumentPropertiesClass();
            doc.Open(filename, false,

            DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess );

            //getting the properties of the document
            DSOFile.SummaryProperties summaryProp = doc.SummaryProperties;

            //reading and writng the summary properties to a file
            string author = summaryProp.Author;
            string comapanyName = summaryProp.Company;
            string managerName = summaryProp.Manager;
            StreamWriter sw = new StreamWriter(@&quot;D:\FileRead.txt&quot;);
            sw.WriteLine(author);
            sw.WriteLine(comapanyName);
            sw.WriteLine(managerName);
            sw.Close();
}
That’s It. Enjoy Happy Coding!
Also, read how to Read the Custom Properties of Word Document Part III

Reading Document Properties

Part I
We are going to discuss about a interesting topic which can be used in SharePoint and also in .Net.
It is possible to reading the summary properties and custom properties of the word document and it is also one of the requirements now a days.
This can be done through using DSO dll which can be downloaded from the below link
(Important Note: This is a 32 bit dll )

What is DSO dll ?
The Dsofile.dll sample file is an in-process ActiveX component for programmers that use Microsoft Visual Basic .NET or the Microsoft .NET Framework. You can use this in your custom applications to read and to edit the OLE document properties that are associated with Microsoft Office files, such as the following: 
• Microsoft Excel workbooks
• Microsoft PowerPoint presentations
• Microsoft Word documents
• Microsoft Project projects
• Microsoft Visio drawings
• Other files that are saved in the OLE Structured Storage format
The Dsofile.dll sample file is written in Microsoft Visual C++. The Dsofile.dll sample file demonstrates how to use the OLE32 IPropertyStorage interface to access the extended properties of OLE structured storage files.
Features of this DLL
1. This dll is 32 bit and can read only Microsoft word 2003 (ie., .doc) formats only.
2. It has a OLE property reader class which can read the properties of the word document.
3. Using this dll, we can read both the Summary properties and also the Custom properties we create for the documents.
4. Also with this dll, we can set the custom properties programmatically.

Also, Read how to extract the summary properties of the word document in this article Part II.

Copying the File from and to Document Library in SharePoint

Let’s see how to copy the file from and to the document library using object model.
SPSite site = new site("http://siteurl");
using (site)
{
    SPWeb web = site.OpenWeb();
    using (web)
    {
        SPList lib1 = (SPDocumentLibrary)web.Lists["lib1"];
        SPList lib2 = (SPDocumentLibrary)web.Lists["lib2"];
        SPListItem item1 = lib1.Items[0];
        byte[] fileBytes = item1.File.OpenBinary();
        string destUrl = lib2.RootFolder.Url   "/"   item1.File.Name;
        SPFile destFile = lib2.RootFolder.Files.Add(destUrl, fileBytes, true);
    }
}

That’s it! Happy coding!

Nov 24, 2011

Checking whether a file uploaded is of .doc or .docx file format

We can use the Java Script to check whether the file uploaded is of 2003 or 2007 word format. Hence we can handle the validation in the client side.
Java Script
<script type="text/javascript" language="javascript">
   function FileFormatValidate()
   {
        var uploadControl = document.getElementById('<%=FileUpload1.ClientID%>').value;
        //Regular Expression for the fileupload control.
        var reg = /^(([a-zA-Z]:)|(file://%7b2%7d/w )/$?)(//(/w[/w].*)) (.doc|.docx|.DOC|.DOCX)$/;
        //Checking if the file is empty or not
        if (uploadControl.length > 0) 
        {
            //Checks with the control value.
            if (reg.test(uploadControl)) 
            {
                return true;
            }
           else 
            {
                //If the condition not satisfied shows error message.
                alert("Only .doc, docx files are allowed!");
                return false;
            }
         }
        else 
        {
            //If the File is Empty or No File is  selected to upload shows this 
error message.
            alert("Please select a file to Upload");
            return false;
        }
    } //End of function FileFormatValidate.
</script>
Design
<p style="height: 28px; width: 216px">
    <asp:Button ID="btn_Upload" runat="server" Height="25px" 
        onclick="btn_Upload_Click" OnClientClick="return FileFormatValidate();" Text="Upload" Width="128px" />
</p>

Hence you can validate and check the file being uploaded at the client side using this code. This can be re-used for any file formats by changing the Regular Expression.
Happy Coding!!!