Friday, April 14, 2017

Get all web applications, site collections and sites in a farm using powershell

You can get all web application and site collection in each web application and sub sites in each site collection in a SharePoint farm using the below powershell code

$webApp = Get-SPWebApplication
write-host $webApp
foreach ($webApps in $webApp)
{
write-host “WEBAPPLICATION :” $webApps.Name
foreach ($site in $webApps.Sites)
{


write-host “SITE: ” $site.URL
foreach($wb in $site.webs)
{
write-host "web: ” $wb.URL
}

}
}

save this as .ps1 extension and run the SharePoint management shell with administrator privilege and open the .ps1 file saved and you will get  list of web applications name and site collection in it and sub sites in that site collection one by one.

Happy Coding !!!

Friday, March 3, 2017

Get all sub sites in a site using rest api in SharePoint

You can get all sub sites in a site using rest api in SharePoint.

Here is the URL to get all sub sites

http://yoursite/_api/Web/webinfos

This will give you the properties of sub site like :-

  • Title
  • Description
  • Web template used for the site (e.g. Team site, project site etc) 
  • Server relative url 
  • Date of creation etc in json format



Happy Coding !!!


Monday, February 20, 2017

Reference error:GetCtxRgiidFromlid is not defined

Recently i encountered a weird issue in SharePoint 2013, when i click on any document library context menu it shows "Reference error:GetCtxRgiidFromlid is not defined" as shown below



After lot of googling and some hit and trial methods, i figured out that this issue is related to the sequence of SharePoint js files in my custom master page.

I used sp.init.js and sp.runtime.js  and gave the reference as
 <script src="/_layouts/15/sp.init.js"></script>
<script src="/_layouts/15/sp.runtime.js"></script>

I gave theses reference because i need to execute some functions (SharePoint jsom api) and these files were required.

But this lead to the reference error so i modified the custom master page and given the links as

<!--MS:<SharePoint:ScriptLink language="javascript" name="sp.runtime.js" OnDemand="true" runat="server" Localizable="false">-->
        <!--ME:</SharePoint:ScriptLink>-->
        <!--MS:<SharePoint:ScriptLink language="javascript" name="sp.init.js" OnDemand="true" runat="server" Localizable="false">-->

First sp.runtme.js is to be loaded then sp.init.js after doing these changes above error was gone.

Happy Coding !!


Thursday, February 16, 2017

Use CK editor in SharePoint default forms

The SharePoint multi column field has some issues as it does not render properly except in internet explorer.

Here i am going to explain you today how you can use third party text editor to use in SharePoint default forms (newform.aspx/editform.aspx). I used ck editor here.

This editor supports multiple editing options and moreover it renders properly in all the browsers.

First i created a columns named "FullHTMLColumn" multiple line of text and choose plain text from
Specify the type of text to allow option 

This columns will store the html content in multiple line of text form

Now you have to place the ck editor files in document library or you can give live links, here i have placed all the editor files in style library and given the reference.
Don't forget to give the jQuery reference, in my case i have given the reference in master page.

Then open the list's newform.aspx and find the PlaceHolderMain and placed the below script in that

<script src="../../Style Library/ckeditor/ckeditor.js"></script>
<script>
var FullHTMLColumn="";


$(document).ready(function(){
FullHTMLColumn=$("[title='FullHTMLColumn']").attr('id');



CKEDITOR.replace(FullHTMLColumn);

});
 function PreSaveAction() { 

$("[title='FullHTMLColumn']").val("<DIV>"+CKEDITOR.instances[FullHTMLColumn].getData()+"</DIV>");


  return true;
  }

</script>

Now open the newform.aspx from browser you will see all the editor options are present on the above column as shown below.

Now you can perform all the text editing option here and save the data in to list.
Use the same script on editform.aspx to show same editor options on that form also



















Now on allitems.aspx and viewform.aspx place the below script under placeholdermain content placeholder.

This script will render the html content inside the multi line of text column, if you will not place this script html will be rendered as plain text

