Monday, December 13, 2010

Opening a SharePoint Portal and Sending back form information to its parent Page

Last week I got another code challenge when I was given a task as follows:

  1. There will a be a popup which will open from Editor Part of my custom Web Part Properties
  2. User will select a user names from the list into popup and click Ok button.
  3. Now selected user names will be added into the list box control of Editor Part.

Solution:

As I had to bring the selected users from popup to parent page and parent List will be auto refreshed with the new added users.

So I kept my consolidated users details into one hidden textbox and do post back so that updated details gets refreshed in List box.

  1. Beacause we need to open SharePoint popup from Editor Part so we will have to write our popup opening javascript at runtime. As follows:
        private void GenerateJavascript()

{
string strPath = SPContext.Current.Web.Url + "/_layouts/Egspi/Default/DlgContactsSearch.aspx";
string strScript =
"function OpenDialog() { " +
"var options = SP.UI.$create_DialogOptions(); " +
"options.url = '" + strPath + "'; " +
"options.width = 360;" +
"options.height = 300; " +
"options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);" +
"SP.UI.ModalDialog.showModalDialog(options); " +
"}" +
"var messageId;" +

"function CloseCallback(result, target) { " +
"var strConsol='';" +
"if(result === SP.UI.DialogResult.OK) { " +
"var txtSearch = document.getElementById('" + txtContacts.ClientID + "');" +
"if (target != ''){" +
"var strExisting = txtSearch.value;" +
"var arrExisting = strExisting.split('#');" +
"var arrNew = target.split('#');" +
"var arrConsol = unique(arrExisting.concat(arrNew));" +
"strConsol = arrConsol.join('#');" +
"}" +
"txtSearch.value=strConsol; " +
"__doPostBack();" +
"}" +
"}" +

"function unique(arrayName) {" +
"var newArray = new Array();" +
"label: for (var i = 0; i < arrayName.length; i++) {" +
"for (var j = 0; j < newArray.length; j++) {" +
"if (newArray[j] == arrayName[i])" +
"continue label;" +
"}" +
"newArray[newArray.length] = arrayName[i];" +
"}" +
"return newArray;" +
"}" +

"function btnDeleteContacts_Click() {" +
"var strNewContacts = '';" +
"var txtSearch = document.getElementById('" + txtContacts.ClientID + "');" +
"var containerRef = document.getElementById('" + cblContacts.ClientID + "');" +
"var inputRefArray = containerRef.getElementsByTagName('input');" +
"var spanRefArray = containerRef.getElementsByTagName('span');" +
"for (var i = 0; i < inputRefArray.length; i++) {" +
"var inputRef = inputRefArray[i];" +
"if (inputRef.type.substr(0, 8) == 'checkbox') {" +
"if (inputRef.checked != true) {" +
"if (strNewContacts != '')" +
"strNewContacts += '#';" +
"strNewContacts += spanRefArray[i].getAttribute('optValue') + '~' + spanRefArray[i].getAttribute('optText');" +
"}" +
"}" +
"}" +
"txtSearch.value=strNewContacts;"+
"__doPostBack();" +
"}";

Page.ClientScript.RegisterClientScriptBlock(typeof(ContactsEditorPart), "ContactsDialogJavaScript", strScript, true);
}
 
  • OpenDialog(): This method will open our desired Popup.
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);

check out 2nd parameter it says that this method will be called from parent when popup will get closed.


  • CloseCallback(): This method will get the selected values into target parameter as string
    Then it will check any duplicate username which is already present into Editor Part List Control, if yes then it will remove it from the target string.
    Finally it will insert target string into my hidden text box.

  • Unique(): This is simple method to remove the duplicate array elements.

  • btnDeleteContacts_Click() : There is an option to select and delete any user from Editor Part list control.

Sunday, December 12, 2010

Opening a Sharepoint Portal and Sending back form information to its parent Page

Last week I got another code challenge when I was given a task as follows:

  1. There will a be a popup which will open from Editor Part of my custom Web Part Properties
  2. User will select a user names from the list into popup and click Ok button.
  3. Now selected user names will be added into the list box control of Editor Part.
Sol:

  1. Beacause we need to open SharePoint popup from Editor Part so we will have to write our popup opening javascript at runtime. As follows:

