Working with sharepoint large lists

October 7, 2009

Please visit this : Samsung Service Galaxy S

In a recent project, I had to get some information from the last sharepoint listitems inserted. I used foreach. Of course it is a bad idea. When the list grew (thousand of listitems)…the program worked as fast as a drunken turtle. Ok… As I was saying the data I needed was from the last x items inserted. So I replaced the foreach with a simple for:
count=10; (the last 10 items inserted)
for (int i = oList.Items.Count – count; i < oList.Items.Count; i++)

I ran the program and saw that the improvement was not what I expected, so I made a testProject to measure the execution time, for the foreach block code and the code above (with the simple for);

DateTime startTime = DateTime.Now;

chunk of code (for or foreach iteration)

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime – startTime;

For large lists the foreach statement took forever. The for statement took from 5 to 30 seconds for 4000 list items.
The odd part was that in the for statement as I said before, i iterated through the last 10 items.
So for 10 items I waited some good seconds.
I googled for the truth and I found this interesting article.

So I found out the SPQuery is one of the best ways to work with large lists.

SPQuery query = new SPQuery(oList.Views[0]);
Comm
query.RowLimit = 10;
SPListItemCollection filteredList = oList.GetItems(query);
foreach (SPListItem item in filteredList)
{
Blabla;
}

I ordered the list Descending by their ID so i got the most recent 10 list items.
I measured the execution time. At the first run it took 800 milliseconds for 4000 list items. The next executions took only from 15 to 30 milliseconds.
I would say…it is at least a good improvement;
An easier way to create CAML queries is with U2U CAML Query Builder
I tried to use CAML query to get the max ID directly but I didn`t succeed. If someone reads this…:P and knows how please leave a reply.

Commerce Server 2009
Thank you,
Ing. Msc. Dan Gheorghe

Kill “Not responding” programs in windows with a shortcut.

May 13, 2009

Please visit this : Samsung Service Galaxy S

As i was stumbling around, i found this article .
You can kill frozen application just with a double click on a shortcut on your desktop.
You must create a new shortcut and in the location bar write : taskkill.exe /f /fi “status eq not responding” .

Commerce Server 2009

How to make index_changed event work for asp.net Gridview

April 2, 2009

Please visit this : Samsung Service Galaxy S

I have tried to work with indexchanged event of the asp.net gridview. It didn`t even enter the function. After some searching i found solution.
You must add a column to the gridview typeof linkbutton.
In the Command atribute type “Select”

addlinkbutton1

In the RowDataBound event attach the function GridView1_RowDataBound:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

// Get reference to button field in the gridview.
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, “Select$” + e.Row.RowIndex);
e.Row.Style["cursor"] = “hand”;
e.Row.Attributes["onclick"] = _jsSingle;

}
}
}

Now you must override the Render function:

protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
ClientScript.RegisterForEventValidation(((LinkButton)row.Cells[0].Controls[0]).UniqueID, “Select$” + row.RowIndex);
}
}

base.Render(writer);
}
After this you can attach the indexChanged function to the gridview indexchanged event and get your row selected index when you click the row.

Ing. Msc. Dan Gheorghe

Commerce Server 2009

Add RoleAssignment to listitem.

March 26, 2009

Please visit this : Samsung Service Galaxy S

This is continuing the previous post. After you create the list item impersonating the current logged in user in the sharepoint site you might want to give that user only the right to read it.
After oListItem.Update(); you must run the code to do this with elevated Privileges to assign the role.
SPUser user = oWebsiteRoot.SiteUsers.GetByID(web.CurrentUser.ID);
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(SPControl.GetContextSite(this.Context).ID);
SPWeb w = site.OpenWeb();
Guid g = oListItem.UniqueId;
oListItem = w.Lists["Announcements"].GetItemByUniqueId(g);

oListItem is the listitem created in the previous post

I tried to set the RoleInheritence of the list item to false: oListItem.BreakRoleInheritance(false);
but i had some problems with it. I got the error:
“Updates are currently disallowed on GET requests.”

oListItem.BreakRoleInheritance(false) sets the spweb.AllowUnsafeUpdates to false; so after this you must set it true manually again even though we did that in the code before this (in the previous post) :

oListItem.BreakRoleInheritance(false);
w.AllowUnsafeUpdates = true;
w.Update();
Now to set the roles:

SPRoleDefinitionCollection webroledefinitions = w.RoleDefinitions;

SPRoleAssignment roleassignment = new SPRoleAssignment(user);

roleassignment.RoleDefinitionBindings.Add(webroledefinitions["Read"]);
oListItem.RoleAssignments.Add(roleassignment);
oListItem.Update();

});

And now every user sees the the items created by themselves.

Commerce Server 2009
By Ing. Msc. Dan Gheorghe

Sharepoint Impersonation.

March 25, 2009

Please visit this : Samsung Service Galaxy S

When you create a web form or web part for wss or sharepoint and work with list items for example you should impersonate the current logged user in your application to see who modified, added the list item. I chose this example to be the simplest.
So I created a web part for my sharepoint site.

