Thursday, November 24, 2011

Get DateOnly from Caculate a Date in Ninetex workflows

Tuesday, October 11, 2011

How to start Nintex Workflow programtically

 Problem Statement: I have a SPList with Ninetex WF attached to it. The WF triggers for every item creation/updating on the list. But here I am creating/updating list items through SharePoint object model. While doing so, list items are getting updated but Ninetex WF is not triggered.
Reason: In SharePoint 2007, we cannot start the Ninetex WF using “system account” credentials (i.e. Drawback of Ninetex tool).
Below code will help you to run the Nintex workflow even with "System account" credentials also.
SPSecurity.RunWithElevatedPrivileges(delegate())
{
using (SPWeb currentweb = new SPSite(siteUrl).OpenWeb())
{
 currentweb.AllowUnsafeUpdates = true;
 SPList spList = currentweb.Lists["Custom List Name"];
 SPListItem spListItem = spList.Items.Add();
 private SPWorkflowManager wfManager;
 private SPWorkflowAssociationCollection spWorkFlows;
 // To replace the WF name globally
 string WorkflowName =ConfigurationManager.AppSettings["WorkflowName"].ToString();
 wfManager = spList.ParentWeb.Site.WorkflowManager;
 spWorkFlows = spList.WorkflowAssociations;
 foreach (SPWorkflowAssociation sendingWF in spWorkFlows)
 {
  if (sendingWF.Name == WorkflowName.Trim())
  {
    spListItem.Update();
    //To start Ninetex WF after updating Items in list
    wfManager.StartWorkflow(spListItem,sendingWF,
                            sendingWF.AssociationData, true);
    break;
  }
 }
});
Note: SPSecurity.RunWithElevatedPrivileges, it runs with the “System Account” credentials.

Monday, September 26, 2011

Code Block are not allowed in this file

Most of them got this exception if you are working on developing site pages with inline code in SharePoint. you can get the answer if you searched in search engine with in less time. But we cannot get all the answers in one place that is what I am doing here merging all the solutions at one place for quick reference.
Error: I have created site pages through SharePoint designer and added inline code inside of “Script” tag and after that if I tried to view this page I got this error “An error occurred during the processing of /Pages/Sample.aspx. Code blocks are not allowed in this file”.
Affected files: i.e. Master pages and Page layouts.

< PageParserPath>
 //To allow script code to the specific page
 < PageParserPath VirtualPath=”/Pages/Sample.aspx” CompilationMode=”Always” AllowServerSideScript=”true” />

