Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Tuesday, September 5, 2017

backup restore external content type and external list

1. Create ECT in SPD using Secure Store as Authentication

2. Configure in BCS as required

3. Export the ECT from SPD on Dev

4. Set up identical Secure Store on Test

5. Import BCS Model in Test

6. Set Permissions as required on ECT

7. Create list from ECT

backup restore external content type and external list 

Thursday, August 3, 2017

SharePoint: CAML Query not working based on WHERE clause

When we write the CAML query in SharePoint development and if we put WHERE clause in query it still returns all records.


For example look at the below query, it works fine in U2U builder but returns all records if we use the same in code.


SPQuery query = new SPQuery();
query.Query = "<Query><Where></Where></Query>"


Here is the Fix:

Remove the "<Query>" Tag and rewrite it

SPQuery query = new SPQuery();
query.Query = "<Where></Where>"

SharePoint: SPSecurity.RunWithElevatedPrivileges method

This is used to execute the specified method with Full Control rights even if the logged in user does not otherwise have Full Control.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // Your code here...
});


Note:

1.The RunWithElevatedPrivileges method can not be used within a sandbox solution 

2.The item that is actioned with elevated privileges will be executed under the web applications App pool account in IIS, which means that the modified user of the document/list item will most likely display as SYSTEM ACCOUNT.

3.If you did not want to execute the code as the App Pool account for any reason, you could alternatively use a specific user account to execute the code under by implementing the SPUserToken class.

SharePoint WebPart Life Cycle

It's important to know everything about webpart events and the sequence to avoid development mistakes.

Initial Load:

Events fired when a web part is initially loaded.

OnInit 
OnLoad
EnsureChildControls 
CreateChildControls 
EnsureChildControls 
CreateControlCollection 
EnsureChildControls (many) 
OnPreRender 
EnsureChildControls (many) 
SaveViewState 
RenderControl 
Render 
RenderControl 
RenderContents 
RenderChildren 
OnUnload 
Dispose

Post-back:

OnInit 
LoadViewState
EnsureChildControls 
CreateChildControls 
EnsureChildControls 
CreateControlCollection 
EnsureChildControls (many) 
OnLoad
btnUpdate_Click
OnBubbleEvent
EnsureChildControls 
OnPreRender 
EnsureChildControls (many) 
SaveViewState 
RenderControl 
Render 
RenderControl 
RenderContents 
RenderChildren 
OnUnload 
Dispose



Like Asp.Net life cycle there is also Web Part life cycle. So it is better to understand the web part life cycle. 


OnInit: This method handles initialization of the control.

OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.

CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method.

EnsureChildControls: This method ensures that CreateChildControls has executed. EnsureChildControls method must be called to prevent null reference exceptions.

SaveViewState: View state of the web part saved.

OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render. 

Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.

Render: This method is used to render everything.

RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.

OnUnload: Performs the final cleanup.

Set Default value to Person or Group field in SharePoint 2010 using JavaScript and JQuery

This article is about how to set default value to person or group field when new list form opens using JavsScript and JQuery.

It includes the following

1. Get the members of a SharePoint group using SPServices JQuery library
2. Set the value to Person or Group field using JavaScript

<script type="text/javascript" language="javascript" src="/Style%20Library/JS/jquery-1.8.3.min.js"></script>
<script type="text/javascript" language="javascript" src="/Style%20Library/JS/jquery.SPServices-0.7.2.min.js"></script>
<script type="text/javascript">

    $(document).ready(function() {
      var strHTMLGroupUsers = "";
        $().SPServices({         
        operation: "GetUserCollectionFromGroup",
        groupName: "Approvers",
        async: false,
        completefunc: function(xData, Status) {
        $(xData.responseXML).find("User").each(function() {
          strHTMLGroupUsers += $(this).attr("Name")+";";
        });
      }
        });
        //get the people pickers input div
        var pp = getPickerInputElement("Approvers");
        //set it to the current user if we've found it
        if(pp != null) 
        pp.innerHTML = strHTMLGroupUsers;
        $("img[title='Check Names']").parent().click();

    });