<script type="text/javascript">
$(document).ready(function(){

function render_html()
{

var theTDs = document.getElementsByTagName("TD");

var i=0;

var TDContent = " ";

while (i < theTDs.length) {

try {

TDContent = theTDs[i].innerText || theTDs[i].textContent;

if ((TDContent.indexOf("<DIV") == 0) && (TDContent.indexOf("</DIV>") >= 0)) {

theTDs[i].innerHTML = TDContent;

}

}

catch(err){}

i=i+1;

}

}

render_html();

});

 </script>

Happy Coding !!!

Thursday, February 2, 2017

Create List Items using rest Api in SharePoint

You can create lists records using the powerful rest API that SharePoint provide.

Here is an example how you can do it



<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function AddListItem() {
         var category = $("select[id$='ddlcategory'] option:selected").text();
        var feedback = $("[id$='txtfeedback']").val();
        $.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Feedback')/Items",
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.FeedbackListItem"
                    },
                    Title: category,
                    Feedback: feedback
                   
                }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "X-HTTP-Method": "POST"
                },
                success: function (data, status, xhr) {

                },
                error: function (xhr, status, error) {

                }
            });
    
    }
</script>
I created this function to create list records in my Feedback list.
I am getting a string value from a text box and from one select box and passing these value to list fields and called this function on button click.

You have to take care of the below code

  data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.FeedbackListItem"    // This is the list title and the syntax to create item
                    },
                    Title: category,  //These are internal names of fields to which you will be passing values
                    Feedback: feedback
                   
                }),

Happy Coding !!!

Wednesday, January 18, 2017

Get List items using Rest Api and Angular js in SharePoint

Hello Folks,

I am going to explain you how to get list items from SharePoint list using restful api and angular js.

First of all you need to get the angular js file, you can get online link or you can download it from here https://angularjs.org/ (version 1) and place inside any SharePoint library

Place a script editor web part on page and add below script.
<script type="text/javascript" src="/Style Library/vmware/js/angular.min.js"></script>

<script type="text/javascript">
    var myAngApp = angular.module('div_ngapp', [ ]);
    myAngApp.controller('div_ngcontroller', function ($scope, $http) {
        $http({
            method: 'GET',
            cache: true,
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Test')/items?$select=Title,ID",
            headers: { "Accept": "application/json;odata=verbose" }
        }).success(function (data, status, headers, config) {
            $scope.listitems= data.d.results;

        }).error(function (data, status, headers, config) {

        });
      
    });
<div  ng-app="div_ngapp">
             <div ng-controller="div_ngcontroller">
                       <div class="row" ng-repeat="item in listitems">
                                <h3>{{item.Title}}{{item.ID}}</h3>
                                      
                        </div>
              </div>
</div>

Let me explain you whole script

   var myAngApp = angular.module('div_ngapp', [ ]);

This is needed to activate angular js and it should be one of the html tag. In my case i have created a div and give its ng-app value as div_ngapp. You can try with different names as you wish.

Now you have to initialize controller function as 

 myAngApp.controller('div_ngcontroller', function ($scope, $http) {
        $http({
            method: 'GET',
            cache: true,
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Test')/items?$select=Title,ID",
            headers: { "Accept": "application/json;odata=verbose" }
        }).success(function (data, status, headers, config) {
            $scope.listitems= data.d.results;

        }).error(function (data, status, headers, config) {

        });
      
    }); 


You have to create another div inside your ng-app div and give its ng-controller value in my case i have created a div div_ngcontroller and passed its value in above function

Specify method as 'GET' 

Pass the url _spPageContextInfo.webAbsoluteUrl this will give you the web absolute url and you have to give the list title from where you want to get the items

spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Test')/items?$select=Title,ID"

Above will get the items from list 'Test' and get only the fields specified after $select  as you can see i am getting only title and id fields. You have to give the internal name of the fields after select.

