Wednesday, October 27, 2010

ExcelService - RangeCoordinate

small discription about range coordinat, cause I was pretty confused while using it, so sharing my exp
RangeCoordinates rngCrd = new RangeCoordinates();


rngCrd.Row = 0;


rngCrd.Column = 0;

rngCrd.Height = 3;

rngCrd.Width = 10;
 
.Row = start Row
.Column = start column
.Height = no of rows. in this case total three rows.
.Width = no of columns, total ten columns.
 
So the above line mean, range starting from 0th row,0th column and ending at 10th column of 3rd row.
 
Happy coding

Tuesday, October 26, 2010

ExcelService, You donot have permission to open this file

Hi All,

I was getting this error from 3-4 days, and it was becoming frustrating, since the error is resolved I want to share my experience with all of you. The error from ULS log is-
1.       From ULS log the error is -            w3wp.exe (0x1EC0)                       0x21B4  SharePoint Server                           Logging Correlation Data               xmnv     Medium               Result=Id=OpenWorkbookAccessDenied; Microsoft.Office.Excel.Server.CalculationServer.FileOpenException: You do not have permissions to open this file. ---> Microsoft.Office.Excel.Server.Host.HostFileException     at Microsoft.Office.Excel.Server.MossHost.MossHostFileLoader.GetSPFile(IClaimsIdentity claimsIdentity)     at Microsoft.Office.Excel.Server.MossHost.MossHostFileLoader.CheckForPermissions(IClaimsIdentity claimsIdentity)     at Microsoft.Office.Excel.Server.MossHost.MossHostHelperMethods.<>c__DisplayClass4.b__2()     at Microsoft.Office.Excel.Server.MossHost.MossHostHelperMethods.WithEnsureClaimsIdentitySetOnThread(IClaimsIdentity claimsIdentity, MethodToRun action)
  • In my case ClaimsToWindows was set correctly,
  • file  was under trusted file location
  • App Pool account was added as owner in comtentDB
So nothing was helping me. Lastly I run the configwizard, which ended up in running farm config wizard (I did farm config earlier, noting helped). I cross varified web.config and what helped is -

IIS authentication settings :) The site and sharePoint web services both should run with "Windows Authentication" and it was resolved.
Some times we miss very simple point and that hurts badly :)

Keep programmig...

Thursday, October 21, 2010

Operations started by an earlier run of the Farm Configuration Wizard are still in progress

 "Operations started by an earlier run of the Farm Configuration Wizard are still in progress. You must wait for those operations to complete before running the wizard again. You can monitor the status of these operations by looking at the "Farm Configuration Wizard" timer job on the Timer Job Status page in the Monitoring section of Central Administration"

Was the error and unable to run "farm configuration wizard". after some lookups I got TimerJob Status and job named "Farm configuration wizard" which was disabled, so deleted that and I got the option to re-run it again :)
cheers

Wednesday, August 11, 2010

URL for webpart Maintenance Page

Tip -
Sometimes it happens that any web part wrongly added to page and then breaking the complete functionality of page not even giving option to web part Maintenance Page..what's then?
In the URL directly append   "?contents=1"  will take you to web part maintenance page and delete the culprit.
so for example my default page is throwing error and the URL is http//<>/pages/default.aspx, then the url for content Page is http://%3c%3e/Pages/default.aspx?contents=1

Cheers

Monday, July 26, 2010

SharePoint, Javascript and Content Place Holder

Hi,

want to add JavaScript in contentPage. Most of the time there are two ways -

1. Add javascript in master Page (as it can be added in <Head>)
2. Add javascript in Content Editor.

While coding I came across third way, which is very use full when you donot have web part zone (like Xlviewer.aspx) so there is no option of adding content editor web part, below is the coding style in content Page -

<asp:Content ContentPlaceHolderId="customCEPlaceHolder" runat="server">


<script type="text/javascript">
// <![CDATA[
function testing()
{

};

function getArgs() {

var args = new Object();
var query = window.location.search.substring(1);
var cntString = query.split("&");
var val=cntString[0].split('%2F');
var val1=decodeURI(val[1]);
var val2=decodeURI(val[2]);
var tempUrl = "/_layouts/temp.aspx?itemName="+val2+"&listName="+val1;
var myUrl = "/pages/gl.aspx?itemName="+val2+"&listName="+val1;
var caUlr = "/CA%20Collaboration/Forms/AllItems.aspx?itemName="+val2+"&listName="+val1;
//document.forms[0].action = caUlr ;
//document.forms[0].submit();


window.open(myUrl,'_self');

}
_spBodyOnLoadFunctionNames.push("testing");
// ]]>
</script>
</asp:Content>

