Thursday, 31 January 2013

SPWeb.AllProperties and SPWeb.Properties with Sharepoint 2010


SPWeb.Properties is a StringDictionary, and doesn’t support casing for keys/values (everything gets converted to lowercase), while
SPWeb.AllProperties is a Hashtable, and supports a few other datatypes apart from strings (I believe ints and DateTimes are supported)
Instead of working directly with the SPWeb.Properties StringDictionary, SharePoint 2010 now provides four methods to manage properties:
  • SPWeb.GetProperty(Object key)
  • SPWeb.AddProperty(Object key, Object value)
  • SPWeb.SetProperty(Object key, Object value)
  • SPWeb.DeleteProperty(Object key)

Call SPWeb.Update() in order to persist the changes to the underlying database and AllProperties is no different, so don’t forget to do so.

SharePoint Lookup field issue

Client has asked to show hide SharePoint lookup fields those contains more than 20+ items.
On my List New Item page there are two fields which needs to be handled.
The issue coming when hiding one lookup and chaging the filed value of different lookup.
Now when showing hidden lookup, The events are not working also I am not able to select/input any item

Please follow this link to follow the behavior of SharePoint Lookup in descriptive way.

Then I found this  great article, Which chanage the lookup to normal lookup that contains 20+ Items:


<script>
$(document).ready(function () {

// Name of the column (Display Name)
var columnName = "Lookup";

// Override the Drop Down List
OverrideDropDownList(columnName);

// Main Function
function OverrideDropDownList(columnName) {

// Construct a drop down list object
var lookupDDL = new DropDownList(columnName);

// Do this only in complex mode...
if (lookupDDL.Type == "C") {

// Hide the text box and drop down arrow
lookupDDL.Obj.css('display', 'none');
lookupDDL.Obj.next("img").css('display', 'none');

// Construct the simple drop down field with change trigger
var tempDDLName = "tempDDLName_" + columnName;
if (lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").length == 0) {
lookupDDL.Obj.parent().append("<select name='" + tempDDLName + "' id='" + tempDDLName + "' title='" + tempDDLName + "'></select>");

lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").bind("change", function () {
updateOriginalField(columnName, tempDDLName);
});
}

// Get all the options
var splittedChoices = lookupDDL.Obj.attr('choices').split("|");

// get selected value
var hiddenVal = $('input[name=' + lookupDDL.Obj.attr("optHid") + ']').val()
if (hiddenVal == "0") {
hiddenVal = lookupDDL.Obj.attr("value")
}

// Replacing the drop down object with the simple drop down list
lookupDDL = new DropDownList(tempDDLName);

// Populate the drop down list
for (var i = 0; i < splittedChoices.length; i++) {
var optionVal = splittedChoices[i];
i++;
var optionId = splittedChoices[i];

var selected = (optionId == hiddenVal) ? " selected='selected'" : "";
lookupDDL.Obj.append("<option" + selected + " value='" + optionId + "'>" + optionVal + "</option>");
}
}
}

// method to update the original and hidden field.
function updateOriginalField(child, temp) {
var childSelect = new DropDownList(child);
var tempSelect = new DropDownList(temp);

// Set the text box
childSelect.Obj.attr("value", tempSelect.Obj.find("option:selected").val());

// Get Hidden ID
var hiddenId = childSelect.Obj.attr("optHid");

// Update the hidden variable
$('input[name=' + hiddenId + ']').val(tempSelect.Obj.find("option:selected").val());
}

// just to construct a drop down box object. Idea token from SPServces
function DropDownList(colName) {
// Simple - when they are less than 20 items
if ((this.Obj = $("select[Title='" + colName + "']")).html() != null) {
this.Type = "S";
// Compound - when they are more than 20 items
} else if ((this.Obj = $("input[Title='" + colName + "']")).html() != null) {
this.Type = "C";
// Multi-select: This will find the multi-select column control on English and most other languages sites where the Title looks like 'Column Name possible values'
} else if ((this.Obj = $("select[ID$='SelectCandidate'][Title^='" + colName + " ']")).html() != null) {
this.Type = "M";
// Multi-select: This will find the multi-select column control on a Russian site (and perhaps others) where the Title looks like 'Выбранных значений: Column Name'
} else if ((this.Obj = $("select[ID$='SelectCandidate'][Title$=': " + colName + "']")).html() != null) {
this.Type = "M";
} else
this.Type = null;
} // End of function dropdownCtl
});
</script>

