Saturday, December 29, 2012

The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered.(SharePoint 2010 Powershell error)

Error:- "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered when trying to run SharePoint 2010 PowerShell"

This message would also show up if you try to run the SharePoint 2010 Managment Shell without the proper permissions, or if the account does not have the proper permissions in SQL

OR






the SharePoint 2010 Management Shell was pointing to the incorrect version or path that is invalid and not compatible.
 To Verify which version is being used
1.  Bring up SharePoint 2010 Managment Shell (ignore) the error Message
2.  Type:
$ver=$host | select version
$ver.Version
3.  If you receive something like below.  If the Major version is not on 2, then you will get this runtime error.
Major  Minor  Build  Revision
—–  —–  —–  ——–
3      0      -1     -1
4.  Close out of SharePoint 2010 Managment Shell.
5.  Go back to the SharePoint 2010 Managment Shell Shortcut, right click and select “Properties”
6.  Under the Shortcut tab, Target: section, insert ”-version 2″ into the path, like so.  Make sure its before the -NoExit.
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -version 2 -NoExit ” & ‘ C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1 ‘ “
7.  Click apply, and then Ok
8.  Reopen up the SharePoint 2010 Managment Shell with admin rights, and you should now no longer receive that error, you should then be able to run your scripts.

Tuesday, December 18, 2012

Modify XSLT for discussion board page SharePoint 2010

If you edit Discussion Board page in SharePoint, You can provide link to xsl file to change the look and feel of the page:-




You can refer to default XSL used by this page(thread.xsl)

Path:-

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\XSL

Monday, December 17, 2012

C# Delegate to perform asynchronous method calls


Paste below code in  VS 2010 console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectDelegateAsync
{
    class Program
    {
        public delegate void LongTimeTask_Delegate(string s);
        public delegate void LongTimeTask_Delegate1(string s);
        static void Main(string[] args)
        {
            LongTimeTask_Delegate d = null;
            d = new LongTimeTask_Delegate(LongTimeTask);

            IAsyncResult R = null;
            R = d.BeginInvoke("TestString", null, null); //invoking the method

             LongTimeTask_Delegate1 d1 = null;
             d1 = new LongTimeTask_Delegate1(LongTimeTask1);

             IAsyncResult R1 = null;
             R1 = d1.BeginInvoke("TestString", null, null); //invoking the method

             Console.WriteLine("last line of program");
             Console.ReadLine();
        }
        public static void LongTimeTask(string s)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write(" i:" + i);
            }
        }
        public static void LongTimeTask1(string s)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write(" jj:" + i);
            }
        }
    }
}

Output:-

last line of program
 jj:0 jj:1 i:0 jj:2 jj:3 jj:4 jj:5 jj:6 jj:7 jj:8 jj:9 jj:10 jj:11 jj:12 jj:13 j
j:14 jj:15 jj:16 jj:17 jj:18 jj:19 jj:20 jj:21 jj:22 jj:23 jj:24 jj:25 jj:26 jj:
27 jj:28 jj:29 jj:30 jj:31 jj:32 jj:33 jj:34 jj:35 jj:36 jj:37 i:1 i:2 i:3 i:4 i
:5 i:6 i:7 i:8 i:9 i:10 i:11 i:12 i:13 i:14 i:15 i:16 i:17 i:18 i:19 i:20 i:21 i
:22 i:23 i:24 i:25 i:26 i:27 i:28 i:29 i:30 i:31 i:32 i:33 i:34 i:35 i:36 i:37 i
:38 i:39 i:40 i:41 i:42 i:43 i:44 jj:38 jj:39 jj:40 jj:41 jj:42 jj:43 jj:44 jj:4
5 jj:46 jj:47 jj:48 jj:49 jj:50 jj:51 jj:52 jj:53 jj:54 jj:55 jj:56 jj:57 jj:58
jj:59 jj:60 jj:61 jj:62 jj:63 jj:64 jj:65 jj:66 jj:67 jj:68 jj:69 jj:70 jj:71 jj
:72 jj:73 jj:74 jj:75 jj:76 jj:77 jj:78 jj:79 jj:80 jj:81 jj:82 jj:83 jj:84 jj:8
5 jj:86 jj:87 jj:88 jj:89 jj:90 jj:91 jj:92 jj:93 jj:94 jj:95 jj:96 jj:97 jj:98
jj:99 i:45 i:46 i:47 i:48 i:49 i:50 i:51 i:52 i:53 i:54 i:55 i:56 i:57 i:58 i:59
 i:60 i:61 i:62 i:63 i:64 i:65 i:66 i:67 i:68 i:69 i:70 i:71 i:72 i:73 i:74 i:75
 i:76 i:77 i:78 i:79 i:80 i:81 i:82 i:83 i:84 i:85 i:86 i:87 i:88 i:89 i:90 i:91
 i:92 i:93 i:94 i:95 i:96 i:97 i:98 i:99

