Wednesday, December 17, 2014

Column Validation in SharePoint 2010

The ability to easily validate the column values entered into list items is a welcome addition to SharePoint 2010.I’d like to walk thru 2 simple example s of how to use column validation, at the column level, then at the list level.I’ll then point out some specific notes about this feature.
Simple Example #1 – Column Level
  1. Create a new column on a list, and click "Column Validation":
  1. Add a validation Formula, and a message that will display if validation fails:
  1. Create a new item, and enter a value that will not validate.Click OK.You will see your failure message:
Simple Example #2 – List Level
  1. In the List Settings, click on "Validation Settings"
  1. Enter a validation formula to apply to this list.Click Save.
  1. Create a new list item, entering in values that will not validate.Click OK.The item does not save, but the User Message doesn’t appear either.I assume this is a bug, and it ought to be fixed before RTM.
Field Types
In this simple example we used a "Single Line of Text" field type.The following field types can be validated with the "Column Validation" feature:
  • Single Line of Text
  • Choice (single only)
  • Number
  • Currency
  • Date & Time
Formulas
  1. You can only compare column values to one another in a list level validation.
  2. A validation formula at the column level cannot include any other columns besides itself.For example, [Column1]>[Column2] is an invalid formula and SharePoint will not allow it to be used at the column level.In this case, you want to use list-level validation.
  3. There is only one formula available at the list level.
  4. The formula syntax is similar to that used in Calculated Columns
There are a few dozen functions available – I have not tried every one.One interesting thing to note is that SharePoint 2010 would not allow me to use the TODAY function, even when validating a Date field.[DateColumn]>TODAY is not a valid validation formula.
Conflicts
  1. What if you have both column level validation and list level validation?
    1. The column level formulas will be evaluated first, then the list formulas
  1. What if the column and list level validations are in conflict?
    1. Example – at the list level, you require that [Text1] = [Text2], but each column has it’s own validation; [Text1]="AAA", and [Text2]="BBB".In this case, it will be impossible to actually submit a list item.The column validations are evaluated first, but if the values validate here, they will of course fail the list validation.
  1. What if the list level validation includes columns not included in a particular content type?
    1. If a column used in the list formula isn’t available in the current content type, validation will always fail.This means that if you have multiple content types in your list,you should not validate at the list level for a column that is not included in all content types on the list.These columns can only be validated at the column level.
Site Columns
  1. You can set validation on custom columns of the field types listed above
  2. You can override the validation of a site column at the list level
Items To Investigate
  1. How does validation behave with page fields in a Pages library on a publishing site?
  2. How does validation behave in Office client applications?
  3. Is validation available in the Site Directory?Does it work at site creation time?
  4. Can we use regular expressions in a validation formula?

Reference:
http://blogs.perficient.com/microsoft/2009/09/column-validation-in-sharepoint-2010/
 

Wednesday, December 10, 2014

Adding Target audience to sharepoint left navigation programatically

SPNavigationNodeCollection nodeColl = newSite.Navigation.QuickLaunch;
 
                                            SPGroupCollection groups = newSite.Groups;
                                            string groupnamesString = ";;;;";
                                            foreach (SPGroup group in groups)
                                            {
                                                if (group.Name.Contains("Owner") || group.Name.Contains("Member"))
                                                    groupnamesString += group.Name + ",";
                                            }
 
                                            //groupnamesString = groupnamesString.Substring(0, groupnamesString.Length - 1);
                                            //node.Properties.Add("Audience",  ";;;;" + Group1+","+ Group2 +","+ Group3+","+etc... "" );
                                            Console.WriteLine(groupnamesString);
 
                                            if (!string.IsNullOrEmpty(groupnamesString))
                                            {
                                                foreach (SPNavigationNode node in nodeColl)
                                                {
                                                    if (node.IsExternal == true && node.Title != "General")
                                                    {
                                                        if (node.Properties.ContainsKey("Audience"))
                                                        {
                                                            node.Properties["Audience"] = groupnamesString;
                                                        }
                                                        else
                                                        {
                                                            node.Properties.Add("Audience", groupnamesString);
                                                        }
                                                        node.Update();
                                                    }
                                                }
                                                newSite.Update();
                                            }