private void GenerateJavascript() { string strPath = SPContext.Current.Web.Url + "/_layouts/Egspi/Default/DlgContactsSearch.aspx"; string strScript = "function OpenDialog() { " +
"var options = SP.UI.$create_DialogOptions(); " + "options.url = '" + strPath + "'; " + "options.width = 360;" + "options.height = 300; " + "options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);" + "SP.UI.ModalDialog.showModalDialog(options); " + "}" + "var messageId;" + "function CloseCallback(result, target) { " + "var strConsol='';" + "if(result === SP.UI.DialogResult.OK) { " + "var txtSearch = document.getElementById('" + txtContacts.ClientID + "');" + "if (target != ''){" + "var strExisting = txtSearch.value;" + "var arrExisting = strExisting.split('#');" + "var arrNew = target.split('#');" + "var arrConsol = unique(arrExisting.concat(arrNew));" + "strConsol = arrConsol.join('#');" + "}" + "txtSearch.value=strConsol; " + "__doPostBack();" + "}" + "}" + "function unique(arrayName) {" + "var newArray = new Array();" + "label: for (var i = 0; i < arrayName.length; i++) {" + "for (var j = 0; j < newArray.length; j++) {" + "if (newArray[j] == arrayName[i])" + "continue label;" + "}" + "newArray[newArray.length] = arrayName[i];" + "}" + "return newArray;" + "}" + "function btnDeleteContacts_Click() {" + "var strNewContacts = '';" + "var txtSearch = document.getElementById('" + txtContacts.ClientID + "');" + "var containerRef = document.getElementById('" + cblContacts.ClientID + "');" + "var inputRefArray = containerRef.getElementsByTagName('input');" + "var spanRefArray = containerRef.getElementsByTagName('span');" + "for (var i = 0; i < inputRefArray.length; i++) {" + "var inputRef = inputRefArray[i];" + "if (inputRef.type.substr(0, 8) == 'checkbox') {" + "if (inputRef.checked != true) {" + "if (strNewContacts != '')" + "strNewContacts += '#';" + "strNewContacts += spanRefArray[i].getAttribute('optValue') + '~' + spanRefArray[i].getAttribute('optText');" + "}" + "}" + "}" + "txtSearch.value=strNewContacts;"+ "__doPostBack();" + "}"; Page.ClientScript.RegisterClientScriptBlock(typeof(ContactsEditorPart), "ContactsDialogJavaScript", strScript, true); }

  • OpenDialog(): This method will open our desired Popup.
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);

check out 2nd parameter it says that this method will be called from parent when popup will get closed.

  • CloseCallback: This method will get the selected values into target parameter as string

    Then it will check any duplicate username which is already present into Editor Part List Control, if yes then it will remove it from the target string.

    Finally it will insert target string into my hidden text box.

  • unique: This is simple method to remove the duplicate array elements.

  • btnDeleteContacts_Click() : There is an option to select and delete any user from Editor Part list control.


Monday, December 6, 2010

Security trimming on CustomActions tag for custom menu items and ribbon buttons

We often need to add a security trimming for our custom menu items or ribbon buttons using CustomActions tag.

Here is the solution

<customaction
ContentTypeId = "Text"
ControlAssembly = "Text"
ControlClass = "Text"
ControlSrc = "Text"
Description = "Text"
GroupId = "Text"
...
Rights = "Text"
..>

We can apply security trimming using 'Rights' attribute.

There are lot of options that can be used as value for this attribute.

Check out this link to see possible values


Happy Sharepointing :)

Monday, November 8, 2010

"BDC Metadata Store is currently unavailable" when I try to get the External Content Types on SPD

This issue I faced when I was trying to make one POC using BCS for SharePoint 2010.

First I found that my SP was trial so I upgraded it to "SharePoint Server with Enterprise Client Access License".

I was giving me same error even after upgrading then i saw on other vpc with same config and licence where it was working.

There I found the solution, which is that we need to do association of BDC service with the desired web application.

Goto : Central Admin -> Application Mgt -> Manage Web Application -> Select desired Web Application -> click 'Service Connections' from ribbon buttons -> in the popup make sure "Business Data Connectivity Service" is checked.

And bingo it worked..

Wednesday, October 20, 2010

Populate list items automatically when list definition feature gets activated

SharePoint 2010 - There was a requirement in which I had to populate 2 list items when its list definition feature gets activated.

Following is the solution:

Into Elements.xml file of list instance


< ?xml version="1.0" encoding="utf-8"?>

< Elements xmlns="http://schemas.microsoft.com/sharepoint/">

< ListInstance Title=....... ;">



< Data>

< Rows>

< Row>

< Field Name="Title">.....</Field>

< Field Name="MailBody">.....</Field>

< /Row>

< Row>

< Field Name="Title">.....</Field>

< Field Name="MailBody"></Field>

< /Row>

< /Rows>

< /Data>



