Month: June 2011

Editing Microsoft Office Files Using Open XML

To edit MS office files the best approach Available after Office 2007 onwards (when doc files became docx and ppt became pptx and so on) is to use Open Office SDK.

Initially editing doc files required MS Word to be installed on a particular machine but with Open XML format it is not the case. To better Understand how these files work now you can change the extension of the Word file to Zip instead of docx and unzip it. Explore through the files and folders available in the folder and you will get a fair idea about the scenario.

To begin with the demo here.

Say we have a requirement to Add Header to a Word Document or Say Replace the Header of a Word Document. For this requirement we already have a Code in SDK which can help us Out.

For that You can Search “How to: Replace the Header in a Word Processing Document” or go to given Hyperlink which has same code.

http://msdn.microsoft.com/en-us/library/cc546917.aspx

Create a Console Application and Add given References and Method to the application.

static void Main(string[] args)
{
AddHeaderFromTo(@”D:File.docx”, “This is The Header”);
}

Now here in the method we are passing file “File.docx” and Header “This is Header”.

This will add header to the file.
PS: This code will give exception if the file is not having any data or it is open. Do proper Exception handling for that.

For further reference you can go through sample codes provided by Microsoft.
Sample Code

Windows Phone 7 Emulator Crashed VirtualBox.

Today I noticed something Not so cool for me as I lost almost an hour of work. I was working on something using Virtualbox and in between felt like exploring The Windows Phone 7 development Kit that I recently Installed.

Now what I did was opened Windows Phone 7 Emulator and started playing with it like searched on Bing, Surfed web using its IE, Tried voice search on it etc…

Now I turned to Virtual box to see the code I was working on and There was a Yogi on the screen Informing me that Virtual box crashed and Then an Error message telling that It crashed because one Virtualization Application can be used at a Time.

After Searching on net Found these two discussions saying the same thing.

http://forums.virtualbox.org/viewtopic.php?f=6&t=39350

http://forums.virtualbox.org/viewtopic.php?f=6&t=40004

Crux of above is that you can’t have two Virtualization applications running together as well as you can’t have a virtual application running inside other like Windows phone 7 Emulator inside Virtualbox.

So the Virtual Box Crashed and I lost some work for Trying Windows Phone 7 Development Kit/Emulator.

Nice start in Smartphone apps Development. Lets See where it takes me further.

Sharepoint Exception: Trying to use an SPWeb object that has been closed or disposed and is no longer valid.

When I created sharepoint webpart and Used


using (SPSite site = new SPSite("http://Server:port/sites/Site/"))
{
using (SPWeb web = site.OpenWeb())
{
//Some Code Here.
}
}

It worked fine but before deploying I changed new SPSite(“http://Server:port/sites/Site/”) to SPContext.Current.Site and it started throwing the above exception on the Error Page but while debugging there was no Exception.

Weird issue and I don’t have any explaination for it but what helpd me solving the issue was the fact when we are passing Url to the SPSite it works fine.

So on the same lines I used SPContext.Current.Web.Url to fetch the Url of current siteand It worked like a charm.

So instead of above if we use


using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
//Some Code Here.
}
}

it works. 🙂

Issue with Silverlight Combobox SelectionChange event

We have a Silverlight Combobox and if there is a Silverlight SelectionChange event registered to it (in XAML) in that case the event is fired even when the first time Silverlight Application is loaded.


private void cmbSelection_SelectionChanged(object sender , SelectionChangedEventArgs e)
{
MessageBox.Show("Event Fired");
}

Above event will be fired and will show when the Application will load for the first time.

Other issue that you might face is Using
if(cmbSelection.SelectedIndex ==0)
{
}
in your event will throw exception.

The cause of above issue is that event is fired before the values for the combobox are initialized and the value for cmbSelection.SelectedIndex is null.