Assign broken permissions to publishing pages through programtically

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(newSite);
                                            PublishingPageCollection allPages = publishingWeb.GetPublishingPages();
 
                                            foreach (PublishingPage page in allPages)
                                            {
                                                Console.WriteLine(page.Name);
 
                                                if (page.Name.ToLower() == "about us.aspx" || page.Name.ToLower() == "people.aspx" || page.Name.ToLower() == "services.aspx")
                                                {
                                                    #region checkout and assign the permissions to intranet_readers
 
                                                    // checkout the page
                                                    if (page.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                                                    {
                                                        page.CheckOut();
                                                    }
                                                    else
                                                    {
                                                        page.ListItem.File.UndoCheckOut();
                                                        page.CheckOut();
                                                    }
 
                                                    // Break the permissions
                                                    page.ListItem.BreakRoleInheritance(true);
 
                                                    // Rename the page
                                                    //page.ListItem["Name"] = "About us";
 
                                                    // Assign the permissions to intranet_readers
                                                    SPRoleAssignment roleAssignment = new SPRoleAssignment(newSite.SiteGroups["readersgroup"]);
                                                    if (roleAssignment != null)
                                                    {
                                                        roleAssignment.RoleDefinitionBindings.Add(newSite.RoleDefinitions["Read"]);
                                                        page.ListItem.RoleAssignments.Add(roleAssignment);
                                                        page.ListItem.Update();
                                                    }
                                                    // CheckIn the page
                                                    page.CheckIn("Broken permissions added");
                                                    // publish the page
                                                    SPModerationInformation moderationInformation = page.ListItem.ModerationInformation;
 
                                                    if (moderationInformation != null && moderationInformation.Status != SPModerationStatusType.Approved)
                                                    {
                                                        SPFile pageFile = page.ListItem.File;
                                                        pageFile.Publish("publish comments");
                                                        pageFile.Approve("approve comments");
                                                    }
 
                                                    #endregion
                                                }
 
                                            }

Passing Eval text to javascript function

OnClientClick='<%# String.Format("javascript:openVendorDetailsForm(\"{0}\")", Eval("Title").ToString()) %>'

Wednesday, November 26, 2014

Customize My Profile Tabs for SharePoint 2010

If you have a requirement to add, edit, or delete the tabs within the my profile pages its actually quite easy. The default tabs are:
  • Overview
    • URL: /my/person.aspx
  • Organization
    • URL: /my/OrganizationView.aspx
  • Content
    • URL: /my/personcontent.aspx
  • Tags and Notes
    • URL: /my/_layouts/thoughts.aspx
  • Colleagues
    • URL: /my/_layouts/MyContactLinks.aspx
  • Memberships
    • /my/_layouts/MyMemberships.aspx
image
You can manage these tabs by navigating to the My Site Host http://sitename/my/ or the the my profile page http://sitename/my/Person.aspx.
Click on Site Actions > Site Settings > Look and Feel > Quick Launch
image
You will notice that all of the tabs are managed as quick launch links. This will allow you to easily add, edit, and delete tabs.
If you want to customize the look of the tabs to be vertical or place it somewhere else on the page you simply have to modify the person.aspx page within the My Site host Site collection.
Open up the site (http://sitename/my/) in SharePoint Designer 2010, and click on All Files.
image
Notice that 3 out of the 6 .aspx files are managed in SharePoint and the other three are stored on the server in the following location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS
Check out the person.aspx file and edit in advanced mode.
The tabs on the profile page are actually a SharePoint:AspMenu menu control. Which has a horizontal orientation and a unique “s4-sn” css class to give it its unique look and feel.
<SharePoint:AspMenu
ID="MySiteSubNavigationMenu"
Runat="server"
EnableViewState="false"
DataSourceID="MySiteSubNavDS"
AccessKey="<%$Resources:wss,navigation_accesskey%>"
UseSimpleRendering="true"
UseSeparateCss="false"
Orientation="Horizontal" StaticDisplayLevels="1"
MaximumDynamicDisplayLevels="0"
PopOutImageUrl=""
SkipLinkText=""
CssClass="s4-sn"> </SharePoint:AspMenu>
<SPSWC:MySiteDataSource
ShowStartingNode="False"
SiteMapProvider="MySiteSubNavProvider" id="MySiteSubNavDS"
runat="server"/>
This control is placed on all 6 of the aspx pages to give the effect that a user is simply changing the content on the page by clicking on a different tab and not actually going to a different page.
The key is to keep that consistency throughout your custom profile pages so that the user does not get confused when navigating the tabs.


Reference:
http://erikswenson.blogspot.sg/2010/11/customize-my-profile-tabs-for.html
http://mikeoryszak.com/2011/09/user-profiles-adding-a-custom-tab-and-page/
 

Sunday, November 23, 2014

Embedding YouTube Video in a SharePoint 2010 List

Workaround using jquery:

1) add this tag to the SP field

<div class="myCompany_iframe" style="visibility: hidden">width="560" height="315" src="//www.youtube.com/embed/Basc-0edkhw?list=sasd" frameborder="0" allowfullscreen</div>


2) Add this script to the page/master page
<script type="text/javascript">
$(document).ready(function() {

$( ".myCompany_iframe" ).each(function() {
$(this).html("<iframe " +  $(this).html() + "></iframe>").css("visibility","visible");
});

});</script>
 
 
 