_spBodyOnLoadFunctionNames.push ensures that your function executes on page_load so it is equal as saying <page onLoad="" >

Try this you are saved from writting code for web part zone or saved from touching the master Page.

Cheers

Thursday, July 8, 2010

Ribbon from SharePoint 2010 Pages

hi,

Just to share - Any body wants to get rid off top ribbon comes in every page with sharePoint? just comment javascript function -DisplayRibbonDiv();


when it is commented it will display ribbon on top, otherwise it won't.
 
Cheers :)
Ruchi

Monday, July 5, 2010

SharePoint Designer and 404 file not found, MasterPage using features and 404 error

hi,
Lastly I was working on masterpage, since my sharepoint portal integrates asp.net pages (old asp.net pages which includes runat=server) I am using MasterPage deployment using features. Everything was working perfactly fine. Suddenly I thought, I need some changes in UI and the debugging and troubleshooting started.

The issue is thus deployed masterpage, whenever I change and save, and again try to see it in browser it is giving me '404, resource or one of its dependacny could not be found' oh God. every thing was there not sure what I was missing.

After hours of struglling I thought to open master page using notepad rather than SharePoint Designer, oh and it worked like charm. the error gone. I am not sure what changed SPD was doing in file when I am opening it using SPD.

Posted this just to save time others struggling like me :)

Good Old  Notepad saved life.

Thursday, May 27, 2010

JSOM or Excel Service Java Script Model

hi,

It's high time to reveal another screte which microsoft is shipping with SPS 2010. For some it may not be screte but I am sure the code snippet is screte for most of the readers. let's jump to topic directly.

The New functionality is Editable excel sheet, which means the user can edit sheet in EWA. more detailed is - developer uses Excel Web Access EWA to render excel sheet in SharePoint, Till MOSS it was just readonly now user can edit the sheet there only. How it is possible?
The developer team introduced another property 'Allow Type and Formula' which is visible from web part properties, once this check box is checked user can edit the sheet right away.


 now why I am so excited about this -> hey it gives us javascript based Object Model to interact with rendered sheet. Ideally what I do is use on content editor web part and assosiate it wih .txt file which contains javascript code.

So below is small snippet about setting selected value using Javascript OM -

function setCellValue(selectedValue)

{
ewa= Ewa.EwaControl.getInstances().getItem(0); // --get handle of currently rendered workbook

workbook = ewa.getActiveWorkbook(); // handle of active workbook;
rangelocal = workbook.getActiveCell(); //handle of active cell
var column = rangelocal.getColumn(); //
var row = rangelocal.getRow();
var valueArray = new Array(1);
valueArray[0] = new Array(1);
valueArray[0][0] = selectedValue;
rangelocal.setValuesAsync(valueArray,asyncCallbackSet,'SetValue');
}
function asyncCallbackSet(asyncResult)
{
}
lets talk highlighted Text. we will reverse track here, will start from green one.
  • setValuesAsync() is the function responsible for setting range value using async call back.
  • asyncCallbackSet is my call back function,  'SetValue' is context.
  • valueArray this is the 2-Dimensional array contains value for the cell. Now why it is 2 - dimensional as it is excel where cell is row and column, so the first index represents row and second column.
since I just wanted to set value of one cell I my array is of length one but it has to be two -dimension as second dimension represents column value.
asyncResult gives option to trace error using asyncResult.getCode()  and asyncResult.getDescription()
excecute this simple code and feel the power.

worth mentioshing is since SPS 2010 supports silverlight OOB , and communication between Silverlight and Javascript is possible ..now the power is just double :) and this Object model give you control for excel  events like cell changed, tab out etc.
Enjoy :)

Monday, May 17, 2010

SharePoint 2010 Certification

hi,

let's wait for new certication from microsoft till then use below information to be ready for first exam :)
70-573 - 12th July 2010
For more about this -
keep waiting :)

Friday, May 14, 2010

XDocument, Creating XDocument Progamatically