success(function (data, status, headers, config) {
            $scope.listitems= data.d.results;

In success function getting the list items in a scope variable; in my case i have created a scope array named listitems and all result is stored here.

In html you have to create the following structure

<div  ng-app="div_ngapp">
             <div ng-controller="div_ngcontroller">
                       <div class="row" ng-repeat="item in listitems">
                                <h3>{{item.Title}}{{item.ID}}</h3>
                                      
                        </div>
              </div>
</div>

ng-app and ng-controller i have already explained.

 ng-repeat="item in listitems" 

This causes the html structure below this tag to repeat like  a for loop.

listitems is scope array variable and item is another variable. You can give any names as you wish to give. Now you will get values by item variable

 <h3>{{item.Title}}{{item.ID}}</h3> will be repeated n-times where n is number of items in list ( $scope.listitems)

To get the value you have to pass inside curly braces {{item.Title}} this gets the item title value inside h3 tag

Similarly you can get any column value by using this syntax.

Happy Coding!!!









Friday, July 31, 2015

"This content cannot be displayed in a frame" CRM 2015 online SharePoint 2013 online issue

Recently i got this error message when i tried to show SharePoint 2013 online page in iframe in CRM 2015 online. I tried different options like adding both the sites to trusted zone and enabled mixed mode content in internet explorer but it did not work.

To solve this issue i added the below tag in master page of the site collection's root site and it worked like a charm.

I added this tag after all the <%@ Register tags

<WebPartPages:AllowFraming runat="server"/>

This allows the site pages to be shown in iframe outside the SharePoint.

Happy Coding !!!

Thursday, June 4, 2015

XSLT date sorting in RSS viewer Web Part

Recently i encountered a issue while sorting in RSS Viewer web part. In xslt you can sort only on number and text data type and no option for date-time data type.

I wanted to sort data on pubDate of RSS feed. I tried using the SharePoint designer and use the sort and group option but  did not work.
The trick is to convert the pubDate to some format and then split the year, month and day and then sort on these 3 parts.

Example:

In my case pubDate is in this format Wed, 20 May 2015 07:02:09 +0200
I format this using FormatDate(pubDate,number(2057),1) and output is 20/06/2015.
Then split the year 2015, month 06 and day 20 using substring method and then sort these respectively.

You have to use the xsl:sort under RSSMainTemplate.body template after the xsl:for-each.

Source Code:

<xsl:for-each select="$Rows">
<xsl:sort  order="descending" select="substring(ddwrt:FormatDate(pubDate,number(2057),1),7)"></xsl:sort>

  <xsl:sort  order="descending" select="substring(ddwrt:FormatDate(pubDate,number(2057),1),4,2)"></xsl:sort>
  <xsl:sort  order="descending" select="substring(ddwrt:FormatDate(pubDate,number(2057),1),1,2)"></xsl:sort>


Happy Coding !!!

Wednesday, February 11, 2015

Create External Content Type in SharePoint 2013 online from on-premises SQL Server


In this post i will explain you how to create a external content type in SharePoint 2013 online from a on premises Sql Server

1.       Create and Deploy OData Services to any server that can be accessed on internet


1.       Create BDC Model using Visual Studio

1.       Go to SharePoint Admin Center

a.       Click BCS from left menu and click Manage BDC Models and External Content Types


b       Choose BDC Model from drop down and click import

.


c.       Import the BDC model which you have extracted in Step 2
d.      Select the external content types from the drop down and choose your content type that is imported from the BDC Model and click set object permissions. Permissions are required so that users can read the data using this content type


1.       Create External List from this content type

Click add an app and then choose external list from the apps and then select the external content type for the data source of this list.


Wednesday, July 16, 2014

Something went wrong SharePoint App issue

Problem: 

Whenever SharePoint hosted or Auto hosted app code or html  is updated and you upload it to app catalog, and add the newly updated app into site you get the Something Went wrong error message.

Resolution

1) When you remove the app from the web, it will go into the recycle bin of that web and the site collection of that web. You need to remove it from the web recycle bin and site collection's recycle bin. In site collection recycle bin choose "Deleted from end user recycle bin" and then delete the app

2) Second method is to create a new GUID for the app and then open Appmanifest.xml with code and then replace the Product ID with the newly created GUID. In this way app will be registered with a different product id.