function getPickerInputElement(fieldsInternalName)

    var result  = "";
    var divs = document.getElementsByTagName("DIV");
    for(var i=0; i < divs.length ; i++)
     { 
       if(divs[i].id=="WebPartWPQ3")
        { 
          var tds = divs[i].getElementsByTagName("TD");
          for(var j=0; j < tds.length; j++)
           { 
             var cellHTML = tds[j].innerHTML;
              
             if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
             { 
               var innerDivs = tds[j].getElementsByTagName("DIV");
               for(var k=0; k < innerDivs.length; k++)
               { 
                 if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
                 { 
                   result = innerDivs[k];
                   break;
                 }}}
             }
           }
        }
   return result;
}



</script>
 

Thursday, July 6, 2017

SharePoint 2013 Global Navigation Menu Alignment and Display

Add below CSS to Content Editor WebPart and it will resolve problem.
<style>
.ms-core-listMenu-horizontalBox .menu-item.ms-core-listMenu-horizontalBox  
.menu-item .additional-background.ms-core-listMenu-horizontalBox  
.menu-item .additional-background .menu-item-text { display:block; }
ul.dynamic { min-width:175px; }
span.menu-item-text:hover { 
background-color:rgba(205,230,247,0.5);
padding:2px;
}
span.menu-item-textpadding:2px;
}
</style> 

SharePoint 2013 Search REST API

You can use the Search REST service to submit Keyword Query Language (KQL) or FAST Query Language (FQL) queries in your apps for SharePoint, remote client applications, mobile applications, and other applications.

The Search REST service supports both HTTP POST and HTTP GET requests.

GET requests

Construct the URI for query GET requests to the Search REST service as follows:

/_api/search/query

For GET requests, you specify the query parameters in the URL. You can construct the GET request URL in two ways:
  • http://server/_api/search/query?query_parameter=value&query_parameter=value
  • http://server/_api/search/query(query_parameter=value&query_parameter=)
POST requests

You construct the URI for query POST requests to the Search REST service as follows:

/_api/search/postquery

For POST requests, you pass the query parameters in the request in JavaScript Object Notation (JSON) format.

Disabling ParserEnabled affect: SharePoint 2013

Disabling ParserEnabled affect:
  1. We can't search in document library using Office document properties.
  2. When you upload image file. Thumbnail will not be generated.
  3. When you save a list template, You will not see it in list template gallery.
If you need to disable this property you need to take care of its effect. Disable it only in special sites. if you want it when you upload document using code disable it temporary using code like below:

using (var site = new SPSite("http://sharepoint-portal"))
{
    using (var web = site.OpenWeb())
    {
       SPFile file = web.GetFolder("Documents").Files["mydoc.docx"]; 
       using (var fs = new FileInfo(@"C:\Documents\mydoc.docx").OpenRead())
 
       {
        documentBytes = ..... // get the documents bytes
       }
       web.ParserEnabled = false;
       web.Update();
       file.SaveBinary(documentBytes);
       web.ParserEnabled = true;  
       web.Update();
    }
}

SharePoint SPWeb Property ParserEnabled

ParserEnabled :- property controls demotion and promotion.
Promotion :- The process of extracting values from properties of a document and writing those values to corresponding columns on the sharepoint list or document library where the document is stored.

Demotion :- The same process in reverse.Read sharepoint list or library columns values and written to document properties.

When ParserEnabled property false there will not be any property demotion and promotion, which means metadata and document file properties will not be in sync.