hi,
Just a simple how to, The code below will let you create XML document in Silverlight.
Silver light does not support XmlDocument, but it gives us XDocument with similar functionalities, which is in System.Xml.Linq.  Below is code -

Object[]  xmlNodes = new Object[5];
xmlNodes[1] = new XElement("Person",new XElement("Name","XX"),new XElement("Age","2"));
xmlNodes[2] = new XElement("Person",new XElement("Name","YY"), new XElement("Age","3"));

XDocument xDoc = new XDocument (new XDeclaration("1.0","utf-16","Yes"),new XElement("Root",xmlNodes);

Wow! done The out put is -
<xml version="1.0" coding="utf-16" standalone="yes">
<Root>
<person>
 <name>XX</name>
<age>2</age>
</person>
<person>
<name>YY</name>
<age>22</age>
</person>
</Root>
So what happened actually -
XElement is responsible for creating any node, it takes Node name and value, or object array of values.
XDeclaration is resposible for Xml declaration if
and XDocument is replacement for XmlDocument.
So we create object of XDocument and used Add method to add elements into it.
cheers !!

Tuesday, May 4, 2010

SharePoint 2010 capacity, boundry and limits

The best collection of information -
http://www.microsoft.com/downloads/details.aspx?FamilyID=66438e41-5733-448a-bd76-a8052b394fe2&displaylang=en

Left navigation, quick launch, V4.master,create web Page and Team lists

Hi all,
Back to work after 15 days of break :) and below are my recent findings -
There are two ways to create page using UI ->
  • _layouts/spcf.aspx 
  •  siteActions->new web page.
by default the second option (site Actions->new web page) gives you left navigation whereas the first one just gives place holder for content.
So in second one user can get left navigation and quick launch, where as if you start with first approach to get left nav you might be prompted to create subsite, which is wrong. Most of the time people create subsite just to get navigation correctly.
Ideally to get Navigation ->
Site Actions->Site settings->Navigation.
here user will see two options
  • Global Navigation - Ideally the top navigation
  • Current Navigation - Left Navigation
User can create new page and then add them to any navigation area using Add heading and Add links.

In the same excersie I wanted to have link list, team discussion when using Publishing Template for portal,on first glance I didn't find it,
Activate site features 'Team Collaboration Lists' and you will get the all and new type of lists.

so I got required UI without coding and without creating any subsite :)
Try it.

Tuesday, March 30, 2010

Developer Dashboard

hi,
A new capability to debug and deep analysis is named "Developer Dashboard". Actually it gives the much information about the rendered page, once this is 'ON' the developer can see ->
  1. Time taken to render by each method in page life cycle
  2. information about page, current user, page status etc
  3. Time taken by database queries
  4. Time taken by web part to render [each web part]
etc
The command to enable Daveloper Dashboard is -
stsadm -o setproperty -pn developer-dashboard  -pv ondemand
[The -ov options are On, off, Ondemand]
after the command is completed successfully a small icon on top left [next to currentlyLog in user] will appear.

The informtion on bottom of page is - This informtion can be used for deeper
analysis of performance.

 

Cheers for debugging !!

Wednesday, March 24, 2010

Document Set, Knowledge Managment And MetaData

Hi,

 
I was just going through knowledge management options with SPS 2010, I find some very basic steps to create a KM store within minutes [of course you should have taxonomy or atleast some thoughts in ready :) ]

 
Document Set and Meta Data service plays a important role in KM management. So let;s have a one liner of both of these -

 
Document Set -> Obvious from name documents can be grouped within one set, can be created from base content type 'Document set'.

 
Meta Data Service -> Another service given by SPS 2010, helps in adding meta data with documents. Since this is a service, term set defined in one service can be consumed by different web applications in different FARM altogether.

 
So below is the idea for KM in sps 2010 [The first step is optional, you can directly start from CA]-

 
  • Choose on source web app [from thsi web app you can easily modify content type]
  • Goto CA -> ManageService Application
  • Select the Manage ServiceApplication proxy. The UI will look like [Fig-1]

 
 
 
  • After creating term set, goto Site->Site Settings->Galleries -> Site Content Type
  • Create New contet type with base type as 'DocumentSet'.
  • Goto Document Library, from advanced settings, enable content type.
  • Now come to document upload of Document Library, you will see 'DocumentSet' right there !!.

 
In part 2 we will see KM from these information.

Thursday, March 11, 2010