3) Third is change the version of app and then upload it again to app catalog site.

Happy Programming !!!

Tuesday, June 3, 2014

Create a basic Auto-hosted SharePoint App

Here i am going to demonstrate how to create a Auto-hosted SharePoint 2013 app using client side object model. I have deployed this app in SharePoint 2013 online environment. I used the Visual Studio 2013 to build this app.

Let's start

Start visual studio 2013, click File ->New->Project. Select the Apps template and select App for SharePoint 2013 as shown below and give it a proper name.



Specify the URL of SharePoint Site where you want to deploy this app and choose Autohosted as shown below


This will create as solution with two project as shown below




Every autohosted app have two projects, One Project contains the App itself and other web based project contains the code, pages and other logic.Open the default.aspx page under the web project to add html and code you want.
I have created this app that shows the current logged in user name. In the default.aspx page put the below html code.You must use the Jquery file in order to render the chrome container. The below java script creates chrome and app setting link and contact URL's
 <script type="text/javascript" src="../Scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        var hostweburl;

        // Load the SharePoint resources.
        $(document).ready(function () {

            // Get the URI decoded app web URL.
            hostweburl =
                decodeURIComponent(
                    getQueryStringParameter("SPHostUrl")
            );

            // The SharePoint js files URL are in the form:
            // web_url/_layouts/15/resource.js
            var scriptbase = hostweburl + "/_layouts/15/";

            // Load the js file and continue to the
            //   success handler.
            $.getScript(scriptbase + "SP.UI.Controls.js", renderChrome)
        });

        // Function to prepare the options and render the control.
        function renderChrome() {

            // The Help, Account, and Contact pages receive the
            // same query string parameters as the main page.
            var options = {
                "appIconUrl": "../Images/AppIcon.png",
                "appTitle": "My First Test App",
                "appHelpPageUrl": "Help.html?"
                    + document.URL.split("?")[1],
                "settingsLinks": [
                    {
                        "linkUrl": "specify any link url/",
                        "displayName": "display of link url "
                    },
                    {
                        "linkUrl": "mailto:specify your mail",
                        "displayName": "Contact us"
                    }
                ]
            };

            var nav = new SP.UI.Controls.Navigation(
                                    "chrome_ctrl_placeholder",
                                    options
                              );
            nav.setVisible(true);
        }

        // Function to retrieve a query string value.
        // For production purposes you may want to use
        // a library to handle the query string.
        function getQueryStringParameter(paramToRetrieve) {
            var params =
                document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="divSPChrome"></div>
        <div id="chrome_ctrl_placeholder"></div>
        <asp:Label ID="lbltitle"  runat="server"></asp:Label>
        <asp:Button Text="Click this" ID="btnclick" runat="server" OnClick="btnclick_Click" />
</form>
</body>

In defaault.aspx.cs use the below code on button click event use this code

 protected void btnclick_Click(object sender, EventArgs e)
        {
                      var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
           {
               clientContext.Load(clientContext.Web.CurrentUser);
                clientContext.ExecuteQuery();
                lbltitle.Text = "Welcome "+clientContext.Web.CurrentUser.Title;
             
            }
}

Double click on the AppManifest.xml and set the Query string as shown below.


Query string tokens are used to get some properties like host site URL, logo URL etc on the app page. We can use these token in java script or client object model. For more on this read at http://msdn.microsoft.com/en-us/library/office/jj163816(v=office.15).aspx


Also on the permissions tab set the appropriate permission setting for this app






Now build web project and then build the app project itself. Now right click on the first project i..e. app project and select Publish

This will  open the screen and then select publish and then click publish the app. Now your app is ready to be uploaded to app catalog. App contains the .app extension file and upload this file to your app catalog on SharePoint Online environment or on premises.

On any site choose add an app from the top and then choose app from your organizations and then select the newly uploaded app. Test it and make changes accordingly.

Please let me know if you face any issue. Happy coding, cheers :) 

