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

Saturday, March 7, 2015

The name ‘InitializeControl’ does not exist in this context. SharePoint 2013 Visual Web Part development

While developing Visual Web Parts for SharePoint 2013 using Visual Studio 2012, suddenly you may get an error. “The name ‘InitializeControl’ does not exist in this context”.

1

To fix this error quickly, select user control file (.ascx) of visual web part in Visual Studio and check if its property Custom Tool = SharePointWebPartCodeGenerator.

2

Also make sure that Site URL property of your project is set properly.

Then, right click on user control (.ascx) of visual web part and click on “Run Custom Tool”. It will fix all issues with .ascx.g.cs file and you will be good to go.

3

Thursday, June 13, 2013

Read column value for a list item programmatically

While reading list item’s column value using code, we get exception if column is empty/ null. To avoid such exception, we can use this line of code while reading column value.

if (item["ColumnInternalName"] != null && SPEncode.HtmlEncode(item["ColumnInternalName"].ToString()) != string.Empty && !string.IsNullOrEmpty(item["ColumnInternalName"].ToString()))
{
ImageFieldValue image = (ImageFieldValue)item["ColumnInternalName"];
imageURL = image.ImageUrl;
}
else
{
imageURL = "/_layouts/images/icon.png";
}


Friday, November 12, 2010

Check programmatically if List is already exists in SharePoint site


While programming with SharePoint Object Model, sometimes we are in situation where we need to check if a list is already exists in given scope especially or we should create a new list. We can check this by creating a list in a try block and if list already exists it will throw exception which will be handled in catch block. However we can check it by other couple of ways.

  • Check if lists exists.
       string listName = "Tasks";
    SPSite site = (SPSite)properties.Feature.Parent;
    SPWeb webName = site.RootWeb;
    bool isListExixts = webName.Lists.TryGetList(listName);
    if (isListExixts == true)
        // List Exists.

  • Iterate through collection of lists and match for each list with specified list name. 
   string listName = "Tasks";

SPSite site = (SPSite)properties.Feature.Parent;
SPWeb webName = site.RootWeb;
SPListCollection listCollection = webName.Lists;
foreach (SPList tempList in listCollection)
{
   if (tempList.Title == listName)
      return true;
}

  • Iterate through list of collection using this code.
   string listName = "Tasks";

SPSite site = (SPSite)properties.Feature.Parent;
SPWeb webName = site.RootWeb;
if(webName.Lists.Cast<SPList>().Any(list => list.Title.Equals(listName, StringComparison.OrdinalIgnoreCase)))
{
   return true;
}


In both ways, code looks into List collection and if Task list is already exists it returns true.

Monday, November 1, 2010

Create custom User Profile properties in SharePoint 2010 reading from XML file

We create custom User Profile properties quite often in SharePoint. User Profile properties are created easily in Central Administration web site however while developing large enterprise solutions, direct access to production servers are not usually available to developers. To achieve such goals, we usually develop console applications which runs during deployment script or develop features which execute code during feature activation. User Profile properties can be created in SharePoint development environment using Microsoft.Office.Server.UserProfiles namespace. A simple XML file containing details of required custom properties can be used as input. Here is sample XML which I created for this example.
<Properties Server="http://flhsrv116" TermStore="Managed Metadata Service Application Proxy">
<Property>
<Name>Audience</Name>
<DisplayName>Audience</DisplayName>
<!-- Collection of Values for Type Node : (big integer | binary | boolean | date | date no year | date time | Email | float | unique identifier | HTML | integer | Person | string | string (Single Value) | string (Multi Value) | Time Zone | URL)  -->
<Type>string (Multi Value)</Type>
<!-- IsMultiValue : Possible Options true | false :  Note = Only true when Type = String (Multi Value) -->
<IsMultiValue>true</IsMultiValue>
<TermStoreGroup>DSG</TermStoreGroup>
<TermSet>Audiences</TermSet>
</Property>

<Property>
<Name>DateofJoining</Name>
<DisplayName>Date of Joining</DisplayName>
<!-- Collection of Values for Type Node : (big integer | binary | boolean | date | date no year | date time | Email | float | unique identifier | HTML | integer | Person | string | string (Single Value) | string (Multi Value) | Time Zone | URL)  -->
<Type>date</Type>
<!-- IsMultiValue : Possible Options true | false -->
<IsMultiValue>false</IsMultiValue>
<TermStoreGroup>null</TermStoreGroup>
<TermSet>null</TermSet>
</Property>
</Properties>

In this simple example, I am creating two properties. One is of date type and second is of term set type. This XML file has a root node with two attributes and two child nodes. Each child node represent a custom property. Property’s name, display name, type and other properties can be configured as mentioned above. At the moment, we have only one custom property of term set type in User Profile store.

Properties1

To do this, create a console application in Visual Studio 2010.
Add references of System.Xml, Microsoft.Office.Server.UserProfiles, Microsoft.SharePoint and Microsoft.SharePoint.Taxonomy if term set type value is required to create.
Add this code in .cs file.


using System;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.Xml;
using System.Collections;