ASP.net Integration with SharePoint 2010

Hi,

 
from Couple of days I was trying to integrate asp.net application into SPS 2010. The integration was simple, but the glitch was the asp.net files were written in asp style, those pages were written in early days of .net. So I did we appraoch to this problem, below are some technical points in this direction -

 
Some how we need the old story , .aspx pages and corresponding dll deployed to bin or GAC.

 
For this simple requirement, we created new project of type 'web application' [this ensures out put as dll], deployed it to bin and added entry in <safe control> in web.config. [I was getting can not load type as not registred as safe, after struggling with this stupid error, I created simple console application, used reflection and cheked out what are the classes in this namespace, once done, the code was running like anything]

 
now comes the tricky part, how to integrate the pages, I tried importing them to contentDB using SPD [nothing worked]
Then used features to deploy the pages and worked like charm :)
The integration done :)

 
Few more technical points in this journey -
  • Added each page within master page.
  • used ContentPlaceHolderMain for displaying the pages.
  • When integrating frame and iframe gave some problems.
  • controls were accessible using document.getElementById(), rather then document.formname.elementName.[even within window.opener]
  • Since the controls were simple html control need not to use &lt%=.ControlID%&gt
  • have to remove runat="server" from &ltForm&gt
Hope this will help you if you are trying something similar on these lines :)

Tuesday, March 9, 2010

V4.0 master page with just placeHolder

hi,

Today I created very basic master page i just has required placeholder, since I could not find it over net I thought let's post it, may be some body else will find it usefull :) below is code -
<%@ Master Language="C#" %>
<%@ 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" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="Welcome" src="~/_controltemplates/Welcome.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="MUISelector" src="~/_controltemplates/MUISelector.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="<%$Resources:wss,language_value%>" xmlns:o="urn:schemas-microsoft-com:office:office" runat="server" dir="<%$Resources:wss,multipages_direction_dir_value%>" __expr-val-dir="ltr">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<meta name="GENERATOR" content="Microsoft SharePoint"/>
<meta name="progid" content="SharePoint.WebPartPage.Document"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Expires" content="0"/>
<SharePoint:RobotsMetaTag runat="server"/>
<title id="onetidTitle"><asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server"/></title>
<SharePoint:CssLink runat="server" Alternate="true"/>
<SharePoint:Theme runat="server"/>
<SharePoint:CssRegistration Name="minimalv4.css" runat="server"/>
<SharePoint:CssRegistration Name="layouts.css" runat="server"/>
<SharePoint:ULSClientConfig runat="server"/>
<SharePoint:ScriptLink language="javascript" name="core.js" OnDemand="true" runat="server"/>
<SharePoint:CustomJSUrl runat="server"/>
<SharePoint:SoapDiscoveryLink runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
<SharePoint:DelegateControl runat="server" ControlId="AdditionalPageHead" AllowMultipleControls="true"/>
<SharePoint:SPShortcutIcon runat="server" IconUrl="/_layouts/images/favicon.ico"/>
<SharePoint:SPHelpPageComponent Visible="false" runat="server"/>
</head>
<body onload="javascript:if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form runat="server" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
<asp:ScriptManager id="ScriptManager" runat="server" EnablePageMethods="false" EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true" />
<WebPartPages:SPWebPartManager id="m" runat="Server"/>
<SharePoint:FormDigest runat="server"/>

<asp:ContentPlaceHolder ID="SPNavigation" runat="server">
</asp:ContentPlaceHolder>

<div >


<asp:ContentPlaceHolder id="PlaceHolderHelpButton" runat="server">

</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="PlaceHolderWelcomeMenu" runat="server">

</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="PlaceHolderDeveloperDashboardLauncher" runat="server">

</asp:ContentPlaceHolder>
</div>



<asp:ContentPlaceHolder id="PlaceHolderSiteName" runat="server">
</asp:ContentPlaceHolder>



<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server" />


<asp:ContentPlaceHolder id="PlaceHolderPageSubTitle" runat="server" />



<div>
<asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" runat="server" />
</div>
<div id="maincontent">
<asp:ContentPlaceHolder id="PlaceHolderMain" runat="server" />
</div>
<div style="display:none;">
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderNavSpacer" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderBodyLeftBorder" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderPageImage" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderTitleLeftBorder" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderTitleAreaSeparator" runat="server" />
</div>
<div id="DeveloperDashboard">
<SharePoint:DeveloperDashboard runat="server"/>
</div>
</form>
</body>
</html>