Reference URL:
 
 
 

Thursday, November 20, 2014

SharePoint: Redirecting to a page after adding a New item to a list

SharePoint: Redirecting to a page after adding a New item to a list

There are times when you want a user to add an item to a list without displaying the list, either before or after they fill out the “New Item” form.
 
To get them to the form is easy. Go to the list, click the New button and note the URL. Copy the URL and paste it as a link in Quick Launch, an Announcement, a links list or a Content Editor Web Part.

When the user clicks your link they will go directly to the New item page. But… when they click OK they will go to the list, not back to your page.
 

The fix is easy...        Add “source=” to the end of the link.

1) Go to the list and click the new button. You will see a URL like:
http://www.yourserver.com/sites/sales/Lists/Tasks/NewForm.aspx?RootFolder=%2FLists%2FTasks&Source=http%3A%2F%2Fwww.yourserver.com%2Fsites%2Fsales%2FLists%2FTasks%2FAllItems%2Easpx

2) copy the URL and change the part after Source= to the desired destination. The following will send them back to your home page:
http://www.yourserver.com/sites/sales/Lists/Tasks/NewForm.aspx?RootFolder=%2FLists%2FTasks&Source=http%3A%2F%2Fwww.yourserver.com%2Fsites%2Fsales

Absolute or Relative?
Best practice would be to use a relative URL (no HTTP or server name) so your site will work when you have internet and intranet access to the same site. Something like "Source=/sites/sales/" or "Source=/sites/sales/mycustompage.aspx".
To return to the home page add this URL as a link in your Announcement, a links list or a Content Editor Web Part:
Absolute:
http://www.yourserver.com/sites/sales/Lists/Tasks/NewForm.aspx?RootFolder=%2FLists%2FTasks&Source=http%3A%2F%2Fwww.yourserver.com%2Fsites%2Fsales
Relative:
/sites/sales/Lists/Tasks/NewForm.aspx?RootFolder=%2FLists%2FTasks&Source=%2Fsites%2Fsales

In the examples above I did not always escape the slashes:  /  =  %2F
Any slash after the "?" should be escaped.


Redirect the Cancel Button
One of the questions below notes that the redirect steps above redirect both the OK and the Cancel button to the “Source” URL.  Here’s is a quick pass at adding a “CancelDestination” parameter to the query string to set the destination for the cancel button.
Steps:
Go the “New Item” page
Edit the URL and add “&ToolPaneView=2” to the end of the URL to put the page in edit mode
 
http://yourserver/sites/sales/Lists/Announcements/NewForm.aspx?RootFolder=%2fsites%2fsales%2fLists%2fAnnouncements&Source=http%3a%2f%2fyourserver%2fsales%2fyoursite&ToolPaneView=2
 
Click “Add a Web Part” and add a Content Editor Web Part (CEWP)
Move the CEWP below the existing list web part
Edit the CEWP and click the Source Editor button
Paste the JavaScript from below
Save your changes and exit the edit mode of the page
Create a URL similar to the one earlier in the article, but add a new parameter named “&CancelDestination=http://yourcanceldestination"
 
http://www.yourserver.com/sites/sales/Lists/Tasks/NewForm.aspx?RootFolder=%2FLists%2FTasks&Source=http%3A%2F%2Fwww.yourserver.com%2Fsites%2Fsales&CancelDestination=http%3A%2F%2Fwww.yourserver.com%2Fsites%2Fsales%2FCancelPage.aspx
 
