Lookup Field as a Site Column using CAML | SharePoint Lookup field

February 9, 2014 2 comments

Its very important when you are using CAML  syntax for Lookup field to use Overwrite=”TRUE” otherwise you will be in trouble. For multi lookup field type use the following schema:

<Field
ID=”{63C4B167-F089-4A3E-8D2D-76DB12F63FFA}”
Name=”ProdTitle”
DisplayName=”Prod:Title”
Overwrite=”TRUE”
ReadOnly=”FALSE”
List=”Lists/ListName”
ShowField=”Title”
Required=”FALSE”
Type=”LookupMulti”
Mult=”TRUE”
></Field>

For lookup field type just use the following schema

<Field
ID=”{63C4B167-F089-4A3E-8D2D-76DB12F63FFA}”
Name=”ProdTitle”
DisplayName=”Prod:Title”
Overwrite=”TRUE”
ReadOnly=”FALSE”
List=”Lists/ListName”
ShowField=”Title”
Required=”FALSE”
Type=”Lookup”
></Field>

You can use the following code snippet to set value in SP list item.

Suppose hiddenValue = “1:test1;2:test2;3:test3;”

var lookupItems = new SPFieldLookupValueCollection();
var items = hiddenValue.Remove(hiddenValue.LastIndexOf(‘;’)).Split(‘;’);
lookupItems.AddRange(items.Select(item => new SPFieldLookupValue(Convert.ToInt32(item.Split(‘:’)[0]), item.Split(‘:’)[1])));

 

Categories: SharePoint Tags:

Safest way to read SharePoint List item using C#

January 29, 2014 1 comment

We all know, when we need to read SharePoint list item, before trying to retrieve the value, we need to check whether that field is exits or not. Suppose in your page content type, you have RollupImage and PublishingPageImage. But in case if the list item contain only PublishingPageImage value and RollupImage value is empty and if you tried to access RollupImage value, definitely you will get exception. So you have to check whether this is null or not. You can use following method if you want 🙂

If you have Guid type field, you can get value using the following method. PublishingPageImage and RollupImage field type is Guid type. You can  check the following code:

ImageFieldValue value =
default(Microsoft.SharePoint.Publishing.Fields.ImageFieldValue);

if (TryGetValue<Microsoft.SharePoint.Publishing.Fields.ImageFieldValue>(listItem, FieldId.RollupImage, out value))
{
item.ImageUrl = value.ImageUrl;
}
else
{
item.ImageUrl = TryGetValue<Microsoft.SharePoint.Publishing.Fields.ImageFieldValue>(listItem, FieldId.PublishingPageImage, out value) ? value.ImageUrl : string.Empty;
}

public static bool TryGetValue<T>(SPListItem listItem, Guid fieldId, out T value)
{
value = default(T);
try
{
if (listItem.ContentType.Fields.Contains(fieldId))
{
object rawValue = listItem[fieldId];
if (rawValue != null)
{
value = (T)rawValue;
return true;
}
else
{
return false;
}
}
else
return false;
}
catch (Exception)
{

return false;
}
}

Categories: C#, SharePoint

SharePoint friendlyurl using server object model

January 29, 2014 Leave a comment

Its a common thing to know about friendly url if you are working on SharePoint 2013. I am not discussing about what is friendly url. You can simply use my code to get your friendly url.

public string GetFriendlyUrl(string Path, string siteUrl)
{
var friendlyUrl = string.Empty;
if (!String.IsNullOrEmpty(Path))
{
SPListItem listItem = null;
_uri = new Uri(siteUrl + Path);

var file = _web.GetFile(_uri.AbsolutePath);
listItem = file.ListItemAllFields;
if (listItem != null)
{
if (!listItem.ContentTypeId.IsChildOf(ContentTypeIds.Page))
{
return string.Empty;
}
}
if (listItem != null)
{

var friendlyUrls = TaxonomyNavigation.GetFriendlyUrlsForListItem(listItem, true);
if (friendlyUrls.Count > 0)
{
friendlyUrl = friendlyUrls[0].GetResolvedDisplayUrl(string.Empty);
}
}
}
return friendlyUrl;
}

Categories: SharePoint Tags:

How to export custom complex type data as a web part property in SharePoint

January 28, 2014 Leave a comment

If you want to add custom property in a webpart, you need to implement Editor Part. Suppose you have several Taxonomy Field and some other information and you wanted to export those information. By default you will get only basic type information, when you will export the web part. So what you can do ? I guess its so easy. My proposed solution is to add one string property in Parent webpart. Then add the following method.