Friday, February 12, 2010

First DashBoard in SharePoint 2010

hi,

Today I created first dashboard, since I invested time in gathering information, I thought lets blog all at one place.
1. Create site using BI template [this particualr point took whole lot of time to find]

2. Click Start using performace Point service, Run DashBoard designer.


Now you are required to create dashboard.
Dashboard is collection of score cards, KPIs and Reports. The PPS team is giving good start in form PDF file at technet. Few starting points which I like are
http://technet.microsoft.com/en-us/library/bb794633.aspx
http://blogs.adatis.co.uk/blogs/timkent/archive/tags/PerformancePoint+Monitoring/default.aspx
http://performancepointblog.com/

Enjoy!!

Monday, January 18, 2010

SharePoint 2010 (Beta) Training Kit

download it from http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=f1599288-a99f-410f-a219-f4375dbe310c

Monday, January 11, 2010

Completely Remove Left Navigation from v4. master Page

hi,

yesterday i was goign through the htmls of master page, the big difference I found is tables has been replaced by <Div>. The team gave OOB minimal v4.0 Master page also v3.0 master pages are present.

I was trying to remove left navigation completely, after investing some time below are the steps to do it -
look for div id="s4-leftpanel" class="s4-notdlg"
right click on it, select tag, remove that complete portion. you just removed the left navigation..every thing Quick launch,Recycle Bin. But to work the master page properly add the removed contentPlace Holders again, below are the contentPalce holder which should be added at minimum to work it proper -
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBarDataSource" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderCalendarNavigator" runat="server" />
<asp:ContentPlaceHolder id="PlaceHolderLeftActions" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBarTop" runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="PlaceHolderQuickLaunchTop" runat="server"></asp:ContentPlaceHolde>

now to use the complete space occuiped by left nagivation ->
Div with ContentID = MSO_ContentTable has a style class s4-ca which sets left margin to 115, make it to 0 and you are done.
it should look like -
div class="s4-ca s4-ca-dlgNoRibbon" id="MSO_ContentTable" style="margin-left:0px"

Done..use compelet space now!!

Friday, January 8, 2010

Silverlight ClientObject Model, uploading File to Document Library

Hi,
I want to share the new learning with all of you,I was trying to upload file to document library suing client object model. the client Object Model for Managed code gives option for 'SavebinaryDirect()' but no such thing for silverlight, then how to achieve the same goal using silverligt. hey below is the code -

private void uploadFileToDocumentLibrary(string fileName, byte[] fileContent)
{
ClientContext cnt = ClientContext.Current;

listForUpload = cnt.Web.Lists.GetByTitle("Redmond");

this.Dispatcher.BeginInvoke(delegate()
{
cnt.Load(listForUpload);
cnt.Load(listForUpload.RootFolder);
cnt.Load(listForUpload.RootFolder.Files);
cnt.ExecuteQueryAsync(succeedUploadFileListner, failureUploadFileListner);
});

}


private void succeedUploadFileListner(object sender, ClientRequestSucceededEventArgs e)
{

// byte[] dataArray;
Microsoft.SharePoint.Client.File file1 = listForUpload.RootFolder.Files[0];
this.Dispatcher.BeginInvoke(delegate()
{
byte[] dataArray = allFiles[lstFiles.Items[0].ToString()];
FileCreationInformation file = new Microsoft.SharePoint.Client.FileCreationInformation();

file.Content = dataArray;
file.Overwrite = true;
file.Url = lstFiles.Items[0].ToString();
listForUpload.RootFolder.Files.Add(file);
listForUpload.Update();
ClientContext.Current.ExecuteQueryAsync(s1, f1);


});


}

private void s1(object sender, ClientRequestSucceededEventArgs e)
{
this.Dispatcher.BeginInvoke(delegate()
{
MessageBox.Show("File Uploaded");
});
}
private void f1(object sender, ClientRequestFailedEventArgs e)
{
this.Dispatcher.BeginInvoke(delegate()
{
if (string.IsNullOrEmpty(e.Message))
{
MessageBox.Show(e.Exception.InnerException.Message);
}
else
{
MessageBox.Show(e.Message);
}
});
}
Key things are - First list should be loaded, then you can access .rootFolder and add files to it. this is the reason why I am writting actual file upload code in succeddLisnter of List load.