PowerShell way of Disabling and enabling this property:
Disable ParserEnabled property:
    [system.reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint")
    $site = new-object Microsoft.SharePoint.SPSite("http://mossweb/sites/test")
    $site.RootWeb.ParserEnabled = $false
    $site.RootWeb.Update()

Enable ParserEnabled property or document property promotion:
    $site.RootWeb.ParserEnabled = $true
    $site.RootWeb.Update()

Friday, June 30, 2017

Display Custom Metadata in the Advanced Search Web Part within SharePoint

                        string advancedUrl = newSearchWebSearch.Url + "/Pages/advanced.aspx";
                        SPFile advanceFile = newSearchWebSearch.GetFile(advancedUrl);
                        if (advanceFile.Exists)
                        {
                            advanceFile.CheckOut();
                            //Get Result search page
                            SPListItem wikiItem = advanceFile.Item;
                            string managePropertyname = strSubjectAreaName + getPropertyType(newSearchWeb, strSubjectAreaName), managePropertytype = getPropertySearchType(newSearchWeb, strSubjectAreaName), managePropertyDisplayName= strSubjectAreaName;


                            SPLimitedWebPartManager advsearchwebPartManager = newSearchWebSearch.GetLimitedWebPartManager(advancedUrl, PersonalizationScope.Shared);
                            foreach (var wsp in advsearchwebPartManager.WebParts)
                            {
                                if (wsp is AdvancedSearchBox)
                                {
                                    var wpAdavance = wsp as AdvancedSearchBox;
                                    string SearchQuery = wpAdavance.Properties.ToString();
                                    XmlDocument xmlDocs = new XmlDocument();
                                    xmlDocs.LoadXml(SearchQuery);
                                    XmlNodeList category1 = xmlDocs.SelectNodes("/root/r");
                                    XmlNodeList category = xmlDocs.SelectNodes("/root/PropertyDefs");
                                    XmlNodeList resulttype = xmlDocs.SelectNodes("/root/ResultTypes/ResultType");

                                    var newProperty = xmlDocs.CreateNode(XmlNodeType.Element, "PropertyDef", "");


                                    var property_attribute4 = xmlDocs.CreateAttribute("Name");
                                    property_attribute4.Value = managePropertyname;
                                    var property_attribute1 = xmlDocs.CreateAttribute("DataType");
                                    property_attribute1.Value = managePropertytype;
                                    var property_attribute2 = xmlDocs.CreateAttribute("DisplayName");
                                    property_attribute2.Value = managePropertyDisplayName;

                                    newProperty.Attributes.Append(property_attribute4);
                                    newProperty.Attributes.Append(property_attribute1);
                                    newProperty.Attributes.Append(property_attribute2);
                                    foreach (XmlNode node in category)
                                    {
                                        if (node.Name == "PropertyDefs")
                                        {
                                            category[0].AppendChild(newProperty);
                                        }
                                    }
                                    for (int j = 0; j < resulttype.Count; j++)
                                    {
                                        var Result_newInnerNode = xmlDocs.CreateNode(XmlNodeType.Element, "PropertyRef", "");
                                        var result_attribute = xmlDocs.CreateAttribute("Name");
                                        result_attribute.Value = managePropertyname;
                                        Result_newInnerNode.Attributes.Append(result_attribute);
                                        resulttype[j].AppendChild(Result_newInnerNode);
                                    }
                                    wpAdavance.Properties = xmlDocs.InnerXml;
                                    advsearchwebPartManager.SaveChanges(wpAdavance);
                                }
                            }
                            newSearchWebSearch.AllowUnsafeUpdates = true;
                            advanceFile.CheckIn("Publish", SPCheckinType.MajorCheckIn);
                            advanceFile.Publish("Publish");
                            _sitePage.Update();
                            newSearchWebSearch.Update();
                            newSearchWebSearch.AllowUnsafeUpdates = false;
                        }

                        //Based on Subject Seperate search Page

Thursday, June 22, 2017

Application Page in SharePoint Model Dialog Box

Recently i have done some silly tinker works while open application page in SharePoint Model dialog box. In this post i have explained that. This may help someone who needs

My Scenario:
Open an application page, where have a ListFieldIterator, asp.net file upload controls and once save button and one cancel button. On save button handle the required validation and update the item to list.

First Code Snippet
Webpart Solution (Only the button code) 
Ascx
 <script type="text/javascript"">
     function fnOpenUpdateSection(queryString, title, oldJobAidStatusID, jobAidID) {
         addSectionUri = "/_layouts/LisFiedIteratorResize/LFIApplPage.aspx";
         var options = { url: addSectionUri, width: 800, height: 800, title: "Test Page" };
         SP.UI.ModalDialog.showModalDialog(options);
         return false;
     }
 </script>
 <asp:Button ID="btnTest" runat="server" Text="Click" />

Things to discuss that here, I have added a asp.net button control in my webpart solution and written a javascript to open the application page in SharePoint Model popup dialog box.

Ascx.cs
protected void Page_Load(object sender, EventArgs e)
        {
            btnTest.Attributes.Add("onclick""javascript:return fnOpenUpdateSection()");
        }

On Page load, assigned the javascript to the button through button attributes.

Application Page 
Aspx
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table id="tblUpdateScript" runat="server" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td>
                <SharePoint:ListFieldIterator ID="lfiUpdateJobAid" runat="server"ControlMode="New" ExcludeFields="DisplayOrder;#IsDeleted">
                </SharePoint:ListFieldIterator>
            </td>
        </tr>
        <tr id="trFileUpload" runat="server">
            <td valign="top">
               <asp:Label ID="lblAttachments" runat="server"CssClass="labelAttachment">Attachments</asp:Label>
            </td>
            <td>
                <asp:FileUpload ID="fuSectionAttachment" runat="server" />&nbsp;
                <asp:Label ID="lblAttach1Error" runat="server"CssClass="labelAttachmentError"></asp:Label><br />
                <asp:FileUpload ID="fuSectionAttachment1" runat="server" />&nbsp;
                <asp:Label ID="lblAttach2Error" runat="server"CssClass="labelAttachmentError"></asp:Label><br />
                <asp:FileUpload ID="fuSectionAttachment2" runat="server" />&nbsp;
                <asp:Label ID="lblAttach3Error" runat="server"CssClass="labelAttachmentError"></asp:Label>                               
            </td>      
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td valign="top" colspan="2">
                <asp:LinkButton ID="lbnSave" CommandName="Save" runat="server"OnClick="btnSave_Click">
                    <img id="Img1" src="/Style%20Library/images/save.png"align="absMiddle" runat="server"
                        alt="Save" />
                </asp:LinkButton>&nbsp;&nbsp;               
                    <img id="Img2" src="/Style%20Library/images/cancel.png"align="absMiddle" runat="server"
                        alt="Cancel"onclick="javascript:SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancelled clicked');" />               
            </td>
        </tr>
        <tr>
            <td valign="top" colspan="2">
                <asp:Label ID="lblErrorMessage" runat="server"></asp:Label>
            </td>
        </tr>
    </table>
</asp:Content>

Designed a table in the Main ContentPlaceHolder with 3 rows. In 1st row added SharePoint ListFieldIterator, 2nd row added asp.net file upload controls and 3rd row added two buttons (Linkbutton and html image control)

Aspx.cs
protected void Page_Init(object sender, EventArgs e)
        {
          if (!IsPostBack)
            {

            using (SPSite osite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb oweb = osite.OpenWeb())
                {
                    SPList olist = oweb.Lists.TryGetList("Job Aid Sections");
                    if (olist != null)
                    {
                        lfiUpdateJobAid.ListId = olist.ID;
                    }
                }
            }
          }  
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

                lfiUpdateJobAid.ListItem["JobAidID"] = 1;
                lfiUpdateJobAid.ListItem["SectionType"] = 0;
                lfiUpdateJobAid.ListItem["IsDeleted"] = 0;

                lfiUpdateJobAid.Web.AllowUnsafeUpdates = true;
                lfiUpdateJobAid.ListItem.Update();
                lfiUpdateJobAid.Web.AllowUnsafeUpdates = false;

                Response.Write("<script language='javascript'>window.parent.location.href = window.parent.location.href</script>");
            }           
        }