Sunday, November 4, 2012

Copy list workflow to other site or list

Disable List Deletion sharepoint 2010

If you don’t want users to be able to delete a specific SharePoint 2010 list, you can disable list deletion using Windows PowerShell. The example below demonstrates how to disable deletion of the tasks list on a Web site:


PS > $spWeb = Get-SPWeb http://SP01.powershell.nu
PS > $spList = $spWeb.Lists["Tasks"]
PS > $spList.AllowDeletion = $false
PS > $spList.Update()
PS > $spWeb.Dispose()

source:-secretsofsharepoint.com

Save site collection as template

/_layouts/savetmpl.aspx

it will create wsp file

Versioning of Visual Studio SharePoint Workflow

This article is copy of
Phil Wicklund'sbook of SharePoint Workflow

Thanks to him for solving biggest problem of Sharepoint State Machine Workflow.



You built this compelling Visual Studio workflow and deployed it into production.
But, after a few months, the business requests a small change to the workflow. You go
back into the workflow code, add a few activities to fulfill the request, and redeploy
the workflow into production. To your shock, all the workflows start breaking! You’re
frantic because you’re certain you adequately unit-tested the changes and can’t figure
out what might be going wrong. You didn’t version your workflow.
Workflow versioning is an important technique. When a workflow goes idle, the
state of the workflow is saved into the database. This saving of a workflow’s state is
called hydration. When the workflow resumes, the state is dehydrated out of the database,
and the workflow starts processing again. Versioning is important because, if you
change the assembly while the workflow is hydrated (saved in the database), there’s
no guarantee that, when the workflow is dehydrated, it will match the construct of the
new assembly. If it doesn’t match the construct upon deserialization, the workflow will
break. Changes like adding or removing activities and changing property values may
necessitate a new workflow version. The best practice is to create a new version every
time rather than deploying the assembly and crossing your fingers.
Think of a new workflow version as a new workflow. The basic technique is to
make your assembly increment the version number with each build (rather than leaving
it at 1.0.0.0 forever). Then, for each upgrade, you create a new feature for that
version of the workflow, pointing to the new assembly. You add the new assembly into
the global assembly cache (GAC) alongside the old assembly. Last, you specify that
the old version cannot start new instances of the workflow and then you add the new
workflow onto the list. This way, the old version of the assembly never changes, so
there’s no risk of hydrated workflows breaking when they are dehydrated. You deploy
another version of the assembly and add the new workflow to the list and disable previous
versions. You don’t want to remove the previous versions because that will
orphan those running instances. For the full set of procedures, follow the steps in
table below to create a new version for an existing workflow.

Saturday, November 3, 2012

Add Custom button to SharePoint ribbon with server side code to execute


To add custom button to ribbon we will need to do below things:-

1.       Create SharePoint Empty Project.

2.       Add new “Empty Element”.

3.        Map Layout folder.

4.       Add One JS file to Layout folder.

5.       Add Application Page to same folder.

6.       Crete 2 logo images


Look at below solution Structure:-


 

Output:-



Custom button will be enabled only when item is selected:-


Code:-




Friday, November 2, 2012

Customize SharePoint Content Editor Web Part in VS 2012 classic webpart