< /ListInstance>

< /Elements>

Happy SharePointing.... :)

Validate CheckboxList Control with javascript to make sure atleast one checkbox is checked

While developing one page which sends mail to the selected group from the checkbox list I got requirement to impose validation to check atleast one group should be selected.

Here is the solution.....

< id="CvalGroupCheckbox" display="Dynamic" runat="server" cssclass="MsgLabel" errormessage="" clientvalidationfunction="validateGroupSelection">

< language="javascript" type="text/javascript">

function validateGroupSelection(source, arguments) {
document.getElementById("").style.visibility = "hidden";
var chkSubUsers = document.getElementById('_0');
var chkTestUsers = document.getElementById('_1');

if ((!chkSubUsers.checked) && (!chkTestUsers.checked))
arguments.IsValid = false;
else
arguments.IsValid = true;
}

< /script>

Happy programming.... :)

Monday, August 30, 2010

Query to SharePoint database and WSS_Logging Database

While googling for my What's Hot web part I found 2 very good articles which explains why we should not query sharepoint db. And how we can use WSS_Logging db


Cheers

Monday, August 23, 2010

Monitoring SharePoint Usage through an ASP.NET Web Application

Monitoring SharePoint Usage through an ASP.NET Web Application
By Gayan Peiris

This is very good article for creating an application which can show a desired site usage details


Thursday, August 19, 2010

How to get a month name from date

We can get the month name using following statement

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(datValue.Month)

Cheers..

How to get all available page layouts which can be used to create and page

There was a task in which i had to check what all page layouts are available for a current site which can be used to create a new page. So here is the solution

PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

PageLayout[] pageLayouts = pubWeb.GetAvailablePageLayouts();

PageLayout pageLayout = pageLayouts.Where(p => p.Title.Trim() == item["LayoutName"].ToString().Trim()).FirstOrDefault();

if (pageLayout == null)
.......

Cheers....

Check if List or document/Picture library already exists

During one of my project i came accross this situation many time when i had to check whether list or document library already exists or not. So here is the solution


To check document/picture library there is an existing method which can be used like below

if (!web.GetFolder(strName).Exists)
{
......
}

Here 'strName' is the name of document/picture library.

But for list this method does not work. Unfortunately there is no method to check if list exists so we need to do a trick for that, check out below

