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

Thursday, 17 October 2013

C# The Handle is Invalid


I have been given a task to debug a SharePoint event receiver as it wasn't doing what was meant to do, so I started by looking at event viewer logs. 

Event viewer error didn't helped much other then saying;

Error loading and running event receiver **Assembly Details**. Additional information is below.
: The handle is invalid

Searched google lot but couldn't find anything relevant in SharePoint context, but somehow figured out, this error "The handle is invalid" comes up when user doesn't have enough permissions to perform a task and in my case it was when event receiver tried to create a new event log or even when try to write a log to already created event log.

Fixed the issue by putting code within   SPSecurity.RunWithElevatedPrivileges(delegate(){  }); block, however couldn't figure out which exact permission was required to let user to write event logs but adding above fixed the issue for me, so all good.

Friday, 13 September 2013

Getting SPUser using Login Name


Today I came across a situation where I had to let user input user name(s) and add them to people picker field within a list, unfortunately it has to be done using web services as user is interacting with SharePoint throw iPad.

Problem ?

User can input anything (any string) so I need to validate if user name(s) exists or not,  if user with login name provided has access to site collection page and at end if all previous are true then get SPUser object and add it to people picker field of custom list.

Solution

Assuming you already got or know how to get reference to SPSite, SPWeb, SPList and SPListItem objects

SPUser user = null;

if (!string.IsNullOrEmpty(userLogin))
{
       try
      {
           // statement below will throw exception if user doesn't exists
           if (site.RootWeb.DoesUserHavePermissions(userLogin, SPBasePermissions.Open))
          {
                try
               {
                    user = site.RootWeb.SiteUsers[userLogin];
                }
               catch (Exception ex)
              {
                   string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't has permissions to root web", userLogin);
                   throw new SoapException(other, SoapException.ServerFaultCode, ex);
              }
           }
       }
       catch (Exception ex)
       {
            string other = string.Format("EXCEPTION! UserName '{0}' provided doesn't exists", userLogin);
            throw new SoapException(other, SoapException.ServerFaultCode, ex);
       }

       SPFieldUserValueCollection uvCollection = new SPFieldUserValueCollection();
       SPFieldUserValue uValue = new SPFieldUserValue(web, user.ID, user.LoginName);
       uvCollection.Add(uValue);

//Now update item just by item["People PIcker Field Name"] = uvCollection;
}

That's it, above code worked for me so it should work for you.

Lesson learned

I tried to use RootWeb.Users[userLogin] but it didn't worked for me as it does not return users who have access through a group whereas I had some user's given access to root web through groups only.

RootWeb.AllUsers[userLogin] is a dangerous function as  it returns list of all users who ever had access to web (even ones who don't have access to web anymore now).

web.EnsureUser() method creates a user if not exists already which I couldn't use in this scenario as client input is being used to validate SPUser object.

Monday, 9 September 2013

Stored Procedure to query data using list parameter

Working on this task required me to create a stored procedure which will get a list of strings, do some processing on them and then return some data. Since SQL Server 2000 don't support arrays object so I had to find a different approach. After a bit of googling i figured out I can send list by building a string out of it and then in SQL Server use function "IN" to do processing as required.

Here'e the Stored Procedure,

USE [DataBaseName]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[StoredProcedureName]
(
@listParameter varchar(8000)   -- this is because SQL Server don't support "Max" --
)
AS

exec('SELECT  *
FROM TableName
WHERE ColumnaName IN (' +@PasswordPolicyGroups+ ')   -- checks for list of values --
and CoumnaNameB= 1')

Now I am providing list as

List<String> myListData = GetListData(); // or your logic
string tempListData = string.Empty;

foreach(string data in myListData)
     data += "'" + myListData + "',";

// now just pass data as your parameter and call stored procedure