//To allow script code to all the pages
 < PageParserPath VirtualPath=”/Pages/*” CompilationMode=”Always” AllowServerSideScript=”true” />

//To allow script code to the Master page
 < PageParserPath VirtualPath=”/_catalogs/masterpage/Sample.master” CompilationMode=”Always” AllowServerSideScript=”true” />

//To enable code blocks on folder
 < PageParserPath VirtualPath=”/TeamSite/CustomForms/” CompilationMode=”Always” AllowServerSideScript=”true” IncludeSubFolders="true"/>
< /PageParserPath>

AllowServerSideScript, IncludeSubFolders” are self-explanatory and “CompilationMode” attribute have the following options:
·         Always – The default value, which compiles the page always
·         Auto – Page will not be compiled if possible
·         Never – The page will not be dynamically compiled 
Thanks for reading My post.

Thursday, July 21, 2011

How to validate the users in sharepoint's peoplepicker controls

Here are the steps to include SharePoint people picker control.
Step1: Add the below people picker control in your sharepoint page(.aspx)

Step2: Add the below code to validate the users and stores the user information into SharePoint list.
string PeoplePickerValue=peoplepcikerID.CommaSeparatedAccounts;
if (!string.IsNullOrEmpty(PeoplePickerValue))
   {
       SPUser User1 = null;
       User1 = spDLRWeb.AllUsers[PeoplePickerValue];
       if (User1!= null)
          {
              //To add People Picker to the list items.
              // ”Title” is Single Line of text field.
             spListItem["Title"] = User1.Name; 
             //”Manager” is People Picker Field.
             spListItem["Manager"] = User1;
           }
    }
else{ return; }
In the above code, "CommaSeparatedAccounts" will return the valid users information only otherwise it will return null value.
Note: Now,PeoplePicker validations are implemented on server side. i will update how to validate the users in people control at client side soon..

Monday, June 27, 2011

Identifying Worker Process (w3wp.exe) – IIS 6.0 and IIS 7.0 for Debugging ASP.NET Application

If you are debugging a ASP.NET web application which is hosted on IIS, you need to attach the particular worker process in Visual Studio to start debugging. To Attach a process we can go to Tools > Attach Process or use shortcut key Ctrl +P. The process window will show the worker process (w3wp.exe) which is currently running on IIS. You need to select the process and click on attach button to start the debugging.
Problem starts when you have multiple worker process running on IIS.  If you have multiple sites hosted on IIS and each site having their own application pool then you will see the list of all worker process in the Process Attach window. 

Here  you need to identify the particular worker process which is associated with your application pool. Note: Whenever we create a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS (Kernel Level of IIS) . So whenever HTTP.SYS Received the request from any web application,  it checks for the Application Pool and based on the application pool it send the request 

C:\Windows\System32\inetsrv>appcmd list wp

Sunday, April 10, 2011

Tips and Tricks on using URL in SharePoint2010:

  • Customize DispForm.aspx/EditForm.aspx
o   Replace everything in the URL after “?ID=#“ with “&PageView=Shared&ToolPaneView=2”
  • Jump to web part page maintenance
o   ?contents=1
  • Remove all items in recycle bin
o   javascript:emptyItems();
  • Webpart Gallery
    • _Catalog/WP
  • Web Part Page Maintenance
    • ?contents=1(Add at the end of URL)
  • View All Site Content
    • /_layouts/viewlsts.aspx
  • Site Template Gallery
    • /_catalogs/wt
  • Site Settings
    • /_layouts/settings.aspx
  • Site Content Types
    • /_layouts/mngctype.aspx
  • Site Column Gallery
    • /_layouts/mngfield.aspx
  • Recycle Bin
    • /_layouts/AdminRecycleBin.aspx
  • Master Page Gallery
    • /_catalogs/masterpage(Also includes page layouts)
  • Manage User Permissions
    • /_layouts/user.aspx
  • Manage People
    • /_layouts/people.aspx
  • Manage Site Collection Administrators
    • /_layouts/mngsiteadmin.aspx
  • List Template Gallery
    • /_catalogs/lt
  • Create New Site Content
    • /_layouts/create.aspx
  • Add Web Parts Pane
?ToolPaneView=2(Note: Add to the end of the page URL; WILL ONLY WORK IF THE PAGE IS ALREADY CHECKED OUT)

Tuesday, April 5, 2011

Setting Unique Constraints Programmatically:

This post was moved with bit more clear explanation. To visit the post here:
http://mysharepointquicksolutions.blogspot.in/2012/02/setting-unique-constraints-programmatic.html












Unique Columns

You can create unique column (meaning the column will hold the unique data) inside a list in SharePoint 2010. The unique column MUST be indexed. So while creating the unique column, SharePoint 2010 will ask you to index the Unique Column. E.g. Student “Registration No” can be a unique column in the “Student” list. You can also make any existing column as unique column provided it has unique data for all the list items.
JOIN and Querying Data from Two Lists:-
Developers can query the SharePoint 2010 List using CAML and LINQ to SharePoint and select fields from two different lists as shown in the code below. Here in the below code ( LINQ To SharePoint), I have retrieved all the “Students” for the Department “Computer Science”.
Note: - In order to use LINQ to SharePoint you have to generate the “SharePoint Context” from the SPMetal tool (now comes as a part of SharePoint 2010), which is located at the following directory. (“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN”). Here is syntax to generate your Context.cs file.
SPMetal /web:http://mossserver:8000 /namespace:SPTeamSite /code:SPTeamSite.cs
After this create a new project in VS2010, add the reference to Microsoft.SharePoint.Linq.dll & Microsoft.SharePoint.dll located at the following directory. (“C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI”). Also add the SPTeamSite.cs file generated from the SPMetal tool. See the diagram below.
Now here is the code to retrieve all the “Students” of a particular “Department”.

Note: We can set unique constraints to the list or lirary programtically. For this, plse refer the below url:
Setting Unique Constraints Programmatically:

Friday, April 1, 2011

Why Sandbox solution will not support Visual Webpart

The standard Visual Web Part is not supported in the sandbox environment. The reason for this is because Visual Web Parts effectively host an ASCX user control within the Web Part control. The ASCX file is deployed to the _controltemplates virtual directory in the physical file system on each Web front-end server. The sandbox environment does not allow you to deploy physical files to the SharePoint root, so you cannot use a sandboxed solution to deploy a Visual Web Part based on the Visual Studio 2010 Visual Web Part project template.

A Visual Studio Power Tool is available that addresses this issue. A Power Tool is a plug in for Visual Studio. The tool will generate and compile code representing the user control (.ascx) as part of the assembly. This avoids the file deployment issue. You can download a Power Tool for Visual Studio 2010 that supports Visual Web Parts in the sandbox from
Visual Studio 2010 SharePoint Power Tools on MSDN.

Thursday, March 24, 2011

How to deploy application pages using sandbox solution in SharePoint 2010

Full trust proxy in SharePoint sandbox solution

You know that sandbox solution in SharePoint 2010 has certain limitation like
• It doesn’t allow using web services.
• You can’t access SharePoint web controls
• It won’t allow executing code that runs under elevated privileges etc…
So, basically sandbox solution provides restricted environment to execute your code for specific SharePoint site.

What if you want to execute a web service inside a sandbox solution? The solution is to write a full trust proxy. Let’s solidify this requirement by creating a web part that gets the data from a web part. I’m going to write a simple sandbox solution that displays xml string returned from Lists.GetList(“your list name”) method.

There are three parts of this code.
• Create a proxy: This will execute your sharepoint web service and return xml
• Register full trust proxy.
• Write a web part

Create a proxy
1. Add a class library project to your solution say “RVProxy”.
2. Add a class file inside it say “ServiceHelper.cs”.
3. Copy and paste below code to your ServiceHelper.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.UserCode;
using System.Xml;

[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]
namespace RVProxy
{
public class ServiceHelper:SPProxyOperation
{
public override object Execute(SPProxyOperationArgs args)
{
if (args != null)
{
ListArgs lstArg = args as ListArgs;
string listName = lstArg.ListName;
RVListOperation.Lists lst = new RVListOperation.Lists();
lst.PreAuthenticate = true;
lst.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode node = lst.GetList(listName);
return node.InnerXml;
}
else
{
return null;
}
}
}

[Serializable]
public class ListArgs:SPProxyOperationArgs
{
public ListArgs(string listName)
{
this.ListName = listName;
}
public string ListName
{
get;
set;
}

}
}

In the above code, note that assembly has been tagged with attribute [assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]. This tells the compiler to execute the assembly in partially trusted environment.

Class ServiceHelper inherits SPProxyOperation class. Implement its Execute() method. This method contains all the code that runs under trusted mode.

Class ListArgs serves as an input argument sent to the proxy. Don’t forget to decorate this class with attribute [Serializable]


Now your proxy is ready. You need to register this as full trust proxy.
Register full trust proxy
1. Put the “RVProxy” dll into the GAC.
2. Register this dll as full trust proxy. You can either register this using powershell script or using SharePoint object model. I’ll explain the second one here
a. Create a windows application
b. Use below code to register, unregister or view registered assemblies:
Register
private void RegisterFullTrustProxty(string assemblyName, string typeName)
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
service.ProxyOperationTypes.Add(getEventLogItemCreationOperation);
service.Update();
label1.Text = "Updated successfully!";
}
else
{
label1.Text = "Update failed!";
} 
}
For e.g RegisterFullTrustProxty("RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1"
, "RVProxy.ServiceHelper"
);

Unregister
private void UnregisterFullTrustProxty(string assemblyName, string typeName)
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
service.ProxyOperationTypes.Remove(getEventLogItemCreationOperation);
service.Update();
label1.Text = "Removed succesfully!";
}
else
{
label1.Text = "Remove failed!";
} 
}

View all registered assemblies
private void ViewAllRegisteredProxy()
{
label1.Text = "";
lblRegisteredProxy.Text = "";
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
int count = service.ProxyOperationTypes.Count;
lblRegisteredProxy.Text = "Proxy count: " + count.ToString() + Environment.NewLine ;
foreach (SPProxyOperationType item in service.ProxyOperationTypes)
{
lblRegisteredProxy.Text += "AssemblyName: " + item.AssemblyName + Environment.NewLine + "TypeName: " + item.TypeName + Environment.NewLine;
}
}
}
Write the web part
You have created the proxy as well as registered as a full trust proxy. Now it’s time to utilize this proxy in your web part code. I’m pasting here a sample code that utilizes the above proxy:

[ToolboxItemAttribute(false)]
public class DemoPart : WebPart
{
Label lbl = new Label();
Button btnTest = new Button()
{
Text = "Get List"
public DemoPart()
{
btnTest.Click += new EventHandler(btnTest_Click); 
}

void btnTest_Click(object sender, EventArgs e)
{
string assemblyName = "RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1";
string typeName = "RVProxy.ServiceHelper";
string listInfo = SPUtility.ExecuteRegisteredProxyOperation(assemblyName, typeName, new ListArgs("Tasks")).ToString();
lbl.Text += listInfo;
}
protected override void CreateChildControls()
{
lbl.Text = "Hi Ranvijay, here is your web part under sandbox solution.";
Controls.Add(lbl);
Controls.Add(btnTest);
}
Note: The proxy runs under SPUserCodeService.exe service. So, every time you make changes to your proxy and redeploy the dll to GAC, you will need to restart the “SPUserCodeV4”. To stop use "net stop SPUserCodeV4" and to start use "net start SPUserCodeV4"

The Web application at http://sp2010:12523 could not be found. Verify


Unhandled Exception: System.IO.FileNotFoundException: The Web application at http://sp2010:12523 could not be found. Verify

that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.


private void button1_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://sp2010:12523"))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection lstColl = web.Lists;
}
}
}


Workaround


When you create a new application, it defaults to x86. However sharepoint 2010 is a 64 bit application.


To resolve the issue, View your project properties, go to the Build tab and change the platform target to x64. Run your application again and everything should work as expected now.