Wednesday, August 24, 2011

SharePoint 2010 Managed Client Object Model. How to Get Site Properties?


Silverlight applications use this Managed Client Object Model .In the Client Object Model, each line of statement that requires some site information is a request to the server, the server responds to the request and the Response is packed into a Client Object which is easy to use. In Client Object Model we cannot get all the required data on a single request as the data is too big SharePoint uses On Demand serve request methodology for the Client Object Model. The developer should take care when getting data from the server.He should request minimal information he needs from the Server using LINQ filter queries.

Below is the code to Get Site Properties.

PropertyValues pValues = null;
string siteCollectionUrl = string.Empty;  // stores sitecollection url;
string siteUrl = http://yoursitename ; // site url, may be site under a sitecollection;
string PropertyIDValue = string.Empty;



private void LoadSite()
        {
            ClientContext ctx = new ClientContext(siteUrl);
            siteCollection = ctx.Site;                     
            ctx.Load(siteCollection, s => s.Url);
            ctx.ExecuteQueryAsync(GetSiteRequestSucceeded, RequestFailed);
        }

        private void GetSiteRequestSucceeded(object sender, SP.ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                siteCollectionUrl = siteCollection.Url;
                ClientContext ctx = new ClientContext(siteUrl)
                currentWeb = ctx.Web;
                ctx.Load(currentWeb, w => w.Title, w => w.ServerRelativeUrl, w => w.AllProperties);
                ctx.ExecuteQueryAsync(GetWebRequestSucceeded, RequestFailed);
            });
        }

        private void GetWebRequestSucceeded(object sender, SP.ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                pValues = currentWeb.AllProperties;
         ClientContext ctx = new ClientContext(siteUrl) ;
         ctx.Load(pValues);
                context.ExecuteQueryAsync(GetPropsSuccess, RequestFailed);
                }
            });
        }

        private void GetPropsSuccess(object sender, SP.ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
              this.PropertyIDValue = (string)pValues.FieldValues["propertyid"];
             
            });
        }

       

private void RequestFailed(object sender, SP.ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show("Error occured:  " + e.Exception);
            });
        }

How to open Modal Popup from Silverlight in Sharepoint 2010 using Visual Web part


In our application we are using Silverlight to display some of the site information. I have created a Silverlight Application and deployed the XAP file in the Site root using Module.
In the Silverlight application we are showing SharePoint users as hyperlinks. When we click on the user, a SharePoint dialogue should open which opens the user info page. We know that we can call java script functions from Silverlight using the command .But if use SharePoint 2010 Built in SharePoint Silverlight Web part, we cannot define the JavaScript function that relates to this Silverlight application.
So I have created a Visual Web part which holds silver light object (the XAP file) in it, the syntax is as simple as we add Silver light Object (XAP file )to the html file.
Note: If we use Visual Web Part, then the ClientContext .Current object in Silverlight will return null value.So we need to change our code from ClientContext ctx = ClientContext.Current
 to  ClientContext ctx = new ClientContext(siteCollectionUrl);

Here siteCollectionUrl will be passed to the Silverlight using initparams from the Visual Web part that holds the Silverlight Object. Below is the code.
SilverVisualWPUserControl.ascx
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SilverPropertiesTabUserControl.ascx.cs" Inherits="DLRSilverTab.SilverPropertiesTab.SilverPropertiesTabUserControl" %>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {

            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }
            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }

        function OpenDialogueWidow(url) {
            var options = SP.UI.$create_DialogOptions();
            options.width = 750;
            options.height = 650;
            options.url = url;
            options.dialogReturnValueCallback = Function.createDelegate(
                        null, portal_modalDialogClosedCallback);
            SP.UI.ModalDialog.showModalDialog(options);

           
        }

        function portal_modalDialogClosedCallback(result, value) {
           
        }

       
    </script>
   
    <div id="silverlightObject" runat="server"></div>

SilverVisualWPUserControl.ascx.cs Page_Load method
protected void Page_Load(object sender, EventArgs e)
        {
            string siteCollectionUrl = SPContext.Current.Web.Url;
           
            string html =string.Format("<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" "
            +"style=\"display:block\" height=\"250px\" width=\"100%\"  >"
            +"<param name=\"source\" value=\"/SilverTabControl.xap\"/>"
            + "<param name=\"onerror\" value=\"onSilverlightError\" />"
            + "<param name=\"background\" value=\"white\" />"
            + "<param name=\"minRuntimeVersion\" value=\"2.0.31005.0\" />"
            + "<param name=\"initParams\" value=\"PropertyList=Property Information,PropertyContactList=Properties,PropertyID=Property_x0020_ID,PropertyIDValue=1,Duration=6000,url={0}\" />"
            + "<param name=\"autoUpgrade\" value=\"true\" />"
            + "<a href=\"http://go.microsoft.com/fwlink/?LinkID=124807\" style=\"text-decoration: none;\">"
            + "<img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Get Microsoft Silverlight\" style=\"border-style: none\"/>"
            + "</a></object>"
                  +"<iframe style='visibility:hidden;height:0;width:0;border:0px;' scrolling=no></iframe>",siteCollectionUrl);
            silverlightObject.InnerHtml = html;
        }