File.Url is file name and list.rootFolder gives the address like http:///.

In this snippet the error which bugged me most is 'Remote server returned error:Not found'. this error comes when the requested object is not reachabel, reasons could be typo error or invalid url or like in my case I was giving file.Url = "http://... full url where as it should be file Name like try.txt.

the second error I found at I was trying to add files before list lost, the moment I replaced to add file code to succeddLisnter it worked like charm. try this

Cheers :)

Friday, January 1, 2010

Client OM,Delete multiple items from Document Library Asynchrously[silverlight]

hi All,
Very happy new year to all of you. first day of 2010 gave me new information while working with client object model asynchrnously, which I want to share with all of you.

Below is the code to delete obect from list, using Client OM ->
private void btn_Delete(object sender, RoutedEventArgs e)
{

foreach (GridData data in dataSource)
{
if (data.IsChecked)
{

if (!(selectedItems.ContainsKey(data.DocID)))
{

selectedItems.Add(data.DocID, data.DocUrl);
}
}
}
if (selectedItems.Count > 0)
{
foreach (var grd in selectedItems)
{
deleteItem(grd.Key, grd.Value);
}

}

else
{
MessageBox.Show("Please select atleast one item");
}
}
private void deleteItem(string itemID, string itemUrl)
{

if (cnt == null)
{
throw new Exception("connection failed");
}
else
{

List olist = cnt.Web.Lists.GetByTitle(listName);
ListItem item = olist.GetItemById(itemID);
item.DeleteObject();
this.Dispatcher.BeginInvoke(delegate()
{
cnt.Load(olist, list => list.Title);

cnt.ExecuteQueryAsync(delete_succeedListner, delete_failureListner);
});
}
}
private void delete_succeedListner(object sender,ClientRequestSucceededEventArgs e)
{

this.Dispatcher.BeginInvoke(delegate()
{
MessageBox.Show("Item deleted");
});

}

this is perfactly fine to delete single item from list. Why I am saying so? just look at code once again, actually item is getting deleted at succeddListner, where nothing otherthan messageBox, which means it will always delete the last item from for loop (where I am caling deleteItem()), it will loose all the previous information and will not work as in synchrouse way. what to do for multiple delete in this case? ideally in succeedLisnter, when one item is deleted. deleteItem() should be invoked again to delete the second item, and so on.check the below code for multiple item delete -
private void btn_Delete(object sender, RoutedEventArgs e)
{

foreach (GridData data in dataSource)
{
if (data.IsChecked)
{

if (!(selectedItems.ContainsKey(data.DocID)))
{

selectedItems.Add(data.DocID, data.DocUrl);
}
}
}
if (selectedItems.Count > 0)
{
string tobeDeleted_key = string.Empty;
string tobeDeleted_value = string.Empty;


tobeDeleted_key = selectedItems.First().Key;
tobeDeleted_value = selectedItems.First().Value;
deleteItem(tobeDeleted_key, tobeDeleted_value);


}

else
{
MessageBox.Show("Please select atleast one item");
}


}
private void deleteItem(string itemID, string itemUrl)
{
cnt = new ClientContext(serverUrl);
if (cnt == null)
{
throw new Exception("connection failed");
}
else
{
MessageBox.Show(itemUrl + " From listName " + listName);
oList = cnt.Web.Lists.GetByTitle(listName);
ListItem item = oList.GetItemById(itemID);
item.DeleteObject();
oList.Update();
this.Dispatcher.BeginInvoke(delegate()
{
cnt.Load(oList, list => list.Title);
cnt.ExecuteQueryAsync(delete_succeedListner, delete_failureListner);
});
}
}
private void delete_succeedListner(object sender,ClientRequestSucceededEventArgs e)
{
string tobeDeleted_key = selectedItems.First().Key;
this.Dispatcher.BeginInvoke(delegate()
{
MessageBox.Show("Item deleted");
selectedItems.Remove(tobeDeleted_key);
if (selectedItems.Count > 0)
{
string tobeDeleted_value = string.Empty;
tobeDeleted_key = selectedItems.First().Key;
tobeDeleted_value = selectedItems.First().Value;
deleteItem(tobeDeleted_key, tobeDeleted_value);
}
else
{
fillDataGrid();
}
});

}

Cheers!!