For resolving above both issues you can register the even after everything is initialized.
public MainPage()
{
InitializeComponent();
cmbSelection.SelectionChanged += new SelectionChangedEventHandler(cmbSelection_SelectionChanged);
}

Accessing Data from Sharepoint 2010 List in Silverlight Using Client Object Model

In Sharepoint 2010 Microsoft has come up with the APIs which can be used to access the data in client side execution like in ECMA script or Silverlight.

Here we’ll see How to Use Sharepoint Client Object Model in Silverlight ….

Creating Sharepoint Custom List

  • Create A custom list in Sharepoint 2010 Say”CustomerData”.
  • Add Columns to it Say “CustomerName”,”CustomerID””, “CustomerAddress” & “CustomerWebPage”

Creating Silverlight Project

  • Create a Silverlight project….
  • Add reference to the Following two dlls which can be found at following location (C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATELAYOUTSClientBin)

1. Microsoft.Sharepoint.Client.Silverlight
2.Microsoft.Sharepoint.Client.Silverlight.Runtime

  • Create a Class for Customer fetch Data in its object (Say in Separate file Customer.cs So as to create Less mess in One Place)

public class Customer
{
public String CustName{ get; set; }
public String CustID{ get; set; }
public String CustAddress{ get; set; }
public String CustWebPage{ get; set; }

public Customer(String Name, String Id, String Address, String hyperLnk)
{
this.
CustName= Name;
this.
CustID= Id;
this.
CustAddress= Address;
this.
CustWebPage = hyperLnk;
}

}
public class Customers : ObservableCollection
{

}

  • Add the Following Code to the User Control in Silverlight MainPage.xaml

  • Now Create A method to fetch the data from Sharepoint. All the calls we’ll be making to Sharepoint will be Async Calls as Silverlight doesn’t support Sync Calls.


private ClientContext context = null;
private Web web = null;
private List lst;
ListItemCollection lstCol ;
private delegate void UpdateUIMethod();
private Customers lstCust = new Customers();

public MainPage()
{
InitializeComponent();
fetchData();

}

public void fetchData(
{
context = ClientContext.Current;
web = context.Web;
lst = web.Lists.GetByTitle("CustomerData");

CamlQuery cmlQry = new CamlQuery();


cmlQry.ViewXml = "";

lstCol = lst.GetItems(cmlQry);

context.Load(lstCol,
items => items.Include(
item => item.Id,
item => item["CustomerName"],
item => item["CustomerID"],
item => item["CustomerAddress"],
item => item["CustomerWebPage"]));
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);

}