On Page_Init set theListId property for the SharePoint ListFieldIterator and button_Click perform the required action and update the listitem
Note: In the button click used a javascript to close the application page after update the list item.

OutPut:

















Issue 1:  

When maximize application page the ListFieldIterator Field (Multi Line Text Editor) is not extend the width. Refer the below snapshot, also want to increase the height


















Also want to increase the single line of text box width.

Solution:

Multi Line of Text change height:

We can do it by changing the Column setting
List -- List settings -- Multi Line of Text Column -- Number of lines for editing
Change the value as 40

Multi Line of Text change width:

By default the Enhanced RTE get expand when maximize the page. But here we have add the LFI within table row. So it’s not working. To solve this we can set the table width as 100%
<table id="tblUpdateScript" runat="server" cellpadding="0" cellspacing="0" width="100%">
 
Single Line of Text change width:

We can handle this through the css. 
The default width for the Single Line of Text is 386px. We can handle the class in our css. Refer the below snippet.
ms-long
    {
        width:50%;
    }

Now refer the below snapshot, which has taken after done the above mentioned changes

















Issue 2:

Want to open the model dialog box in maximized mode, 

Solution:

I used showMaximized option in SharePoint Model Dialog box. Refer the below code snippet

var options = { url: addSectionUri, showMaximized:true, title: "Test Page" };

 This open the application page in maximized mode, but gives another issue 
            “After open the page, if I click save button without enter any value then the application page collapsed” refer the below snap, that taken after click the save button

