Tuesday, 22 January 2013

How To Get Document Icon Image in Sharepoint 2010


string strIcon = SPUtility.ConcatUrls("/_layouts/images/",
SPUtility.MapToIcon(item.Web,
SPPUtility.ConcatUrls(item.Web.Url,item.Url), "", IconSize.Size16));

Tuesday, 15 January 2013

How to Fix lookup columns in SharePoint

I have deployed some list templates and found that Lookups are got broken,
After googling, I found that here, that using PowerShell we can fix the Lookup:

//We can create PowerShell Function as follows:

Function Fix-LookupColumn ($webURL, $listName, $columnName, $lookupListName)
{
    #Get web, list and column objects
    $web = Get-SPWeb $webURL
    $list = $web.Lists[$listName]
    $column = $list.Fields[$columnName]
    $lookupList = $web.Lists[$lookupListName]
 
    #Change schema XML on the lookup column
    $column.SchemaXml = $column.SchemaXml.Replace($column.LookupWebId.ToString(), $web.ID.ToString())
    $column.SchemaXml = $column.SchemaXml.Replace($column.LookupList.ToString(), $lookupList.ID.ToString())
    $column.Update()
 
    #Write confirmation to console and dispose of web object
    write-host "Column" $column.Title "in list" $list.Title "updated to lookup list" $lookupList.Title "in site" $web.Url
    $web.Dispose()
}

By paasing parameters, we can execute the above function

Open SharePoint Powershell command prompt and execute above function
followed by this command to call the function for the particular list and column that you wish to fix:

Fix-LookupColumn -webURL <URL> -listName "<List name containing the lookup column>" -columnName "<Lookup column name>" -lookupListName "<List used by the lookup column>"

For example:

Fix-LookupColumn -webURL http://portal -listName "Vendor" -columnName "Company" -lookupListName "Company"

Where,
List Name :- Vendor
Lookup Column:- Company
Lookup List: Company


Monday, 14 January 2013

Paging ListviewByQuery

protected void Page_Load(object sender, EventArgs e)
        {         
if (!IsPostBack)
            {
                //Yor code
            }
            else
            {

                if (!string.IsNullOrEmpty(this.Context.Request.QueryString["Paged"]))
                {
                    string queryString = string.Empty;
                    foreach (string key in this.Context.Request.QueryString.Keys)
                    {
                        if (key.ToLower() != "view")
                        {
                            queryString += key + "=" + this.Context.Request.QueryString[key] + "&";
                        }
                    }
                    SPUtility.Redirect(this.Context.Request.Url.GetLeftPart(UriPartial.Path), SPRedirectFlags.Default, HttpContext.Current, queryString);
                    return;
                }
            }
}

Its working fine for me

Thursday, 10 January 2013

Configuring the User Profile Service in SharePoint 2010

I have followed this great Link to configure User Profile Service in SharePoint 2010

Wednesday, 9 January 2013

Process ‘SPUCWORKERPROCESS.exe’ is not running

Recently , I tried to create a sand boxed solution for SharePoint 2010 using Visual Studio 2010 have created a ” web part. When I pressed F5 in Visual Studio 2010, I got the following warning message even I have already got Microsoft SharePoint Foundation User Code Service started.

---------------------------
Microsoft Visual Studio
---------------------------
Unable to attach. Process 'SPUCWORKERPROCESS.exe' is not running on 'server'.


Do you want to continue anyway?
---------------------------
Yes No
---------------------------

I have cehecked services.msc and found that "SharePoint 2010 User Code Host(SPUserCodeV4 service)" is running properly.

Then I have checked Central Admin and found that "Microsoft SharePoint Foundation Sandboxed Code Service" under System Settings -> Manages Services on Server
is also started.

After googling,I have found out the Sand boxed solution does not work on DC(Domain controller).If you are using SharePoint on DC, the following Windows PowerShell command would need to be run to enable Sandboxed Solutions. Link