Silverlight Application MainPage.xaml.cs  How to invoke JavaScript Method to open Dialogue Window.
HyperlinkButton contactLink = new HyperlinkButton();

            contactLink.Click += new RoutedEventHandler(contactLink_Click);

            contactLink.Tag = new Uri("/_layouts/userdisp.aspx?ID=" + spUser.Id);
            contactLink.Cursor = Cursors.Hand;


void contactLink_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link= sender as HyperlinkButton;
            if(link!=null && link.Tag !=null)
            HtmlPage.Window.Invoke("OpenDialogueWidow", link.Tag.ToString());
        }

In the above Code OpenDialogueWidow is the JavaScript  function name which defined in the Visual Web part

Tuesday, August 09, 2011

SharePoint 2010 Getting List Item Attachments using Silverlight Client Object Model


I did a lot of research to get list item attachments. I have searched in forums but found no solution.
Using Client Object Model, we cannot get List Item Attachments collection, client object model will return a list item object, but the object doesn't contain the attachments collection info and supports no methods to get attachments collection.
  The alternative method is calling web service method GetAttachmentCollection from the service lists.asmx. This method returns the result in the form of XMLNode. Here is the sample code which works perfectly.
The below example Gets the list item from a given list, then Gets its first image attachment and shows it in the Silverlight Image Control.
Add the below line in the import section to import SharePoint.Client dll.
using SP = Microsoft.SharePoint.Client;

Here follows the code. This code I have copied from my Visual studio and formatted here to relate it to the post, I may forgot to declare some of the variables, but once you copy this code in to your Visual Studio, you can easily fix those compilation errors.

SP.ClientContext context;
SP.Web spWeb;
SP.Web currentWeb;
SP.List propertiesList;
string serviceUrl = string.Empty;
SP.ListItemCollection listItems;
 
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
 
private void RequestFailed(object sender, SP.ClientRequestFailedEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Error occured: " + e.Exception);
});
}
 
 
private void GetRequestSucceeded(object sender, SP.ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
serviceUrl = e.Request.WebRequest.RequestUri.AbsoluteUri;
serviceUrl = serviceUrl.Substring(0, serviceUrl.IndexOf("_vti_bin"));
foreach (SP.ListItem item in listItems)
{
   GetAttchmentCollection(item.Id.ToString());
}
});
}
 
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName,id);
}
 
void oClient_GetAttachmentCollectionCompleted(object sender, ServiceReference1.GetAttachmentCollectionCompletedEventArgs e)
{
XElement element = e.Result;
string attachments = element.Value;
string[] splitString = { "http" };
string[] attchmentArray = attachments.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < attchmentArray.Length; i++)
{
string extension=System.IO.Path.GetExtension(attchmentArray[i]).ToLower();
if (extension == ".png" || extension == ".jpg" || extension == ".jpeg" || extension == ".tif")
{
DownloadAttachedFileFromListItem("http" + attchmentArray[i]);
break;
}
}
}
 
 
public void DownloadAttachedFileFromListItem(string fileName)
{
using (ClientContext clientContext = new ClientContext(serviceUrl))
{
File.OpenBinaryDirect(clientContext, "/" + fileName.Replace(serviceUrl, ""), OpenBinaryFileSuccess, OpenBinaryFileFailure);
}
}
 
void OpenBinaryFileSuccess(object o, OpenBinarySucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
BitmapImage bitmapimage = new BitmapImage();
bitmapimage.SetSource(e.Stream);
imgPhoto.Width = bitmapimage.PixelWidth > imgPhoto.ActualWidth ? imgPhoto.ActualWidth : bitmapimage.PixelWidth;
imgPhoto.Height = bitmapimage.PixelHeight > imgPhoto.ActualHeight ? imgPhoto.ActualHeight : bitmapimage.PixelHeight;
imgPhoto.Source = bitmapimage;
});
}
 
void OpenBinaryFileFailure(object o, OpenBinaryFailedEventArgs e)
{
}