I added this to the default project created when you choose Sharepoint Web Part project:
c# code:
private string customMessage = “Hello, world!”;
[WebBrowsable(true),
WebDescription("Displays a custom message"),
WebDisplayName("Display Message"),
Personalizable(PersonalizationScope.User)]
public string DisplayMessage
{
get { return customMessage; }
set { customMessage = value; }

}
In the render function i added my code. To make a similarity to asp.net you can think of it as page_load handler. Whenever you refresh the page that has the web part on it it executes your code.
Here i get the current logged in user i display it on the screen and then i create a new item in the Announcements List as added by the user logged in:

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
try
{
HttpContext ctx = HttpContext.Current;
SPWeb web = SPControl.GetContextWeb(this.Context);

if ( (ctx.User != null) && (ctx.User.Identity != null))
customMessage=ctx.User.Identity.Name;
writer.Write(DisplayMessage);

And we show this way the current logged in user.
Now we impersonate the user and create a new item in the Announcements list in his name. Every logged in user has a token (it identifies the authentication process applied to the user).
SPSite impersonatedSiteCollection = new SPSite( SPControl.GetContextSite(this.Context).ID, token);
SPWeb oWebsiteRoot = impersonatedSiteCollection.OpenWeb();
oWebsiteRoot.AllowUnsafeUpdates = true;
SPList oList = oWebsiteRoot.Lists["Announcements"];

SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = “My Item”;
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem.Update();
}
catch (System.ArgumentException e)
{
customMessage = e.Message ;
writer.Write(DisplayMessage);
}

I put it in a try catch sequence because the current logged in user might not have the rights to add a new item to that list and if so the page that contains the webpart will crash and he would not see it even though he has rights to. With the try catch the webpart will tell him that he has no rights.

Commerce Server 2009
By Ing. Msc. Dan Gheorghe

DataGrid column width.

March 10, 2009

Please visit this : Samsung Service Galaxy S

I recently found out that the datagrid component doesn`t have the column property. The smartdevice project doesn`t have DataGridView in the toolbox, so you would have to work with the DataGrid componnent.

[All code below is in C#]
At first you must create a DataGridTableStyle :

DataGridTableStyle ts = new DataGridTableStyle();

ts.MappingName = “”;

ts.GridColumnStyles.Clear();
If you have a DataTable to use as a datasource for the grid :

DataTable t = getProduse();

Now if you have to create DataGridColumnStyles for each column in the datatable:

for (int i = 0; i < t.Columns.Count; i++)

{

DataGridColumnStyle Col = new DataGridTextBoxColumn();

Col.MappingName = t.Columns[i].ColumnName;

Col.HeaderText = t.Columns[i].ColumnName;

Col.Width = 400;

ts.GridColumnStyles.Add(Col);

}

After this you add the DataGridTableStyle to the DataGrid:
dataGrid1.TableStyles.Add(ts);
Now when you select the DataSource the grid will have the Style you want:
dataGrid1.DataSource = t;

Commerce Server 2009
By Ing. Msc. Dan Gheorghe

Visual Studio 2008 Smart Device project connect to sql server.

March 10, 2009

Please visit this : Samsung Service Galaxy S

A friend of mine ran into some trouble with a smart device project these days. At first with internet connectivity on the pocket pc emulation. After some heavy swearing and a lot of tries he managed to connect to the network and then to
the sql server. There are 2 steps here:

1.Connect to the network

2.Connect to the server

1.To connect to the local network through the pocket pc emulator you must install virtual pc and Windows Mobile Device Center.

Virtual PC

Windows Mobile Device Center.

Run the Windows Mobile Device Center and use the following settings:

Windows  Mobile Center Settings

Windows Mobile Center Settings

Let it run in the background.

After you create the smart device project in visual studio you must enter Tools\Device Emulator Manager, choose the type of emulator you are using right click connect and right click cradle.

cradle

cradle

In the emulator you must go to file\Configure to the Network Tab and enable the first checkbox.

pocketpc emulator network settings

pocketpc emulator network settings

Check in the windows mobile center program if it says connected in the lower left corner. If it didn’t connect reset the settings connect mode to Bluetooth or something else, click ok, and then reset tot DMA again.

2. The sql connection string mustn’t have the name of the server. You must use the ip and the port of the machine from the network where you have sql installed, for example: “Data Source=192.168.0.30,1433;”.

string ConnectionString = “Data Source=192.168.0.30,1433;Initial Catalog=Companies;User ID=admin2;Password=test”;

1433 is the default port that sql server uses.

If you try now it still won’t work.

You must enter in sql server configuration manager\sql server network configuration\protocols and enable TCP/IP, then go to sql server native client configuration\client protocols and enable TCP/IP here also.

Double click on the TCP\IP from network Configuration\protocols, enter the IP ADDRESSES tab and delete from top to bottom TCP Dynamic Ports (let it blank) and enter TCP port 1433 :

Sql Configuration Manager TCP\IP

Sql Configuration Manager TCP\IP

After this you the application should connect to the sql server.

Commerce Server 2009
By Ing. Msc. Dan Gheorghe

with the help of Catalin Manole


Follow

Get every new post delivered to your Inbox.