$acl = Get-Acl HKLM:\System\CurrentControlSet\Control\ComputerName
$person = [System.Security.Principal.NTAccount]"Users"
$access = [System.Security.AccessControl.RegistryRights]::FullControl
$inheritance = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [System.Security.AccessControl.PropagationFlags]::None
$type = [System.Security.AccessControl.AccessControlType]::Allow
$rule = New-Object System.Security.AccessControl.RegistryAccessRule($person, $access, $inheritance, $propagation, $type)
$acl.AddAccessRule($rule)
Set-Acl HKLM:\System\CurrentControlSet\Control\ComputerName $acl

view SharePoint 2010 list field version history

In SharePoint 2010 if we want to see the history of multiline text field whose version is enabled (Appending item); We need to follow the below step:

  • Create a multiple lines of text type of field with “Append Changes to Existing Text” option enabled.
  • Go to edit xslt view in SharePoint Designer.
  • By default, when we enabled “Append Changes to Existing Text”, it will display “View Entries…” for the multiple lines field. We will remove the “View Entries…” and replace it with version details of current field.
  • In Design mode, select Xslt list view web part > click Design on the ribbon > Customize XSLT > Customize Entire View.
  • Still in Design mode, select “View Entries…” and type “testtest” directly to replace it with “change”.
  • Switch to code mode, find “change”, and replace it with following code.
  • <SharePoint:AppendOnlyHistory runat="server" FieldName="<Field Display Name>" ItemId="{$thisNode/@ID}" ControlMode="Display" />
  • Done and save the changes.
$thisNode/@ID is very important part here

Using Server Object Model

 SPListItemVersionCollection  objVerisionColl = objItem.Versions;
foreach (SPListItemVersion objVersion in objVerisionColl)
            {
                if (objVersion.IsCurrentVersion)
                {
                    latestComment = objVersion["Comments"].ToString().Trim();
                }

            }

Find a Domain Controller Using Command prompt



    • 1
      Press the "Windows" and "R" keys simultaneously. Type "cmd" (without quotes) in the "Run" window that appears. Press "Enter" to open the "Command Prompt."
    • 2
      Type "net view /domain" (without quotes) to view a list of all the domains on the network into the Command Prompt window, and then press "Enter." Write down the name of the domain that you want to find the domain controller for.
    • 3
      Type "nltest /dsgetdc:domainname" (without quotes) into the "Command Prompt" window, but replace "domainname" with the name of the domain that you want to find the domain controller for. Press "Enter." The name of the domain controller is given to the right of the label "DC:."

Thursday, 3 January 2013

SharePoint Task List email notifications does not work after modification of Items

I had a problem with  SharePoint Task List and the assignTo field for email notifications while modifying the task.
Its not sending any mail neither to assignedTo nor to created By.

After googling, I used the follwing steps:


  1. Confirm that the webapplication of the site collection to which you have imported the site has the correct Outgoing Email Configuration. - Found OK
  2. Run stsadm -o getproperty -url http://site  -pn alerts-enabled
    The expected output is <Property Exist="Yes" Value="yes"/>. 
    If its not Yes then need to enable it with  command: stsadm.exe -o setproperty -pn alerts-enabled -pv "true" -url http://site -Found OK
  3. If everything is there as expected but still emails not working then as Jack mentioned run
    stsadm -o updatealerttemplates -url http://site -f C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\Alerttemplates.xml –LCID 1033
    . - and that was the issue. Now its working fine.
The default timer interval is 5 minutes. Thus, if this interval has not been changed you could notice a delay of up to 5 minutes (the default timer interval) before an alert message is generated. Changes are recorded as they occur in an event log (discussed later in this article) and then alert messages are rendered from that log when the next timer job runs.

         So, I have also checked the default timer interval property of alert using stsadm command:
         stsadm -o getproperty -pn job-immediate-alerts -url http://site
 
        and reset it to 3 min using stsadm command:
       stsadm -o setproperty -pn job-immediate-alerts -url http://site -pv "every 3 minutes"

Wednesday, 2 January 2013

SharePoint Reminder Mail Timer Job Is not Working

I have created SharePoint 2010 Web-scoped timer job and deployed at server. While running the timer job, I found that It is not working and not sending mails.
I then add logs in my code and try to get the issue. While doing this, I found that Log file is showing 0 KB.
Now,What should I do. I then check the main drive space, found that its only 15 MB left.
I cleared my main drive to create some space and wow, without changing a single line of code, its start working. Also now log file is showing its original size.