1. Paste below code in cs file of classic web part(Not visual web Part)

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace POC2012CEWP.MyClassicCEWP
{
    [ToolboxItemAttribute(false)]
    public class MyClassicCEWP : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private string _content;
        private HtmlGenericControl editableRegion = new HtmlGenericControl();
        private HtmlGenericControl emptyPanel = new HtmlGenericControl();
        private bool IsInEditMode
        {
            get
            {
                SPWebPartManager currentWebPartManager = (SPWebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);
                return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.IsInEditMode)
            {
                SPRibbon current = SPRibbon.GetCurrent(this.Page);
                if (current != null)
                {
                    current.MakeTabAvailable("Ribbon.EditingTools.CPEditTab");
                    current.MakeTabAvailable("Ribbon.Image.Image");
                    current.MakeTabAvailable("Ribbon.EditingTools.CPInsert");
                    current.MakeTabAvailable("Ribbon.Link.Link");
                    current.MakeTabAvailable("Ribbon.Table.Layout");
                    current.MakeTabAvailable("Ribbon.Table.Design");
                    if (!(this.Page is WikiEditPage))
                    {
                        current.TrimById("Ribbon.EditingTools.CPEditTab.Layout");
                        current.TrimById("Ribbon.EditingTools.CPEditTab.EditAndCheckout");
                    }
                }
            }
        }

Wednesday, October 31, 2012

Sharepoint designer Cannot perform this operation. The file is no longer checked out or has been deleted

"Cannot perform this operation. The file is no longer checked out or has been deleted."
 
 SharePoint Designer is out of sync with SharePoint and you have to delete its cache in order to rebuild it. The cache is composed of these 2 folders:
  • %APPDATA%\Microsoft\Web Server Extensions\Cache
  • %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache

Open the folders and delete all cache data


You can try saving below code in .bat file and running it


cd "%APPDATA%\Microsoft\Web Server Extensions\Cache"
del *.web /S /Q "%APPDATA%\Microsoft\Web Server Extensions\Cache"
cd "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\"
rmdir /S /Q "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\."
mkdir "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache"
dir "%APPDATA%\Microsoft\Web Server Extensions\Cache"
dir "%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache"
pause


 

Sunday, October 28, 2012

Enable/Disable Developer Dashboard Powershell command SharePoint 2010

Type below commands in Powershell

$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On
$addsetting.Update()


Make it OnDemand


$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::OnDemand
$addsetting.Update()


Turn Off

$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off
$addsetting.Update()

Tuesday, September 25, 2012

Write to workflow history list state machine workflow sharepoint 2010 C# code

void WriteToHistoryList(string comment, string outcome)
        {
            SPWorkflow.CreateHistoryEvent(workflowProperties.Web, this.WorkflowInstanceId, 0, workflowProperties.Web.CurrentUser, new TimeSpan(), outcome, comment, "");
        }

Wednesday, September 12, 2012

Make Column Read Only Sharepoint 2010

PS C:\Users\gadekasa> $spWeb = Get-SPWeb http://abc:5552/sites/AirCraft/
PS C:\Users\gadekasa> $spList = $spWeb.Lists["AllWorkflowDefaultList"]
PS C:\Users\gadekasa> $fields =$spList.Fields["Role"]
PS C:\Users\gadekasa> $fields.ReadOnlyField = $false
PS C:\Users\gadekasa> $fields.update($true)
PS C:\Users\gadekasa> $spList.Update()
PS C:\Users\gadekasa> $spWeb.Dispose()

Saturday, August 25, 2012

Adding Custom CSS style in Markup drop down of Sharepoint 2010 HTML editor ribbon




1. Create one css file in 14 hive(you can add it in your visual studio solution by adding layouts mapped folder)

2. add below css class in that file 

/* custom style in */
DIV.ms-rteElement-mkg-H1
{
-ms-name: "marketing-header";
color: #d65c26;
font-family: Verdana,Geneva,sans-serif;
font-weight: normal;
font-size: 2em;
}

Saturday, August 11, 2012

WCF with sharepoint 2010 service

Try below code, it works perfectly fine:-

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using Microsoft.SharePoint.Linq;
using WCFService.ListWCFService;
namespace WCFService.WP_WCFService
{
    public partial class WP_WCFServiceUserControl : UserControl
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                System.Uri uri = new Uri("http://localhost:16178/_vti_bin/ListData.svc");
               SrgDataContext dc = new SrgDataContext(uri);
               dc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    var query = from dev in dc.Announcements
                                select new
                                {
                                    Title = dev.Title,
                                    Body = dev.Body,
                                    ExpiryDate = dev.Expires,
                                    Path = dev.Path
                                };
                    gridAnnouncementList.DataSource = query;
                    gridAnnouncementList.DataBind();
             
                //dc.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
           

Using Sharepoint rich text box in Web Part

Just add below line in sharepoint project visual web part ascx file:-
<SharePoint:InputFormTextBox runat="server" ID="txtBody" TextMode="MultiLine" ValidationGroup="CreateCase" Rows="8" Columns="40" RichText="true" RichTextMode="FullHtml" AllowHyperlink="true" />

Saturday, June 23, 2012

On Enter Button click redirect with querystring as textbox value


put your text box and button in panel with default button

<asp:Panel  DefaultButton="Button1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </asp:Panel >





OR





<script>

     function button_click(objTextBox, objBtnID) {
         if (window.event.keyCode == 13) {
             if (objTextBox.value != "") {
                 document.getElementById(objBtnID).focus();
                 document.getElementById(objBtnID).click();
             }
            
         }
      }
    </script>



<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />




Page load:-
this.TextBox1.Attributes.Add("onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");


protected void Button1_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(TextBox1.Text))
        {
            Response.Redirect("Default2.aspx?text=" + TextBox1.Text);
        }
    }