Thursday, May 29, 2014

Get Choice Field values using Client Side Object Model in SharePoint 2013

Folks,

In this post i will explain you how to retrieve choice field values in Client Side Object Model (CSOM) in SharePoint 2013. I have tested this code in Auto hosted app on SharePoint online environment. You can use this code snippet to get values from choice field for custom filter and search conditions.

 var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                List queslist = clientContext.Web.Lists.GetByTitle("YourListTitle");
                Field choice = queslist.Fields.GetByInternalNameOrTitle("FieldName");

                FieldChoice fldChoice = clientContext.CastTo<FieldChoice>(choice);
                clientContext.Load(fldChoice, f => f.Choices);
                clientContext.ExecuteQuery();
                foreach (string  item in fldChoice.Choices)
                {
                    ddltopic.Items.Add(item.ToString());
//add choices to dropdown list
                }
}

You have to get the SharePoint context, then get the list field and then get that field choice and use the choice fields as per your needs, i have added the choice values in a drop-down list.

Let me know if you face any problem..

Happy Coding :)

Friday, May 9, 2014

Search SharePoint List items using jQuery/JavaScript and Web Service

You can use jquery/javascript to search items from a SharePoint list. You can define you CAML query and based on that result will be displayed. Lists.asmx web service is used in this case. You can use this to search items both on SharePoint online or on-premises versions.

List.asmx service is called and post method is called provided with soap envelope and in return we get the list items in from of xml. You can also highlight the searched keyword in the result.

Tuesday, March 25, 2014

How to create folder and sub folders inside Document Library using web service in SharePoint

In this post i will explain how we can use the UpdateListItems method of Lists web service to create folder and sub folder inside a document library. I will give you the code snippet and using this you can create folders and sub folders inside document library.

Here is the code snippet

 private void CreateFolder(string listName, string rootSubFolderName, string newFolderName)
        {
       
       
            string rootFolder = rootSubFolderName.Length > 0 ? string.Format("/{0}/{1}", listName, rootSubFolderName) : listName;
       
            string xmlCommand = string.Format("<Method ID='1' Cmd='New'><Field Name='FSObjType'>1</Field><Field Name='BaseName'>{1}</Field></Method>", rootFolder, newFolderName);
         
            XmlDocument doc = new XmlDocument();
            System.Xml.XmlElement batchNode = doc.CreateElement("Batch");
            batchNode.SetAttribute("OnError", "Continue");
            //Insert / to front as it is required by web service.
            if  (!rootFolder.StartsWith("/"))
                rootFolder = string.Format("/{0}",rootFolder);
//if you are having different site collection use  rootFolder = string.Format("/sites/sitename/{0}",rootFolder);

            if(rootSubFolderName.Length>0)
                rootFolder = string.Format("/{0}", rootFolder);
//if sub folder is to be created inside a folder

            batchNode.SetAttribute("RootFolder", rootFolder);
            batchNode.InnerXml = xmlCommand;
            XmlNode resultNode =listsservice.UpdateListItems(listName, batchNode);

            if ((resultNode != null) && (resultNode.FirstChild.FirstChild.InnerText == FOLDER_EXISTS) || (resultNode.FirstChild.FirstChild.InnerText == SUCCESS))
            {
                // success
            }
            else
            {
                //failure
                throw new Exception("Create new folder failed for: " + newFolderName + ". Error Details: " + resultNode.OuterXml);
            }
        }

Usage: You can call this function to create folders and sub folders as described below:

1)  CreateFolder("Your Document Library Title", "","Folder Name");
 This will create the folder inside "Your Document Library Title" with the Name "Folder Name" as no rootSub folder name parameter is specified.
 2)  CreateFolder("Your Document Library Title", "RootFolder","Folder Name");
 This will create the sub folder inside "Your Document Library Title", inside "RootFolder"
