Hi everyone,
I am a little bit lazy here to write anything :) So just a quick briefing:
1) When you use CreateTaskWithContentType activity you should create your content type or use existing content type
2) Used content type should be derived from Workflow Task Content Type
3) Second point could be a problem since Workflow Task Content Type is hidden
Here is post about this problem: http://social.msdn.microsoft.com/Forums/sharepoint/en-US/93679b02-bfa9-43c2-94ad-ec45191cd478/createtask-method-how-to-create-a-task-based-on-a-custom-content-type
Hope that helped...
Monday, July 15, 2013
Infopath: Get related list item ID from Related Content field
Hi everyone,
There is a simple way how to get related list item ID from Related Content field. Inside Related Content field is stored URL to the related item (in the case of the task). The URL should similar like this: http://site/Lists/listName/DispForm.aspx?ID=33
Then you can use substring-after(WorkflowLink, "=") to get current list item ID
You can find the original thread here: http://social.msdn.microsoft.com/Forums/en-US/59d44915-abd9-484a-8687-926c94cc869b/display-current-item-column-from-list-workflow-in-task-notification-approval-infopath-form
How to use InvokeWebService activity
Hi everybody,
I needed to use InvokeWebService activity and as usual there were some obstacles on the way to do so :)
If you find this error message in the SharePoint log:
System.Net.WebException: The request failed with HTTP status 401: Unauthorized. at System.Workflow.Activities.InvokeWebServiceActivity.Execute(ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(T activity, ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(Activity activity, ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutorOperation.Run(IWorkflowCoreRuntime workflowCoreRuntime) at System.Workflow.Runtime.Scheduler.Run()
You may need to pass correct credential to your web service.This should be short briefing how to use this activity and pass those credentials to it.
1) Add InvokeWebService activity into your project from the Toolbox :)
2) The add URL to your web service (Choose required method)
3) After that you should see all parameters of the method in the Properties window of the activity
4) Set parameters as needed
If the web service doesn't require any type of permission I believe you can finish here. In my case I needed to pass credential to it.
5) Set Invoking property and add the following method there:
using ApprovalWorkflowProject.projects.server;
I needed to use InvokeWebService activity and as usual there were some obstacles on the way to do so :)
If you find this error message in the SharePoint log:
System.Net.WebException: The request failed with HTTP status 401: Unauthorized. at System.Workflow.Activities.InvokeWebServiceActivity.Execute(ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(T activity, ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(Activity activity, ActivityExecutionContext executionContext) at System.Workflow.ComponentModel.ActivityExecutorOperation.Run(IWorkflowCoreRuntime workflowCoreRuntime) at System.Workflow.Runtime.Scheduler.Run()
You may need to pass correct credential to your web service.This should be short briefing how to use this activity and pass those credentials to it.
1) Add InvokeWebService activity into your project from the Toolbox :)
2) The add URL to your web service (Choose required method)
3) After that you should see all parameters of the method in the Properties window of the activity
4) Set parameters as needed
If the web service doesn't require any type of permission I believe you can finish here. In my case I needed to pass credential to it.
5) Set Invoking property and add the following method there:
using ApprovalWorkflowProject.projects.server;
//Set correct
credentials
Private void Invokingwebservice (object
sender, InvokeWebServiceEventArgs e)
{
YourWebServiceWCF
svc = (YourWebServiceWCF)((InvokeWebServiceEventArgs)e).WebServiceProxy;
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
After you add a InvokeWebService activity the new web reference is created (for more information check this site http://msdn.microsoft.com/en-US/library/d9w023sx(v=vs.80).aspx or look through whole tutorial http://msdn.microsoft.com/en-us/library/t745kdsh(v=vs.80).aspx). You have to add this reference to your project(that's why that using statement) then you will find YourWebServiceWCF class inside the new namespace.
This should be all. If you want more information, here is also post about this topic http://social.msdn.microsoft.com/Forums/sharepoint/en-US/8c782989-649d-4dd9-9749-b919f6e4176b/pass-credentials-using-invokewebservice-activity
Hope that helped...
Approval workflow - This task is currently locked by a running workflow and cannot be edited.
Hello everybody,
I think that if you had developed some approval workflow you would receive an error in the title at least once. You can find a lot of information about the error: "This task is currently locked by a running workflow and cannot be edited.". Here are some links which were quite useful to me:
CreateParallelTaskWithContentType is an activity which creates all tasks and there is logic to do so, but I won't describe it here because it is not related to this topic.
OnTaskCreated activity just sends emails when a new task is assigned.
WhileActivity is a loop which holds task till it is approved.
OnParallelTaskChanged is an activity which controls the previous loop and break it after a task is updated.
CompleteTask is an activity which should complete the current task and in my case has no method.
CodeCompleteAllTask activity is an activity which should complete all tasks if one of the tasks is approved.
Code of the last activity I have written according to articles above and here it is:
I wouldn't recommend doing any type of actions except the approval logic in the replicator activity. Perhaps there is a bug in my code but in my case some activities inside replicator activity were fired more than once even they shouldn't be.
This should be all and I hope this helps somebody with this annoying error :)
Happy coding...
I think that if you had developed some approval workflow you would receive an error in the title at least once. You can find a lot of information about the error: "This task is currently locked by a running workflow and cannot be edited.". Here are some links which were quite useful to me:
The purpose of this post won't be to describe how to solve this error or find the cause of it since there are many posts about this topic already.
I would like to share the approach I have used to achieve my goals. So what my goals were...
1) Typical approval workflow with at least one approver.
2) All tasks should be approved if at least one approver approves the task.
So here is the snapshot of the workflow designer:
OnTaskCreated activity just sends emails when a new task is assigned.
WhileActivity is a loop which holds task till it is approved.
OnParallelTaskChanged is an activity which controls the previous loop and break it after a task is updated.
CompleteTask is an activity which should complete the current task and in my case has no method.
CodeCompleteAllTask activity is an activity which should complete all tasks if one of the tasks is approved.
Code of the last activity I have written according to articles above and here it is:
//Email body
string
emailBody = string.Empty;
//Email
receiver
SPFieldUserValue
recieverValue;
foreach
(SPWorkflowTask task in this.workflowProperties.Workflow.Tasks)
{
if
(task[SPBuiltInFieldId.TaskStatus].ToString()
!= SPResource.GetString(new CultureInfo((int)task.Web.Language, false),
"WorkflowTaskStatusComplete", new object[0]))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Send email notification about rejected task
recieverValue = (SPFieldUserValue)task.Fields[SPBuiltInFieldId.AssignedTo].GetFieldValue((String)task[SPBuiltInFieldId.AssignedTo]);
receiverCompleteAllAssociatedTasks = recieverValue.User;
emailBody += "some text <br />";
sendMail(receiverCompleteAllAssociatedTasks.Email, "Your reply is no longer needed.",
emailBody, true, true);
emailBody = string.Empty;
//Set task as completed
bool allowUnsafeUpdates =
task.Web.AllowUnsafeUpdates;
task.Web.AllowUnsafeUpdates =
true;
task["ApproveStatus"] = "Rejected";
Hashtable data = new
Hashtable();
data[SPBuiltInFieldId.Completed] = "TRUE";
data[SPBuiltInFieldId.PercentComplete] = 1;
data["FormData"] = "Completed";
data["TaskStatus"] = "Approved";
data["Reviewed"] = "Yes";
data["SendSignOffEmail"] = "Yes";
data[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new
CultureInfo((int)task.Web.Language,
false), "WorkflowTaskStatusComplete",
new object[0]);
bool succed = SPWorkflowTask.AlterTask((task
as SPListItem),
data, false);
if (!succed)
sendMail("", "Error
/ completeAllAssociatedTasks()-AlterTask", "Error
occured at EmployeeID: " + this.workflowProperties.Item["EmployeeID"], false,
false);
//No need to use task.Web.Update() or task.SystemUpdate(),
it is already involved in AlterTask method;
//Set AllowUnsafeUpdates to the original value
task.Web.AllowUnsafeUpdates = allowUnsafeUpdates;
});
}
}
receiverCompleteAllAssociatedTasks = null;
I wouldn't recommend doing any type of actions except the approval logic in the replicator activity. Perhaps there is a bug in my code but in my case some activities inside replicator activity were fired more than once even they shouldn't be.
This should be all and I hope this helps somebody with this annoying error :)
Happy coding...
Monday, July 1, 2013
Successful way to debug SP app using Visual studio 2012 with SharePoint 365
I am quite a new at SharePoint app developing, but recently I needed to deploy and debug App for SharePoint 2013. When I created a new project everything worked fine. I did have a problem though when I wanted to run a project which has been sent to me. I hit the run button then I received this error message: Workflow debugging prerequisites failed to complete. Would you like to disable workflow debugging in order to debug other parts of this project? Workflows will still be installed but will not have debugging support.
It is certain I don't want that, and when I rejected disabling debugging I received this warning and error:
Warning: Microsoft.VisualStudio.SharePoint.SharePointConfigurator.exe could not authenticate successfully to SharePoint to provision workflow debugging prerequisites.
Error: Error occurred in deployment step 'Install app for SharePoint': Deployment was cancelled.
As it turned out it wasn't any technical problem, but just my misunderstanding of handling SharePoint apps (which could be as I think also a problem for other people).
Where the problem is:
You can easily find out that SharePoint apps don't use WSP file but app file. I would expect that this app file is automatically created whenever the Start button is hit (This is the approach which worked fine with WSP files). But I was wrong and you have to create app file manually before you hit the start button. This isn't anything sophisticated, you just right click on your application in Solution Explorer and then click on Publish.. option.
This solved my problem just fine and if I am wrong about something, please let me know. As I said, I am really newbie at SharePont 365 development.
Thanks for reading ;)
It is certain I don't want that, and when I rejected disabling debugging I received this warning and error:
Warning: Microsoft.VisualStudio.SharePoint.SharePointConfigurator.exe could not authenticate successfully to SharePoint to provision workflow debugging prerequisites.
Error: Error occurred in deployment step 'Install app for SharePoint': Deployment was cancelled.
As it turned out it wasn't any technical problem, but just my misunderstanding of handling SharePoint apps (which could be as I think also a problem for other people).
Where the problem is:
You can easily find out that SharePoint apps don't use WSP file but app file. I would expect that this app file is automatically created whenever the Start button is hit (This is the approach which worked fine with WSP files). But I was wrong and you have to create app file manually before you hit the start button. This isn't anything sophisticated, you just right click on your application in Solution Explorer and then click on Publish.. option.
This solved my problem just fine and if I am wrong about something, please let me know. As I said, I am really newbie at SharePont 365 development.
Thanks for reading ;)
Wednesday, April 17, 2013
Unable to debug SharePoint 2010 project - Error 0x80040129
Hi everyone,
Today I had a problem with the debugging Sharepoint project. I have got this error: Unable to start debugging on the web server. An error occurred that usually indicates corrupt installation (code 0x80040129)
Some posts lead me to consider correct setting of the application pool, but unfortunately this wasn't my problem.
The reason why I have got this error is that I am running SharePoint 2010 on Windows server 2008 R2 and recently I have installed Visual Studio 2012 and Windows Service Pack 1. So I have both Visual Studios on my development server installed (2010 and 2012). After a while I have found this very useful post http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopmentprevious/thread/45b0ca9c-0454-475e-b9fb-c37e6527965c
Although this was about downgrading VS from 2012 to 2010, cause of the problem was similar, I guess. The solution for this (in my case of course) is to reinstall Service Pack 1 for Visual Studio 2010.
Then everything works like a charm again...
Hope this helps ;)
Today I had a problem with the debugging Sharepoint project. I have got this error: Unable to start debugging on the web server. An error occurred that usually indicates corrupt installation (code 0x80040129)
Some posts lead me to consider correct setting of the application pool, but unfortunately this wasn't my problem.
The reason why I have got this error is that I am running SharePoint 2010 on Windows server 2008 R2 and recently I have installed Visual Studio 2012 and Windows Service Pack 1. So I have both Visual Studios on my development server installed (2010 and 2012). After a while I have found this very useful post http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopmentprevious/thread/45b0ca9c-0454-475e-b9fb-c37e6527965c
Although this was about downgrading VS from 2012 to 2010, cause of the problem was similar, I guess. The solution for this (in my case of course) is to reinstall Service Pack 1 for Visual Studio 2010.
Then everything works like a charm again...
Hope this helps ;)
Wednesday, April 10, 2013
SqlException (0x80131904): Invalid object name 'AllWebs'
Hi everyone,
recently I have installed service pack 1 and Visual Studio 2012 on my development environment (Windows Server 2008 R2). I have SharePoint 2010 installed and everything looked fine after this upgrade. The problem appeared when I was trying to deactivate sandbox solution. Whenever I was trying to do so, I got this error message:
[SqlException (0x80131904): Invalid object name 'AllWebs'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +212
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +245
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1099
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +112
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6291924
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6292993
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +424
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +211
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +87
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior, SqlQueryData monitoringData, Boolean retryForDeadLock) +716
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, Boolean retryForDeadLock) +116
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command) +55
Microsoft.SharePoint.SPFeatureEnumeratorBase.GetNextRowset(GetFeaturesState state, SPContentDatabase contentDB, SPSite site) +980
Microsoft.SharePoint.SPSiteFeatureEnumerator.System.Collections.IEnumerator.Reset() +43
Microsoft.SharePoint.SPSiteFeatureEnumerator..ctor(GetFeaturesState state, SPSite site) +64
Microsoft.SharePoint.SPUserSolutionCollection.RemoveFeatureInstancesAndDefinition(SPFeatureDefinition featdef) +522
Microsoft.SharePoint.SPUserSolutionCollection.Remove(SPUserSolution solution) +279
Microsoft.SharePoint.WebControls.SolutionItemButton.DeactivateItem() +478
Microsoft.SharePoint.WebControls.SPLinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +75
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
recently I have installed service pack 1 and Visual Studio 2012 on my development environment (Windows Server 2008 R2). I have SharePoint 2010 installed and everything looked fine after this upgrade. The problem appeared when I was trying to deactivate sandbox solution. Whenever I was trying to do so, I got this error message:
[SqlException (0x80131904): Invalid object name 'AllWebs'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +212
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +245
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1099
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +112
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6291924
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6292993
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +424
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +211
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +87
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior, SqlQueryData monitoringData, Boolean retryForDeadLock) +716
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, Boolean retryForDeadLock) +116
Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command) +55
Microsoft.SharePoint.SPFeatureEnumeratorBase.GetNextRowset(GetFeaturesState state, SPContentDatabase contentDB, SPSite site) +980
Microsoft.SharePoint.SPSiteFeatureEnumerator.System.Collections.IEnumerator.Reset() +43
Microsoft.SharePoint.SPSiteFeatureEnumerator..ctor(GetFeaturesState state, SPSite site) +64
Microsoft.SharePoint.SPUserSolutionCollection.RemoveFeatureInstancesAndDefinition(SPFeatureDefinition featdef) +522
Microsoft.SharePoint.SPUserSolutionCollection.Remove(SPUserSolution solution) +279
Microsoft.SharePoint.WebControls.SolutionItemButton.DeactivateItem() +478
Microsoft.SharePoint.WebControls.SPLinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +75
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
I wasn't able to find any similar post on the Internet so I have decided to post my solution ( or at least the way which worked for me)
At first I thought it is somehow related to my recent installation. But when I opened SharePoint 2010 Central Administration, the Sharepoint Health Analyzer was reporting some critical issues. As it turned out, my database was obsolete and it needed to update. I ran SharePoint 2010 Product Configuration Wizard and that solved the problem.
Ok then, that should be all. Hope that will help somebody ;)
Best,
David
Monday, March 18, 2013
Efficient way to add a new item to a SharePoint list
I was just browsing on the Internet and then I found this really interesting post wrote by Rob Garrett:
http://blog.robgarrett.com/2009/02/25/efficient-way-to-add-a-new-item-to-a-sharepoint-list/
Interesting part about is that SPList.Items.Add method gets all items in the list before adding a new SPListItem. So you can use SPQuery class to do this. I am sure gonna test this :)
http://blog.robgarrett.com/2009/02/25/efficient-way-to-add-a-new-item-to-a-sharepoint-list/
Interesting part about is that SPList.Items.Add method gets all items in the list before adding a new SPListItem. So you can use SPQuery class to do this. I am sure gonna test this :)
Programmatically get SmtpClient of SharePoint web application
It is necessary to set up SmtpClient.Host property if you want to send e-mail using System.Net.Mail namespace. This can be easily done using OutboundMailServiceInstance property like this:
string smtpURL = SPContext.Current.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
Best ways to log errors in SharePoint
Hi everyone,
I did some digging about SharePoint error logging, because when you create some project you usually need to solve exception handling problems. I know there are some ways to log those errors (or whatever needs to be logged), but which one is the best or most suitable?
Here is short briefing of things I found and this ought to be good start point for this problem:
This article describes various types of logging and their purposes:
http://spmatt.wordpress.com/2012/02/06/error-logging-in-sharepoint/
If you want to find fast way to log into ULS, this is the solution:
http://zimmergren.net/technical/sp-2010-developing-for-performance-part-4-logging
Previous log technique has some problems with logging into "Product" column of ULS log, so here is workaround for that problem:
http://blog.mastykarz.nl/logging-uls-sharepoint-2010/
If I would summarize some of logging techniques I would say this(more is in the first arcticle ;)):
ULS Logging
Nice way to go, but not for sand-box solutions. So with new SharePoint 365 comes some difficulties. Some of them can be solved by Full-trust Proxy.
E-mail Logging
This is was reason why I did all this digging in the first place. You should be prepared for additional problems, if you choose go down this path. By additional I mean organizing, sharing and unreliable reporting problems. This just shouldn't be your only way to log something (trust me I know what I am talking about :-D )
List Logging
This sounds like a nice and smooth way to log something. I can imagine many projects where this is appropriate solution. And it is also SharePoint 365 friendly :). There is just one thing I am not sure of and feel free to change my mind, but what happens if something goes wrong with SPContentDB? I would say that whole situation would be present like nothing happened at all. Anyway here is nice example how to do this http://www.sharepointblogs.be/blogs/timmy/archive/2011/12/26/sharepoint-365-logging.aspx
Other techniques can be seen in the first article...
At the and I would consider to have at least two ways error logging. That sounds like appropriate way to handle errors to me.
Anyway I hope you realized that this is just starting point for error logging and it will be useful to you ;)
Happy codding...
I did some digging about SharePoint error logging, because when you create some project you usually need to solve exception handling problems. I know there are some ways to log those errors (or whatever needs to be logged), but which one is the best or most suitable?
Here is short briefing of things I found and this ought to be good start point for this problem:
This article describes various types of logging and their purposes:
http://spmatt.wordpress.com/2012/02/06/error-logging-in-sharepoint/
If you want to find fast way to log into ULS, this is the solution:
http://zimmergren.net/technical/sp-2010-developing-for-performance-part-4-logging
Previous log technique has some problems with logging into "Product" column of ULS log, so here is workaround for that problem:
http://blog.mastykarz.nl/logging-uls-sharepoint-2010/
If I would summarize some of logging techniques I would say this(more is in the first arcticle ;)):
ULS Logging
Nice way to go, but not for sand-box solutions. So with new SharePoint 365 comes some difficulties. Some of them can be solved by Full-trust Proxy.
E-mail Logging
This is was reason why I did all this digging in the first place. You should be prepared for additional problems, if you choose go down this path. By additional I mean organizing, sharing and unreliable reporting problems. This just shouldn't be your only way to log something (trust me I know what I am talking about :-D )
List Logging
This sounds like a nice and smooth way to log something. I can imagine many projects where this is appropriate solution. And it is also SharePoint 365 friendly :). There is just one thing I am not sure of and feel free to change my mind, but what happens if something goes wrong with SPContentDB? I would say that whole situation would be present like nothing happened at all. Anyway here is nice example how to do this http://www.sharepointblogs.be/blogs/timmy/archive/2011/12/26/sharepoint-365-logging.aspx
Other techniques can be seen in the first article...
At the and I would consider to have at least two ways error logging. That sounds like appropriate way to handle errors to me.
Anyway I hope you realized that this is just starting point for error logging and it will be useful to you ;)
Happy codding...
Monday, February 18, 2013
How to programmatically create cross-site lookup field
Hi,
when you use SharePoint 2010 you may need to create cross-site lookup field. That is problem because SP 2010 doesn't natively support this kind of field. But as always there is some work around :) Even though the work around doesn't involve GUI, it isn't difficult at all.
Here is sample of code how you can easily create cross-site lookup field:
Ok that's it... not too bad right? Once you create your custom cross-site lookup field you can open column properties in list properties and there you should be able to change some its properties...
After you you add cross-site field I would recommend you to open column properties although you don't need to change anything. It happened to me that newly added column doesn't work properly and re-saving those column properties solved problem.
Happy codding....
when you use SharePoint 2010 you may need to create cross-site lookup field. That is problem because SP 2010 doesn't natively support this kind of field. But as always there is some work around :) Even though the work around doesn't involve GUI, it isn't difficult at all.
Here is sample of code how you can easily create cross-site lookup field:
//Add new column to list and ensure
cross side lookup
try
{
//Web contains list where a new column is required
SPSite currentSite = new
SPSite("https://server/siteContainsListWithRequiredNewColumn");
SPWeb currentWeb = currentSite.OpenWeb();
SPList currentlist = currentWeb.Lists["Some List"];
//Web that holds data for lookup field
SPSite lookupSite = new
SPSite("https://server/lookupSite");
SPWeb lookupWeb = lookupSite.OpenWeb();
SPList lookupList = lookupWeb.Lists["Lookup list"];
string fieldXML = "<Field
DisplayName='Name of new column' Type='Lookup' Required='TRUE' List='"
+ lookupList.ID + "' WebId='" +
lookupWeb.ID + "' Name='LookupField'
ShowField='" + "Viewed field"
+ "' />";
//Add new column to the list
currentlist.Fields.AddFieldAsXml(fieldXML,
true, SPAddFieldOptions.AddFieldToDefaultView);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
After you you add cross-site field I would recommend you to open column properties although you don't need to change anything. It happened to me that newly added column doesn't work properly and re-saving those column properties solved problem.
Happy codding....
Friday, February 15, 2013
Start with developing applications to work with Active Directory using C# code
Hi developers,
It has been while since I post last article. Actually I was planning to post this a little bit earlier, but... you know those excuses :-D
So what this is all about. I had to create project which has to operate with Active Directory and that was quite a new stuff for me. I though it won't be difficult and as usual I was wrong :-D Well, to be clear it isn't as difficult as it is confusing :) So this article isn't for describing some hard codding stuffs, but it should be good starter for anyone who has no experience in this and wants to find a quick and straight way to start developing. (Let's face it, most of the demands involve just simple operation in the active directory) So enough jibber-jabber...
For the start you should know there are two libraries to work with AD. System.DirectoryServices and System.DirectoryServices.AccountManagement, In my opinion DirectoryServices is the most powerful, but difficult to use. AccountManagement is quite easier but it won't let you to do "everything" you want to. Here is large article about them and it contains a lot of information and examples: http://ianatkinson.net/computing/adcsharp.htm#examples2 and there is even more on the Internet ;-). But I will stick just with the introduction these classes to make this post simple as much as it is possible.
Now you may wondering what this post is about. Well I am gonna show you sample code of both libraries, then describe how to extend AccountManagement to let you do more cool stuffs and at the end I will show you some workarounds I had to use when I was codding project.
System.DirectoryServices
For start do not forget use this using System.DirectoryServices; using statement.
And here is the code
If you would need to change some user's attribute you can use this code:
Nothing difficult right? But what if I want to have access to other properties except DisplayName, VoiceTelephoneNumber etc. You can have your own properties in AD which need to be accessed. You will have to use extend UserPrincipal class.Then you will have access to the other attributes (actually you will have access to the attributes you defined in your extended class :) ) I won't show this approach here because you can find great example on the msdn: http://msdn.microsoft.com/en-us/library/bb384372(v=vs.90).aspx
It has been while since I post last article. Actually I was planning to post this a little bit earlier, but... you know those excuses :-D
So what this is all about. I had to create project which has to operate with Active Directory and that was quite a new stuff for me. I though it won't be difficult and as usual I was wrong :-D Well, to be clear it isn't as difficult as it is confusing :) So this article isn't for describing some hard codding stuffs, but it should be good starter for anyone who has no experience in this and wants to find a quick and straight way to start developing. (Let's face it, most of the demands involve just simple operation in the active directory) So enough jibber-jabber...
For the start you should know there are two libraries to work with AD. System.DirectoryServices and System.DirectoryServices.AccountManagement, In my opinion DirectoryServices is the most powerful, but difficult to use. AccountManagement is quite easier but it won't let you to do "everything" you want to. Here is large article about them and it contains a lot of information and examples: http://ianatkinson.net/computing/adcsharp.htm#examples2 and there is even more on the Internet ;-). But I will stick just with the introduction these classes to make this post simple as much as it is possible.
Now you may wondering what this post is about. Well I am gonna show you sample code of both libraries, then describe how to extend AccountManagement to let you do more cool stuffs and at the end I will show you some workarounds I had to use when I was codding project.
System.DirectoryServices
For start do not forget use this using System.DirectoryServices; using statement.
And here is the code
//User's sAMAccountName
string user = "User's
sAMAccountName";
try
{
//Connect to the AD
DirectoryEntry de = new DirectoryEntry("LDAP://serverIP_or_adress", @"userName", "password");
//Create a new instance of DirectorySearcher
class to find required user
DirectorySearcher deSearch = new DirectorySearcher();
//Set the start of searching
deSearch.SearchRoot = de;
//Set filter
deSearch.Filter = "(&(objectClass=user)
(sAMAccountName=" + user + "))";
//Save result to the instance of SearchResult
class
SearchResult result =
deSearch.FindOne();
//Check the result
if (result != null)
{
//Save new to the instnce of DirectoryEntry so
you can operate with user.
DirectoryEntry foundedUser = new DirectoryEntry(result.Path);
//Create
a writer and open the file
TextWriter tw = new StreamWriter("ADUserDefaultProperties.txt");
//Loop through all users properties
foreach (var
property in result.Properties.PropertyNames)
{
try
{
if (result.Properties[property.ToString()] != null &&
result.Properties[property.ToString()].Count > 0)
{
tw.WriteLine(property.ToString() + ":
" + foundedUser.Properties[property.ToString()].Value.ToString());
}
else
{
tw.WriteLine(property.ToString() + ":
" + "Couldn't reach the
property!");
}
}
catch (NullReferenceException
nullEx)
{
tw.WriteLine(property.ToString() + ":
" + "Exception / Couldn't reach
the property!");
}
}
// close the stream
tw.Close();
}
}
foundedUser.Rename("cn="
+ name + " "
+ surname);
foundedUser.CommitChanges();
There is more you can do with System.DirectoryServices, but it is not theme of this post...
System.DirectoryServices.AccountManagement
Again do not forget to add: using System.DirectoryServices.AccountManagement;
This code is actually from site I mentioned above:
// enter AD settings
PrincipalContext AD = new
PrincipalContext(ContextType.Domain,
"leeds-art.ac.uk");
// create search user and add
criteria
Console.Write("Enter
logon name: ");
UserPrincipal u = new
UserPrincipal(AD);
u.SamAccountName = Console.ReadLine();
// search for user
PrincipalSearcher search = new
PrincipalSearcher(u);
UserPrincipal result = (UserPrincipal)search.FindOne();
//Do not forget to dispose search
object
search.Dispose();
// show some details
Console.WriteLine("Display
Name : " + result.DisplayName);
Console.WriteLine("Phone
Number : " + result.VoiceTelephoneNumber);
I just would like to point out another great extended class you can find there. It is extending AvanceFilters class. If you will extend this class you can define your own criteria for searching in AD. Isn't that great? And it simple like this:
public class UserPrincipalsExSearchFilter : AdvancedFilters
{
public UserPrincipalsExSearchFilter(Principal p) : base(p)
{ }
public void
EmployeeID(int value, MatchType
mt)
{
this.AdvancedFilterSet("employeeID",
value.ToString(), typeof(string), mt);
}
}
Ok that's all for introduction. I know I haven't mentioned how to create user, delete user etc., but those things you can easily "google it". Once you know where to start and that there are two main classes to work with AD(and if you can distinguish their purposes) the rest of the work should be a peace of cake. At least for the start...
At the end I would like to mention two "problems" I had.
1. Once I wasn't able to update property in AD using System.DirectoryServices.AccountManagement. You can always combine both classes if you want to. So if you already have UserPrincipal of some user, you don't need to search him again using DirectoryServices. You can do it like this:
DirectoryEntry de = (DirectoryEntry)userPrincipalOfNewUser.GetUnderlyingObject();
de.Rename("cn=" + userPrincipalOfNewUser.Surname +
" " +
userPrincipalOfNewUser.GivenName);
de.CommitChanges();
This can be quite helpful I guess...
2. I was using those classes in WCF service and I could't connect to the AD server or do any changes. My problem was with impersonation. So simple wrap your code like this:
using (HostingEnvironment.Impersonate())
{
//Put your code here
}
It helped me ;)
Ok that's all...I hope this will help you to start with DirectoryServices and AccountManagement classes.
Happy codding..
Subscribe to:
Posts (Atom)