Solution:

Then I resolved this issue be replacing height and width as 0 in the SP Model Dialog option

var options = { url: addSectionUri, width: 0, height: 0, showMaximized: true, title: "Test Page" };

Issue 3:

In the above snap, you can see that the validation message placed two times for the Multi Line of Text Field. This is the default behaviour of the SharePoint Multiple Lines of Text with Enhanced Rich Text mode. Now I want to fix this issue also. 

Solution:

After a very long search in Google, I get the below idea and that worked for me.
protected void Page_Load(object sender, EventArgs e)
        {
            lbnSave.Click += new EventHandler(btnSave_Click);
        }
Change the save button click event code as below
protected void btnSave_Click(object sender, EventArgs e)
        {
            //if (Page.IsValid)
            //{
                BaseFieldControl fieldControl = GetFieldControlByName("Section Content");
                if (Convert.ToString(fieldControl.Value.ToString().Trim()) == string.Empty)
                {
                    fieldControl.ErrorMessage = " ";
                    fieldControl.IsValid = false;
                }
                else
                {

                    lfiUpdateJobAid.ListItem["JobAidID"] = 1;
                    lfiUpdateJobAid.ListItem["SectionType"] = 0;
                    lfiUpdateJobAid.ListItem["IsDeleted"] = 0;

                    lfiUpdateJobAid.Web.AllowUnsafeUpdates = true;
                    lfiUpdateJobAid.ListItem.Update();
                    lfiUpdateJobAid.Web.AllowUnsafeUpdates = false;


                    Response.Write("<script language='javascript'>window.parent.location.href = window.parent.location.href</script>");
                }
            //}
        }
Add the new method
protected BaseFieldControl GetFieldControlByName(String fieldNameToFind)
        {
            BaseFieldControl baseField = null;
            foreach (Control control in Page.Validators)
            {
                if (control is BaseFieldControl)
                {
                    baseField = control as BaseFieldControl;
                    String fieldName = baseField.FieldName;
                    if ((fieldName == fieldNameToFind))
                    {
                        return baseField;
                    }
                }
            }
            return baseField;
        }
Refer the below snap

















See Application Page in SharePoint Model Dialog Box - Part II for complete code for this along with the Field setting changes in LFI.