In this case hierarchy of the folders will be:Your Document Library Title/RootFolder/Folder Name

Tuesday, June 11, 2013

Get Current User's Regional Settings and Locale

SharePoint has a feature where user can set his/her own Regional settings and locale. In this post I will tell you how to get these settings using Object Model and show the date format according to the user's Locale.

To set your Regional settings

Select Welcome Control-> Select My Settings -> Select My Regional Settings

You have to uncheck the "Always follow web settings" option and then set your Locale.

In the code file, use this code

Get the current user's Regional settings by SPRegional Settings class

 SPRegionalSettings rgnUser = SPContext.Current.Web.CurrentUser.RegionalSettings;
             
I have created a property to get the date format you can use the same

public static string format
        {
            get
            {
                SPRegionalSettings rgnUser = SPContext.Current.Web.CurrentUser.RegionalSettings;
                if(rgnUser!=null)
             
                return "{0:" + System.Globalization.CultureInfo.GetCultureInfo(Convert.ToInt32(rgnUser.LocaleId)).DateTimeFormat.ShortDatePattern + "}";

                else

                    return "{0:" + System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern + "}";
            }
        }
If user has set his/her Regional Settings then it will show the date format according to the set locale otherwise it will show the current culture's date format.

Thursday, November 22, 2012

GAC deployment but code does not update

Recently i faced a strange issue and i want to share that with you guys, when deploying the application pages and dll in to GAC. The issue was when i change the html and code and deploy to my sever it was working fine but when i installed the same solution on production environment only the html was showing updates but not the code .i.e changes made to the code files were not reflecting on the production environment. I used the gac utility to uninstall and install but no effect on the code, i was shocked with this strange issue html is reflecting changes but not the code.

I googled this issue but not worked for me. Then in one of the post i read that check the dll version and time of installion, then first thing i did is change the dll version from the project properties. Right click on the project, select Assembly Information and then changed the dll and file version, then build the wsp file and installed on the production server. Yes this time it did the trick code changes were reflecting on the application pages on the production site. The only problem was change the dll version and make sure that in the gac it has latest version installed.


Monday, October 15, 2012

Connected Web Parts

SharePoint Object Model provides the functionality where web parts can communicate with each others by sending and getting parameters and this mechanism is called Connected Web Parts. You can create connections between web parts and send/receive information between them.

In this post i am going to explain how you can make connection between web parts pro-grammatically.

The connected web parts is based on the concept of interface.

First of all creates a interface and a property whose value can be send to other web parts. In my case i have created a property to send client info to other web part 

  public interface ClientInterface
    {
        string clientinfo { get; }

    }
Now create a web part from say "SenderSenderWebPart " where you want to send the value to other web part and inherit above interface like

 public class SenderWebPart : WebPart,ClientInterface
    
Now create a property to send the value in this web part

 public string clientinfo
        {

            get
            {
                return "Your Test Value";
            }
        }

and create a connection attribute like below:

[ConnectionProvider("clientinfoprovider")]
        public ClientInterface getclientname()
        {
            return this;
        }

Now create another web part say "Receiver" that will receive this clientinfo from above web part

Create a object of interface in this new web part like   ClientInterface clientinfostring;

Create a connection consumer attribute like 

[ConnectionConsumer("clientinforRightNavigationWebpart", "GetClientInfo")]
        public void ReceiveClientInfo(ClientInterface c)
        {
            clientinfostring = c;
        }

Now you can get the clientinfo in this web part. 