[WebBrowsable(false),
Personalizable(PersonalizationScope.Shared), Category(“Settings”),
System.ComponentModel.DefaultValue(“”)]
public string SampleData { get; set; }

Serialize as Xml and convert as Xml CDATA data using XCData

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var cdata = new XCData(GetXmlValue());
string cdataString = cdata.ToString();
SampleData = cdataString;
}

private string GetXmlValue()
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<ImageRollupItem>));
var settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false);
settings.Indent = true;
settings.OmitXmlDeclaration = true;

using (var textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, CorouselData);
}
return textWriter.ToString();
}
}

Markup as Serializable for the Class and define the XmlRoot name.

[Serializable]
[XmlRoot(“ImageData”)]
public class ImageRollupItem
{
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public string FriendlyUrl { get; set; }
public string ImageUrl { get; set; }
public string FileType { get; set; }
public bool IsValid { get; set; }
}

If you have other solution please reply on this thread. Thanks.

Categories: SharePoint Tags: ,

How to save data in SharePoint List without providing List Url

January 28, 2014 Leave a comment

It is a very simple post. We all know how to save data in SharePoint list. But in here it is little bit interesting. You dont need to provide any list information. But you need to know your content type id. Something like this:

    public static SPContentTypeId YourContentTypeName = new SPContentTypeId(“0x01009FB8784745E54744BAD252BB7AB08647”);

Here is one simple method to find out the List url:

public string GetListUrl()
{
_site = new SPSite(_siteUrl);
SPContentType ct = _site.RootWeb.ContentTypes[YourContentTypeName ];
var usages = SPContentTypeUsage.GetUsages(ct).FirstOrDefault();
if (_site != null) _site.Dispose();
if (usages != null) return usages.Url;
return string.Empty;
}

Final implementation code is in bellow:

public void SaveData(CustomClass item)
{
var listName = GetListUrl() != string.Empty ? GetListUrl().Split(‘/’).Last() : string.Empty;
if(!string.IsNullOrEmpty(listName))
{
using (var site = new SPSite(_siteUrl))
{
using (var web = site.RootWeb)
{
var list = web.Lists[listName];
var newItem = list.Items.Add();

newItem[“Comment”] = item.Comment;
newItem[“Email”] = item.Email;
web.AllowUnsafeUpdates = true;
newItem.Update();
web.AllowUnsafeUpdates = false;
}
}

}
}

Categories: SharePoint Tags: ,

Programmatically how to implement Keyword Query in SharePoint 2013

January 28, 2014 1 comment

Here I am  not discussing what is Keyword query. Rather i am gonna add some implementation code in here.

using (var query = new KeywordQuery(_site))
{
query.RowLimit = rowLimit > 0 ? rowLimit : query.RowLimit;

query.StartRow = 0;
query.TrimDuplicatesOnProperty = “FullNameOWSTEXT”;
query.EnableStemming = false;
query.IgnoreAllNoiseQuery = true;
query.SortList.Add(“FullNameOWSTEXT”, SortDirection.Descending);

query.SourceId = new Guid(“0cc4911f-4f1a-4052-b3e4-72f839e182ce”); // you need to know your source id.

query.SelectProperties.AddRange(new[] { “ContactImage”, “FullNameOWSTEXT” });

var se = new SearchExecutor();
var rtc = se.ExecuteQuery(query);

if (rtc.Count > 0)
{
var results = rtc.Filter(“TableType”, KnownTableTypes.RelevantResults);
if (results != null && results.Count() == 1)
{
var rt = results.First();
if (rt.ResultRows.Count > 0)
{
items = new List<CustomClassItem>();
var dataRows = rt.ResultRows;

items = (from DataRow row in dataRows
where !String.IsNullOrEmpty(row[“FullNameOWSTEXT”] as string)
orderby row[“FullNameOWSTEXT”] as string ascending
select new BloggerItem()
{
Name = row[“FullNameOWSTEXT”] as string,
ImageUrl = row[“ContactImage”] != null ? Utility.GetUrlFromImageTag(row[“ContactImage”].ToString()) : String.Empty // here you can either add some utility method to find out image url. upto you
}).ToList();
}
}
}
}

Categories: SharePoint

Image rendition in SharePoint 2013

January 28, 2014 1 comment

Image rendition is a new capability in SharePoint 2013 helps you to optimize images in your SharePoint site through having the same image but in different sizes. This will enhance the user experience through browsing the SharePoint site from different devices, like laptop or mobile.