private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
{

UpdateUIMethod updateUI = LoadSiteData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
{

}

private void LoadSiteData()
{
Customers cust = new Customers();

string strName, strID, strHyperlink, strAddress



foreach (var val in lstCol)
{
strName= (val["CustomerName"] != null) ? val["CustomerName"].ToString() : string.Empty;
strID= (val["CustomerID"] != null) ? val["CustomerID"].ToString() : string.Empty;
strHyperlink = (val["CustomerWebPage"] != null) ? ((FieldUrlValue)val.FieldValues["CustomerWebPage"]).Url : string.Empty;
strAddress= (val["CustomerAddress"] != null) ? val["CustomerAddress"].ToString() : string.Empty;

lstCust.Add( new Customers() { new Customer(strTitle, strSummary, strCategory, strHyperlink) });
}

lstBox.ItemsSource = lstCust;

}


Above Code can be used to fetch Data from Sharepoint List and Show it in a list box.
Now it will be very easy to modify the above code as required to fetch data form any source in Sharepoint and use it in silverlight.

Disclaimer : Above code was a small part of project which I’ve extracted as a tutorial. In case any issue is there with the code please leave a comment and I’ll get back to you ASAP with the solution.

First time Error While working with Silverlight Pivot Viewer

Runtime Error in Silverlight Pivot Viewer

If you are working with Silverlight Pivot Viewer control for the first time and have created a basic Page using Pivot Viewer as explained here but still you are getting the Runtime error as shown below.

System.Windows.Markup.XamlParseException occurred
Message=Set property ‘System.Windows.FrameworkElement.Style’ threw an exception. [Line: 14 Position: 34]
LineNumber=14
LinePosition=34
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SilverlightPivotViewer.MainPage.InitializeComponent()
at SilverlightPivotViewer.MainPage..ctor()
InnerException: System.Windows.Markup.XamlParseException
Message=Element is already the child of another element. [Line: 0 Position: 0]
LineNumber=0
LinePosition=0
StackTrace:
at MS.Internal.XcpImports.CreateFromXaml(UnmanagedMemoryStream stream, String sourceAssemblyName, Boolean createNamescope, Boolean requireDefaultNamespace, Boolean allowEventHandlers)
at System.Windows.Controls.Control.GetBuiltInStyle(IntPtr nativeTarget, IntPtr& nativeStyle)
InnerException:

Then the quick resolution for this is to install Latest Silverlight tool kit (which is Apr 2010 release)

For resolving this error Download Silverlight Toolkit from here.

Step By Step Guide to Pivot Viewer Control in Silverlight.


This is going to be a basic post about “How to Use Pivot Viewer Silverlight Control”.

To begin working with the Pivot Viewer Silverlight control First Download and Install the Pivot Viewer Control from Pivot Viewer Home.

Once You install it it will create some dlls in C:Program Files (x86)Microsoft SDKsSilverlightv4.0PivotViewerAug10.

After we are done with the installation we need to create .CXML which we can use as a source to this control so that it can render our desired images.

For that we’ll be using Command line tool available which can be downloaded from Collection Tools link on the Page we downloaded the Pivot Viewer Control from.

Once the command line tool is downloaded unzip it and there will be Two Folders(bin, docs), EULA.docx, User’s Guide.docx inside it.

First Open docs folder so that we can use the XSLX and images provided. Here XSLX defines the Metadata of the images on basis of which we can search and filter it.

In other folder we have Pauthor.exe which can be used to create CXML from XSLX.

For creating CXML open pauthor in command prompt.

“cmd”

Navigate to folder where you have pauthor.exe

“CD C:UsersDownloadsPauthor-RC3Pauthorbin”

and then Execute the following command.

“pauthor /source excel CD C:UsersDownloadsPauthor-RC3Pauthordocssample.xlsx /target deepzoom C:Output”

After executing given command you will get a CXML file and folder structure , “Sample_Deepzoom”, it is referring to in the Output folder on C:

Once CXML and folder structure are created we can go ahead and create Silverlight Application to use Pivot Viewer we installed and CXML we created.

Create a Silverlight Applcation.

Add the Folder Structure “Sample_DeepZoom” and Sample.CXML in the SilverlightApp.Web Project created. (It is recommended to add the structure in client bin but here I’ve Created a new folder Pivot Data in my project and Added the folder and cxml to it.) to avoid cross domain issues add clientaccess policy.xml to the SilverlightApp.Web

ClientAccessPolicy.XML will contain given code.

Now add reference to “System.Windows.Pivot.dll” available in
“C:Program Files (x86)Microsoft SDKsSilverlightv4.0PivotViewerAug10bin” in SilverlightApp.

After adding reference add namespace
” xmlns:pivotcontrol=”clr-namespace:System.Windows.Pivot;assembly=System.Windows.Pivot””
to Mainpage.XAML

now add
to the grid in usercontrol.

and add

string pageUrl = HtmlPage.Document.DocumentUri.AbsoluteUri;
string rootUrl = pageUrl.Substring(0, pageUrl.LastIndexOf(‘/’) + 1);
PV.LoadCollection(rootUrl + @”Pivot data/Sample.cxml”, String.Empty);

to the Mainpage.xaml.cs after InitializeComponent() in MainPage().

You are good to go. Run your Application and you will see the Pivotviewer Up and Running.