Test!

The JavaScript:
<script>
var querystring = window.location.search.substring(1); 
var parameters = querystring.split("&");
var QueryString = Array();
for (var i=0;i<parameters.length;i++)
{
  QueryString[parameters[i].split("=")[0]] = parameters[i].split("=")[1];
}
if (QueryString["CancelDestination"] != undefined)
{
  var inputs = document.getElementsByTagName("INPUT");
  for (var i=0; i<inputs.length; i++)
  {
    if (inputs[i].value == "Cancel")
    {
      inputs[i].onclick =       function () {document.location.href = unescape(QueryString["CancelDestination"])};
    }
  }
}
</script>

Reference:
http://techtrainingnotes.blogspot.sg/2009/06/sharepoint-redirecting-to-page-after.html
 

Monday, November 3, 2014

Configure People Picker for Multi-Domains(or Cross Domains), Forests Environments

Configure People Picker for Multi-Domains(or Cross Domains), Forests Environments

By default, the people picker will issue queries to all two-way trusted domains and two-way trusted forests to search people & groups. It uses the application pool account to search the target domains and forests.
Configure People Picker for Multi-Domains, Multi Forest

If the application pool account does not have permission to the target domains or forests, or if you want to use different account to search the target domains or forests, you can use the below steps:

If the AD domain has a 1-way trust, then you need to specify a username and password, execute the following commands on every server in the farm:
stsadm –o setapppassword –password MyPassword
ensure you use the same password for each server you execute this command on!

On every WFE in the farm execute the following command to instruct the people-picker to use the corret AD domain:
stsadm -o setproperty -pn peoplepicker-searchadforests -pv domain:YourDomain.com,domain\user,password –url relevant web application
you need to run this for each web application, if you do not run this on the WFE you will see a “callback error” in the people-picker