Implementation Steps:

  1. Create a publishing site collection.
  2. Go to the settings. you will find the image rendition option.

Settings

But its not done yet. Have to enable Blob Cache from web.config file. You will find the web.config file location in : C:\inetpub\wwwroot\wss\VirtualDirectories\[Port Number]\web.config. By default it is disabled.

<BlobCache location=”C:\BlobCache\14″ path=”\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|themedbmp|themedcss|themedgif|themedjpg|themedpng|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|wmv|ogg|ogv|oga|webm|xap)$” maxSize=”10″ enabled=”false” />

In the image rendition, you will specify all of your rendition name, width and height.

image rendition

When you add image item, you will see the edit rendition option in the image. If you want, you can change the size and save it.

Now how to set the rendition id in code behind:

Suppose you have the following html:

 <img src=”<%# GetImageUrlWithRendition(Item.ImageUrl, ImageRenditions.ThumbnailThin) %>”/>

Here ImageRenditions.ThumbnailThin is the Enum value where all the id is defined. Like:

public enum ImageRenditions
{
ImageGrid1 = 5,
ImageGrid2 = 6,
ImageGrid3 = 7,
ImageGrid4 = 8,
BlogPostListning = 9,
ThumbnailThin = 10,
ThumbnailSquare = 11
}

And the following utility function in your code:

public static string GetImageUrlWithRendition(string imageUrl, ImageRenditions imageRendition)
{
var imageRenditionParam = String.Format(“RenditionID={0}”, (int) imageRendition);
var regex = new Regex(“\\bRenditionID=[\\d]+\\b”);

return regex.Match(imageUrl).Success ?
regex.Replace(imageUrl, imageRenditionParam) :
String.Format(“{0}{1}{2}”, imageUrl, imageUrl.Contains(“?”) ? “&” : “?”, imageRenditionParam);
}

Everything is settled now.

 
Categories: SharePoint

How to get SharePoint List item data using server object model without providing List Name

January 26, 2014 157 comments

In the following way, just have to know the content type name. Create a SharePoint List using the targeted content type.

public List<ClassName> GetSharePointListData()
{
List<ClassName> items;

SPContentType ct = _site.RootWeb.ContentTypes[ContentTypeName or Content type id];
var usages = SPContentTypeUsage.GetUsages(ct).FirstOrDefault();
if (usages != null && usages.IsUrlToList)
{
items = new List<ClassName>();
SPList list = _web.GetList(usages.Url);
SPQuery query = new SPQuery();
query.Query = string.Concat(
“<Where><Eq>”,
“<FieldRef Name=’ContentType’/>”,
string.Format(“<Value Type=’Text’>{0}</Value>”, ct.Name),
“</Eq></Where>”);
SPListItemCollection listItemCollections = list.GetItems(query);
if (listItemCollections!= null && listItemCollections.Count > 0)
{
for (int i = 0; i < listItemCollections.Count; i++)
{
SPListItem oListItem = listItemCollections[i];
var item = new ShareHolderItem
{
property1 = oListItem[“prop”] != null ? Convert.ToInt32(oListItem[“prop”]) : 0

};
items.Add(item);
}
}
}
return items;
}

Categories: C#, SharePoint

How to clear all the control values in a asp.net page

January 26, 2014 1 comment

All the controls which you want to clear the values in page post back, you have to put all those controls inside a container control like Panel and pass the control as a parameter in the following function. All the controls value will reset.

private void ResetFormValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormValues(c);
}
else
{
switch (c.GetType().ToString())
{
case “System.Web.UI.WebControls.TextBox”:
((TextBox)c).Text = “”;
break;
case “System.Web.UI.WebControls.CheckBox”:
((CheckBox)c).Checked = false;
break;
case “System.Web.UI.WebControls.RadioButton”:
((RadioButton)c).Checked = false;
break;
case “System.Web.UI.WebControls.DropDownList”:
((DropDownList)c).SelectedIndex = 0;
break;
}
}
}
}

Categories: ASP.NET

how to get SharePoint List url from Content type

January 24, 2014 1 comment

SPContentType ct = _site.RootWeb.ContentTypes[“content_type_name”];
var usages = SPContentTypeUsage.GetUsages(ct).FirstOrDefault();
if (usages != null)
{
var url = usages.Url;
}

Categories: SharePoint
Create your own website, free on WordPress.com.Create your own website.
Start free