namespace UserProfilesOMApp
{
class Program
{
static void Main(string[] args)
{
string str = "UserProfileProperties.xml";

// Reading XML document.

XmlDocument doc = new XmlDocument();
doc.Load(str);

// Reading Parent node of document.
XmlNode xmlNode = doc.DocumentElement;
XmlNodeList propertiesxmlnodeList = doc.GetElementsByTagName("Properties");

// Reading Attributes for parent node.
XmlElement xmlElement = (XmlElement)propertiesxmlnodeList.Item(0);

string servername = xmlElement.GetAttribute("Server");
string termstore = xmlElement.GetAttribute("TermStore");

// Reading property node and its Child node lists.
XmlNodeList propertyxmlnodeList = doc.GetElementsByTagName("Property");
XmlNodeList namelist = doc.GetElementsByTagName("Name");
XmlNodeList displaynamelist = doc.GetElementsByTagName("DisplayName");
XmlNodeList typelist = doc.GetElementsByTagName("Type");
XmlNodeList ismultivaluelist = doc.GetElementsByTagName("IsMultiValue");
XmlNodeList termsetlist = doc.GetElementsByTagName("TermSet");
XmlNodeList termstoregrouplist = doc.GetElementsByTagName("TermStoreGroup");


string propertyname = null;
string displayname = null;
string type = null;
string ismultivalue = null;
string termstoregroup = null;
string termset = null;

using (SPSite site = new SPSite(servername))
{

for(int x = 0; x < propertyxmlnodeList.Count; x++)
{

propertyname = namelist.Item(x).InnerText.ToString();
displayname = displaynamelist.Item(x).InnerText.ToString();
type = typelist.Item(x).InnerText.ToString();
ismultivalue = ismultivaluelist.Item(x).InnerText.ToString();
termstoregroup = termstoregrouplist.Item(x).InnerText.ToString();
termset = termsetlist.Item(x).InnerText.ToString();

// Method call for creating a user profile property.
Program.createProfileProperties(site, termstore, propertyname, displayname, type, ismultivalue, termstoregroup, termset);               
}
}
}

static void createProfileProperties(SPSite site, string termstore, string propertyname, string displayname, string type, string ismultivalue, string termstoregroup, string termset)
{

SPServiceContext context = SPServiceContext.GetContext(site);
UserProfileConfigManager upcm = new UserProfileConfigManager(context);

try
{
ProfilePropertyManager ppm = upcm.ProfilePropertyManager;
Console.WriteLine("Creating Propoerty");
// Create core property.
CorePropertyManager cpm = ppm.GetCoreProperties();
CoreProperty coreproperty = cpm.GetPropertyByName(propertyname);

// Check if property already exists.
if (coreproperty != null)
{
Console.WriteLine("Property already exists......");
return;                    
}

CoreProperty cp = cpm.Create(false);
cp.Name = propertyname;
cp.DisplayName = displayname;
//Get Property Type from Enumeration.
PropertyDataTypeCollection pdtc = upcm.GetPropertyDataTypes();
PropertyDataType ptype = null;
IEnumerator enumType = pdtc.GetEnumerator();
while (enumType.MoveNext())
{
ptype = (PropertyDataType)enumType.Current;
if (ptype.Name.ToString().ToLower().Equals(type.ToString().ToLower())) break;
}

cp.Type = ptype.Name;

if(type.ToLower() == "string (Multi Value)".ToLower())
{
cp.IsMultivalued = Convert.ToBoolean(ismultivalue);
if (ismultivalue.ToLower() == "true".ToLower())
{
cp.Separator = MultiValueSeparator.Semicolon;
}

// Set the TermSet.
TaxonomySession taxonomySession = new TaxonomySession(site);
TermStore termStore = taxonomySession.TermStores[termstore];
Group group = termStore.Groups[termstoregroup];
TermSet termSet = group.TermSets[termset];

cp.TermSet = termSet;
}

cpm.Add(cp);

// Create profile type property.
ProfileTypePropertyManager ptpm = ppm.GetProfileTypeProperties(ProfileType.User);
ProfileTypeProperty ptp = ptpm.Create(cp);
ptp.IsVisibleOnViewer = true;
ptp.IsVisibleOnEditor = true;

ptpm.Add(ptp);

// Create profile subtype property.
ProfileSubtypeManager psm = ProfileSubtypeManager.Get(context);
ProfileSubtype ps = psm.GetProfileSubtype(ProfileSubtypeManager.GetDefaultProfileName(ProfileType.User));

ProfileSubtypePropertyManager pspm = ps.Properties;        

ProfileSubtypeProperty psp = pspm.Create(ptp);

psp.PrivacyPolicy = PrivacyPolicy.OptIn;
psp.DefaultPrivacy = Privacy.NotSet;


pspm.Add(psp);

Console.WriteLine("\nuser profile property "+ displayname + " created successfully.\n");
Console.ReadKey();
}
catch (DuplicateEntryException e)
{
Console.WriteLine(e.Message);
Console.Read();
}
catch (System.Exception e2)
{
Console.WriteLine(e2.Message);
Console.Read();
}
}
}
}

After running this code, this output will come.

Output

Now, in User Profile store, two custom properties has been added.

Properties
Download project solution as zip file.

Friday, October 15, 2010

Reference files via relative path in C# using Visual Studio 2010

While building solutions in Visual Studio especially writing console applications, we come across a situation where we need to refer other files in our code. Reading and writing in XML files are the most common example of such actions. And obviously we do not want to set absolute path in our code for these files. So how we can do this in Visual Studio 2010. For example, in my C# code, I am referring a XML file “UserProfileProperties.xml” which is placed on the same level where “Program.cs” is located.

XMLFileLoad

When I run this code, it gives me FileNotFoundException.

XMLError

To solve this issue, I select this xml file and change value of “Copy to Output Directory” from Do not copy to Copy always. After this change, above C# code starts working.

XMLFile