Wednesday, June 20, 2012

Logging error to text file c#.Net

1. Add new static "ErrorLoging" class to solution and paste the below code in cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;

/// <summary>
/// class contain methode for logging WriteToErrorLogFile_Trace(string)
/// </summary>
public  static class ErrorLoging
{
    /// <summary>
    /// log error to path metion in web.config file for key "ErrorFolderPath".
    /// new file will be created for each day
    /// </summary>
    /// <param name="msg">error msg to log.</param>
    /// <param name="ex">exception object, Pass null to just log some msg.</param>
    public static void WriteToErrorLogFile_Trace(string msg,Exception ex)
    {
        try
        {
            if (!System.IO.Directory.Exists(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\"))
            {
                System.IO.Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\");
            }
            //if (!System.IO.File.Exists(Application.StartupPath + "\\Errors\\" + DateTime.Today.Date.ToString().Replace('/', ' ').Replace(':', ' ')+".txt"))
            //{
            //    System.IO.File.Create(Application.StartupPath + "\\Errors\\" + DateTime.Today.Date.ToString().Replace('/', ' ').Replace(':', ' ') + ".txt");
            //}



            FileStream fs1 = new FileStream(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\" + DateTime.Today.Year.ToString() + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd") + ".txt", FileMode.Append, FileAccess.Write);
            StreamWriter s1 = new StreamWriter(fs1);


Friday, May 18, 2012

getting querystring from string

I was having a URL as string
e.g. string videoURL="http://www.youtube.com/watch?v=Rz-Lejndrys";

So now if I wanted to get the value of querstring v. We can get sub-string of videoURL or there is one more method to fetch value of v from above string.

 Uri videoPrevUri = new Uri(videoURL);
 string videoID = HttpUtility.ParseQueryString(videoPrevUri.Query).Get("v");

videoID will return you the value of v

Monday, March 12, 2012

Regular expression for special character in C#

Regex reg = new Regex("[~#%&;*{}\\:<>?/\"|$]+");
 if (reg.IsMatch(TxtBox.Text.Trim()))
{
//Error Msg
}

getting only file name from fileupload control and checking for special character in file name :-JQuery

function ValidateThumbnail() {
//get file name
        var path = $("[id$=fileUploadControl]").val();
        var pos = path.lastIndexOf(path.charAt(path.indexOf(":") + 1));
      
        var f = path.substring(pos + 1);
       //check for special char
        if ((f.indexOf("#", 0) >= 0)
        || (f.indexOf("&", 0) >= 0)
        || (f.indexOf("*", 0) >= 0)
        || (f.indexOf(";", 0) >= 0)
        || (f.indexOf("$", 0) >= 0)
        || (f.indexOf("%", 0) >= 0)
        || (f.indexOf("^", 0) >= 0)
        || (f.indexOf("{", 0) >= 0)
        || (f.indexOf("}", 0) >= 0)
        || (f.indexOf("|", 0) >= 0)
        || (f.indexOf("/", 0) >= 0)
        || (f.indexOf("?", 0) >= 0)
        || (f.indexOf("~", 0) >= 0)
        || (f.indexOf(":", 0) >= 0)
        || (f.indexOf("<", 0) >= 0)
        || (f.indexOf(">", 0) >= 0)
        || (f.indexOf("\"", 0) >= 0)
        ) {
            alert("File: [" + f + "] contains invalid character");
            return false; //will stop button click event here
        }
        return true;
    }

JQuery POP UP during page load /Post back

give call to below fuction on client click

function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = '/_layouts/Portal/Images/ajax-loader-1.gif';
        div.innerHTML = "Please wait...<br />";
        div.style.cssText = 'position: fixed; top: 30%; left: 40%; z-index: 5000; width: 222px; text-align: center; background: #fff; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
       
    }

TaxonomyWebTaggingControl in UpdatePanel with AJAX

When asyncronuous postback will happen it will not load the TaxonomyWebTaggingControl because DOM gets null.
Use below methode to load TaxonomyWebTaggingControl  after asyn postback.

private string GetReloadJavaScript(TaxonomyWebTaggingControl taxonomyControl)
        {
            String script = String.Empty;
          
            String containerId = SPEncode.ScriptEncode(taxonomyControl.Controls[1].ClientID);
            Type type_TaxonomyWebTaggingControl = typeof(TaxonomyWebTaggingControl);
            MethodInfo mi_getOnloadJavascript = type_TaxonomyWebTaggingControl.GetMethod("getOnloadJavascript", BindingFlags.NonPublic | BindingFlags.Instance);
            String fullScript = (String)mi_getOnloadJavascript.Invoke(taxonomyControl, null);
            int pos = fullScript.IndexOf(String.Format("function {0}_load()", containerId));
            if (pos > -1)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("var myPrm_" + taxonomyControl.ID + " = Sys.WebForms.PageRequestManager.getInstance();");
                builder.Append("myPrm_" + taxonomyControl.ID + ".add_endRequest(EndRequest_" + taxonomyControl.ID + ");");
                builder.Append("function EndRequest_" + taxonomyControl.ID + "(sender, args)");
                builder.Append("{");
                // we get te first part of the script needed to initialization
                // we start from pos 1, because we don't need the leading '{'
                builder.Append(fullScript.Substring(1, pos - 1));
                builder.Append("Microsoft.SharePoint.Taxonomy.ScriptForWebTaggingUI.onLoad('");
                builder.Append(containerId);
                builder.Append("');");
                builder.Append("}}");
                script = builder.ToString();
            }
            return script;
        }



How to call above methode

String key1 = "TaxonomyWebTaggingAjaxIncludeOnce1";
                if (!this.Page.ClientScript.IsClientScriptBlockRegistered(base.GetType(), key1))
                {
                    this.Page.ClientScript.RegisterClientScriptBlock(base.GetType(), key1, GetReloadJavaScript(taxanomyProjectCategory_taxonomyControl), true);

                }

give multiple call to methode for all taxonomy controls on page.

Friday, January 27, 2012

Remove user from Sharepoint group using powershell


PS C:\Users\ADM> $spWeb = Get-SPWeb http://abc/
PS C:\Users\ADM> $group=$spWeb.SiteGroups["Legal Approvers"]
PS C:\Users\ADM> $group.Users
PS C:\Users\ADM> $theuser = $spWeb.AllUsers.Item("SHAREPOINT\system")
PS C:\Users\ADM> $group.RemoveUser($theuser)
PS C:\Users\ADM> $group.Update()
PS C:\Users\ADM> $group.Users

SharePoint document metadata not updating

I faced a weird issue today, Metadata for document which has lookup column was not updating even after saving the item. There was no erro...