SPList list = null;
try
{
list = web.Lists[strListTitle];
}
catch { }
if (list == null)
{
.....

Cheers.





Sunday, August 1, 2010

Check if Page is already checked out

It is very helpful while editing the contents of a publishing page to check if desired page is already checked or not.

Here is is the code to check this

Sol 1:

if (pPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
pPage.CheckOut();

Sol 2:

SPFile fileSource = web.GetFile(strSourceFilePath);
SPUser user = null;
user = fileSource.CheckedOutBy;

if (user != null)
{....


If we does not check so then we may get error that page is already checked out.

Open a SharePoint popup after server trip

Last day i had a task in which when user clicks a button few pages got created at runtime and after this i had to show the popup window which will show a aspx page having status of all created pages whether successfully created or failed.

Challenge was to open the popup when button click server trip done (Page rerendered).

My method was creating a javascript at run time to open a popup. But issue was when it runs i gets a javascript error.

"Object Doesn't support this property or method"

Issue was my javascript was getting called even before its supporting js files gets load.

After some rnd i found the solution and here it is.

string strScript = "function OpenDialog() { var option = SP.UI.$create_DialogOptions(); option.url = '" + strPath + "'; option.width = 380; option.height = 330; SP.UI.ModalDialog.showModalDialog(option); } ExecuteOrDelayUntilScriptLoaded(OpenDialog, \"sp.ui.dialog.js\");";

ClientScript.RegisterClientScriptBlock(this.GetType(), "ShowStatusfunction", strScript, true);


Key thing is ExecuteOrDelayUntilScriptLoaded(OpenDialog, \"sp.ui.dialog.js\");";

What it does is, it will wait untill the specified js gets load then it will call the method

Cheers...





Tuesday, July 27, 2010

How to add a picker to select a site or website and pass the selected site url in textbox


check this article from PlanetWilson SharePoint Blog its good

SharePoint field objects – classname, name and types

While working on one of SharePoint project I searched for classnames and fieldtypes that I needed to identify all different field types.

Following table shows most important fields for list.

important fields.

Classname Type TypeAsString TypeDisplayName TypeShortDescription
Microsoft.SharePoint.SPFieldBoolean Boolean Boolean Yes/No Yes/No (check box)
Microsoft.SharePoint.SPFieldCalculated Calculated Calculated Calculated Calculated (calculation based on other columns)
Microsoft.SharePoint.SPFieldChoice Choice Choice Choice Choice (menu to choose from)
Microsoft.SharePoint.SPFieldComputed Computed Computed Computed Computed
Microsoft.SharePoint.SPFIeld ContentTypeId ContentTypeId Content Type Id Content Type Id
Microsoft.SharePoint.SPFieldCurrency Currency Currency Currency Currency ($, , ?)
Microsoft.SharePoint.SPFieldDateTime DateTime DateTime Date and Time Date and Time
Microsoft.SharePoint.SPFieldFile File File File File
Microsoft.SharePoint.SPField Guid Guid Guid Guid
Microsoft.SharePoint.SPFieldNumber Integer Integer Integer Integer
Microsoft.SharePoint.Portal.WebControls.BusinessDataField Invalid BusinessData Business data Business data
Microsoft.SharePoint.Publishing.Fields.ContentTypeIdFieldType Invalid ContentTypeIdFieldType Content Type Id Content Type Id
Microsoft.SharePoint.Publishing.Fields.HtmlField Invalid HTML Publishing HTML Full HTML content with formatting and constraints for publishing
Microsoft.SharePoint.Publishing.Fields.ImageField Invalid Image Publishing Image Image with formatting and constraints for publishing
Microsoft.SharePoint.Publishing.Fields.LayoutVariationsField Invalid LayoutVariationsField Variations Page Layout Variations
Microsoft.SharePoint.Publishing.Fields.LinkField Invalid Link Publishing Hyperlink Hyperlink with formatting and constraints for publishing
Microsoft.SharePoint.Publishing.Fields.PublishingScheduleEndDateField Invalid PublishingScheduleEndDateFieldType Publishing Schedule End Date Publishing Schedule End Date
Microsoft.SharePoint.Publishing.Fields.PublishingScheduleStartDateField Invalid PublishingScheduleStartDateFieldType Publishing Schedule Start Date Publishing Schedule Start Date
Microsoft.SharePoint.Publishing.Fields.SummaryLinkField Invalid SummaryLinks SummaryLinks Summary Links data
Microsoft.Office.Server.WebControls.FieldTypes.SPFieldTargetTo Invalid TargetTo Audience Targeting Audience Targeting
Microsoft.SharePoint.SPFieldLookup Lookup Lookup Lookup Lookup (information already on this site)
Microsoft.SharePoint.SPFieldLookup Lookup LookupMulti Lookup Lookup (information already on this site)
Microsoft.SharePoint.SPFieldNumber Number Number Number Number (1, 1.0, 100)
Microsoft.SharePoint.SPFieldRecurrence Recurrence Recurrence Recurrence Recurrence
Microsoft.SharePoint.SPFieldMultiLineText Note Note Multiple lines of text Multiple lines of text
Microsoft.SharePoint.SPFieldText Text Text Single line of text Single line of text
Microsoft.SharePoint.SPFieldUrl URL URL Hyperlink or Picture Hyperlink or Picture
Microsoft.SharePoint.SPFieldUser

Samples:

SPSite site = new SPSite("http://office2007");
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists["Documenten"];
 
    // Add a new text field
    list.Fields.Add("NewTextField", SPFieldType.Text, false);
 
    // Add a new HTML field
    HtmlField htmlField = new HtmlField(
        list.Fields, "HTML", "NewHTMLField");
    list.Fields.Add(htmlField);


Wednesday, July 14, 2010

Internal mechanism of showing indicator of long operations in Sharepoint using SPLongOperation

This is regarding the progress of process that we we usually see into sharepoint like while creating new site or so.
This is very informative blog
http://sadomovalex.blogspot.com/2010/07/internal-mechanism-of-showing-indicator.html

Open SPSite under RunWithElevatedPrivileges in proper zone

This is very good point when we are developing some custom code which is gona be used for a web application that is hosted on multiple zones like Intranet and Internet and so

http://sadomovalex.blogspot.com/2010/01/open-spsite-under-runwithelevatedprivil.html

Tuesday, July 13, 2010

Fire a button click event when user press enter key from textbox

It is very common requirement that when user clicks enter key. a specific submit button event should fire. Sadomovalex has explained it very well in following blog.

http://sadomovalex.blogspot.com/2009/12/post-login-form-without-submit-button.html

Camlex.NET simplifies creating of CAML queries for Windows SharePoint Services by using expression trees

This is very good technique when we need to work on CAML queries.
Contributors have done a great job.
Check this for more info on Camlex.NET
http://camlex.codeplex.com/
Check following link for good examples by Sadomovalex for camlex
http://sadomovalex.blogspot.com/2010/06/build-dynamic-caml-queries-based-on.html

Cross-site and cross-site collection navigation in Sharepoint

This is very good article about, how we can have common navigation for all sites of a site collection or even accross site collections too.
http://sadomovalex.blogspot.com/2010/05/cross-site-and-cross-site-collection.html

Tuesday, July 6, 2010

Disable WebPart form validators when page is in edit mode

There was a issue that my form validators gets fired when we are in Page edit mode or we are updating a webpart.

So we need to disable validators when page in in edit mode.

Solution

On WebPart user control

using Microsoft.SharePoint.WebPartPages;

protected void Page_Load(object sender, EventArgs e)
{
if (SPWebPartManager.GetCurrentWebPartManager(Page).DisplayMode != WebPartManager.BrowseDisplayMode)
validator.Enabled = false;
}

Showing image preview popup using div and javascript

There was a requirement to have a grid with the image thumbnail column and when we clicks that image, it should show the preview for same image in popup. That popup will have close button on right top.

Also if user selects the image as choice from combo the it should show real images if he selects the document then i need to show the one dummy image and on clicking that image it should open or save document.


Step 1:

<asp:GridView
...

<ItemTemplate>

<center>

<div runat="server" id="previewDocument" >

<a href="<%# DataBinder.Eval(Container.DataItem, "ItemUrl")%>" alt="Click to see preview." target="_blank" >

<img id="Img1" class="imgThumbnail" src="/_layouts/images/EgSpi/Default/document.gif" alt="Click to see preview." />

</a>

</div>

<div runat="server" id="previewImage" >

<img id="Img1" class="imgThumbnail" src="<%# DataBinder.Eval(Container.DataItem, "ItemUrl")%>" alt="Click to see preview." onclick="Large(this)" />

</div>

</center>

</ItemTemplate>

</asp:TemplateField>

....
</asp:GridView>

Step 2:



protected void grvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlGenericControl docPreview = (HtmlGenericControl)e.Row.FindControl("previewDocument");
HtmlGenericControl imgPreview = (HtmlGenericControl)e.Row.FindControl("previewImage");

if (ddlObjectType.SelectedItem.Text == Enums.Object_Types.Document.ToString())
{
docPreview.Visible = true;
imgPreview.Visible = false;
}
else
{
docPreview.Visible = false;
imgPreview.Visible = true;
}
}
}

Step 3:

<script language="javascript">
function Large(obj) {
var imgHeight = 240;
var imgWidth = 240;
var imgBoxHeight = 250;

var imgbox = document.getElementById("imgbox");
imgbox.style.visibility = 'visible';

var divImageContainer = document.createElement("div");
divImageContainer.id = "imgContainer";
divImageContainer.innerHTML = '';

var divClose = document.createElement("div");
divClose.id = "imgclose";
divClose.innerHTML = "X";

if (divClose.addEventListener) {
divClose.addEventListener('onclick', Out, false);
} else {
divClose.attachEvent('onclick', Out);
}
imgbox.innerHTML = '';
imgbox.appendChild(divClose);

var img = document.createElement("img");
img.src = obj.src;

if ((img.height > imgHeight) || (img.width > imgWidth)) {
img.style.height = imgHeight + 'px';
img.style.width = imgWidth + 'px';
}
else {
divImageContainer.style.height = (imgBoxHeight - img.height) / 2 + 'px';
imgbox.appendChild(divImageContainer);
}

imgbox.appendChild(img);
imgbox.style.left = (obj.offsetParent.offsetLeft + 70) + 'px';
imgbox.style.top = (obj.offsetParent.offsetTop) + 'px';

}

function Out() {
document.getElementById("imgbox").style.visibility = 'hidden';
}

</script>

Step 4:

#imgbox
{
position: absolute;
border: 1px solid #999;
background: #FFFFFF;
filter: Alpha(Opacity=100);
visibility: hidden;
height: 250px;
width: 250px;
z-index: 50;
overflow: hidden;
text-align: center;
vertical-align:middle;
padding-top:5px;
padding-left:5px;
}

#imgclose
{
position: absolute;
top: 0px;
right: 0px;
background: #858585;
cursor: pointer;
padding: 6px;
font: bold 12px verdana, sans-serif;
color: white;
}

.imgThumbnail
{
border:none;
cursor:hand;
height:14px;
width:14px;
border: 1px solid #999;
padding:1px 1px 1px 1px;
}


----------------------------------- Enjoy ---------------------------------------