For example 

 protected override void RenderContents(HtmlTextWriter writer)
        {

      
            if (clientinfostring != null)
            {

                 string clientname= clientinfostring.clientinfo;
              
                writer.Write(clientname);
            }

Now build and deploy the web parts. When you place these web parts on page, select edit page, edit sender web part, select connection and make connection to the receiver web part as shown below







Once you create a connection it ask for the confirmation. Now your web parts are connected and can communicate with each other.

Friday, July 20, 2012

InfoPath Form Publishing Error

When you publish  InfoPath  form to the library, then there are chances that you get this error message

"An issue was found with the following variable 'Form.FormCode_variable'. Member variables are not supported. Use the FormState property to store data"

The main cause of this error is that somewhere in the code of form you have declared a variables and you are accessing that variables.

e.g. public string clientname="c1";

and you are using this "clientname" variable through out the form.

To avoid this use property like

public string clientname
{
get;set;
}

and use the FormState property of  InfoPath  form to use this value through out the form.

FormState property is state management technique in InfoPath forms and can be accessed in the form.

Use FormState["client"]=clientname;

and to access this use string clientname=Convert.ToString(FormState["client"]);

With the help of FormState the form will be published without any errors.

Friday, July 13, 2012

SharePoint Rich Text Input Control

SharePoint 2010 has inbuilt text box control that can be used to create rich text strings including images, hyperlinks, can use your own html tags in this.




Let's see how to use this control

The control tag is defined below

 <SharePoint:InputFormTextBox ID="txtmsg" runat="server" Rows="10" TextMode="MultiLine"
                RichText="true" RichTextMode="FullHtml">

There are properties that turns this simple text box to rich text box control and those are "RichTextMode" and "RichText"

Set "RichText" property value to true to and "RichTextMode" to "FullHtml". You can set height and width of this control using the "Columns" and "Rows" properties respectively.

Known Issues

This control does not work with firefox and chrome browsers. Only works with IE.

Sometimes this control does not render properly and only html text is displayed, to overcome this issue use the below function on the html part of page where you are using this control.


This function converts the text area to rich text control using function"RTE_ConvertTextAreaToRichEdit"

that is defined in the "/_layouts/1033/form.js" file.


<script type="text/javascript">

function CreateRichEdit(id) {

if (browseris.ie5up && browseris.win32 && !IsAccessibilityFeatureEnabled()) {

g_aToolBarButtons = null;

g_fRTEFirstTimeGenerateCalled = true;

RTE_ConvertTextAreaToRichEdit(id, true, true, "", "1033", null, null, null, null, null, "Compatible", "\u002f", null, null, null, null);

RTE_TextAreaWindow_OnLoad(id);

}

else {

document.write("&nbsp;<br><SPAN class=ms-formdescription><a href='javascript:HelpWindowKey(\"nsrichtext\")'>Click for help about adding basic HTML formatting.</a></SPAN>&nbsp;<br>");

};

}

    var id = "<%= txtmsg.ClientID %>";


"here use your own rich text control id and call the function like below;

    CreateRichEdit(id);
</script>

Tuesday, June 26, 2012

How to create SharePoint User Group and Assign Permissions


There are some cases where you want to create a group pro grammatically and want to assign permission. e.g. on the Feature receiver (Feature Activated) code.

In this post i am going to explain you how to create group and to assign permissions to this group.
First get the collection of site groups.

SPGroupCollection groups = web.SiteGroups;

web.BreakRoleInheritance(false);
Add the group to this collection. I have created "Test Group" in this example.

groups.Add("Test Group", web.CurrentUser, null, "");
SPGroup grp= web.SiteGroups["Test Group"];          

AllowMembersViewMembership property of this group to false.

This  Gets or sets a Boolean value that specifies whether only group members are    allowed to view the list of members in the group.
grp .OnlyAllowMembersViewMembership = false;
        grp .Update();

Now create a Role Assignment object of this group.

SPRoleAssignment asgn = new SPRoleAssignment(web.SiteGroups[ "Test Group"]);

Create a Role Definition, Here i have used the "Administrator" role, other available roles are

1) None
2) Guest
3) Reader
4) Contributor
5) WebDesigner
6) Administrator  

            SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Administrator);

Now assign the Role to the Role Assignment and add the  Role Assignment to the web and update the web

            asgn.RoleDefinitionBindings.Add(role);
            web.RoleAssignments.Add(asgn);
            web.Update();

Now deploy the solution and check the group and its permissions.

I have used this code on the feature activated code that creates group and assign permissions to this.