Note: you can specify mulitple domains to lookup as well, just encapsulate the domain names in quotation marks and seperate them with a semi-colon (-pv "YourDomain1.com;YourDomain2.com”,domain\username,password)

If the AD domain has a 2-way trust you do not need to run the stsadm –o setapppassword command, just execute this one:
stsadm -o setproperty -pn peoplepicker-searchadforests -pv domain:YourDomain.com,domain\user,password –url relevant web application
you need to run this for each web application, if you do not run this on the WFE you will see a “callback error” in the people-picker

If you need to reset the people-picker back to normal, just execute this command:
stsadm -o setproperty -pn peoplepicker-searchadforests –pv (don’t specify anything here) –url relevant web application
you need to run this for each web application, if you do not run this on the WFE you will see a “callback error” in the people-picker

In case of Cross forests:
stsadm.exe -o setproperty -url <URL> -pn "peoplepicker-searchadforests" -pv "forest:forest.corporate.com (forest:DnsName) ;domain:na.corporate.com", LoginName, P@ssword
Don't forget to do the IISReset!

More Info:
MOSS 2007: http://technet.microsoft.com/en-us/library/cc263318%28office.12%29.aspx
SharePoint 2010: http://technet.microsoft.com/en-us/library/gg602066.aspx#section4
http://technet.microsoft.com/en-us/library/gg602075.aspx
http://blogs.msdn.com/b/joelo/archive/2007/01/18/multi-forest-cross-forest-people-picker-peoplepicker-searchadcustomquery.aspx


Limit the People Picker in SharePoint 2010 to a Specific OU or Domain
Say, There are two Site Collections: Sales and Legal. Active Directory is setup to store Sales department users in the Sales Organizational Unit and Legal department users in the Legal Organizational Unit. The requirement is to prevent Sales users from adding site/library/item permissions for Legal users, and vice versa.

So here is the solution:
Run the following PowerShell commands
Set-SPSite -Identity http://portal/sites/sales -UserAccountDirectoryPath "OU=sales,OU=SharePoint,DC=MYCOMPANY,DC=com"Set-SPSite -Identity http://portal.contoso.com/sites/legal -UserAccountDirectoryPath "OU=Legal,OU=SharePoint,DC=MYCOMPANY,DC=com"

Here is a related post: http://sharepointserver-2007.blogspot.com/2008/10/limiting-sharepoint-people-picker.html


Read more: http://www.sharepointdiary.com/2011/06/configure-people-picker-for-multidomain-forest.html#ixzz3I4o7Ohf5

Monday, October 13, 2014

Implement-check-all-checkbox-functionality-in-ASPNet-GridView-control-using-JavaScript

http://www.aspsnippets.com/Articles/Implement-check-all-checkbox-functionality-in-ASPNet-GridView-control-using-JavaScript.aspx

http://www.aspsnippets.com/Articles/Delete-multiple-rows-in-GridView-with-CheckBox-selection-and-with-confirmation-in-ASPNet.aspx


Sunday, September 21, 2014

Javascript alert from cs page

var message = "<script type=text/javascript>alert('At least 1 image is required');</script>";
                    System.Web.UI.ClientScriptManager clientScriptManager = Page.ClientScript;
                    clientScriptManager.RegisterStartupScript(this.GetType(), "Message", message);

Monday, August 18, 2014

Get all users from the sharepoint group


public static string GetAllGroupUsers(string GroupName)
        {
            string userList = string.Empty;

            SPSite spSite = new SPSite(SPContext.Current.Site.ID);
            using (SPWeb spWeb = spSite.RootWeb)
            {
                try
                {
                    SPGroup spGroup = spWeb.SiteGroups[GroupName];
                    if (spGroup != null)
                    {
                        foreach (SPUser spUser in spGroup.Users)
                        {
                            userList += spUser.Email + ";";
                        }
                    }
                }
                catch (Exception ex)
                {
                   
                }
            }
            return userList;
        }

Wednesday, August 13, 2014

Copy Users from One SharePoint Group to Another using PowerShell

Recently, I had a requirement to copy users from one SharePoint group to another group. Unfortunately, SharePoint doesn't support nested groups. Simply renaming the group didn't help us! Well, There is no direct way to copy users from one group to another, but without having to retype each user IDs, you can use this trick to save time in copy-move SharePoint users: 
  • Go to Site Actions >> Site Settings
  • Click on "People and Groups" under Users and Permissions group
  • Pick required users from the source group. Click on "E-mail Users" from "Actions" menu.
  • This launches the default E-mail client such as Outlook. Now you can copy those IDs.
  • Head-on to the Target SharePoint group >> Add users and paste those copied IDs.
The above method could be relatively simpler when you have to copy or move few users between SharePoint groups. Wouldn't it be better to use the scripted way to copy multiple users in bulk?

PowerShell Script to Copy/Move Users from One SharePoint Group to Another :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Input variables
$SourceGroupName="Operations Members"
$TargetGroupName="Operations Owners"
 
#Get the Web
$web = Get-SPWeb $WebURL
 
#Get the Source and Target Groups
$SourceGroup = $web.groups | where {$_.name -eq $SourceGroupName }
$TargetGroup = $web.groups | where {$_.name -eq $TargetGroupName }
 
#Iterate through each users in the source group
foreach ($user in $SourceGroup.users)
{
   $TargetGroup.AddUser($user)
    Write-Host "Copied $user from $SourceGroup to $TargetGroup"
    #To move users, Just remove them from source group
    #$SourceGroup.RemoveUser($user)
}

Copy users from one SharePoint site collection to another using PowerShell:
The above script copies users between SharePoint groups of the same site. Can we copy users between groups in different site collections? Why not? Lets change the above script slightly to copy users from one SharePoint site group to another.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Input variables
$SourceGroupName="Operations Members"
$TargetGroupName="Marketing Members"
 
#Get the Webs
$SourceWeb = Get-SPWeb $SourceWebURL
$TargetWebURL= Get-SPWeb $TargetWebURL
 
#Get the Source and Target Groups
$SourceGroup = $SourceWeb.groups | where {$_.name -eq $SourceGroupName }
$TargetGroup = $TargetWebURL.groups | where {$_.name -eq $TargetGroupName }
 
#Iterate through each users in the source group
foreach ($user in $SourceGroup.users)
{
   $TargetGroup.AddUser($user)
    Write-Host "Copied $user from $SourceGroup to $TargetGroup"
    #To move users, Just remove them from source group
    #$SourceGroup.RemoveUser($user)
}


Reference:
http://www.sharepointdiary.com/2014/04/copy-users-from-one-sharepoint-group-to-another-using-powershell.html

Image noise comparison methods

 1. using reference image technique     - peak_signal_noise_ratio (PSNR)     - SSI 2. non-reference image technique     - BRISQUE python pac...