Sharepoint 2013 Search Query Rules

SharePoint 2013 has re-architected Search, removing the differentiation between Enterprise Search and FAST Search. The single powerful Enterprise Search functionality in SharePoint 2013 now provides an extended range of search options for intranet search and people search, and a platform to build search-driven applications.

Sharepoint 2013 has introduced new search features listed below:

  • Query rules are introduced that enable the query engine to act on what it interprets or infers about the query intent.
  • The Search service application now performs analytics tasks that were the job of the Web Analytics service in SharePoint 2010.
  • The Search service now includes a continuous crawl option as an alternative to incremental crawls.
  • SharePoint 2013 Search includes relevance enhancements, including promoted results defined by query rules, result blocks showing groups of related results, and relevance adjustments to improve result ranking.
  • Result sources now replace both federated locations and search scopes.

We will look into detail about Sharepoint 2013 Search Query Rules.

Sharepoint 2013 Search Query Rules:

Query rules are a new feature in SharePoint Server 2013 that have replaced search keywords, which have been deprecated. The difference between the two is that query rules return results that may be relevant to the user query, whereas search keywords promote only one specific result set. Query rules, which execute at the site collection level, can enable a single user search request to trigger multiple queries and, therefore, multiple
Results sets.
Query rules are a function of a site collection Search configuration, which is found on the Site Settings page. A Query rule is made up of three components:

  1. Query Condition:  Query condition defines the context in which the query becomes active, such as when a query:
    • Contains a specific word or words.
    • Contains a word that is specific to a dictionary.
    • Contains an action word that matches a specific phrase or term set.
    • Is common in a different source.
    • Results include a common result type.
  2. Query Action: Query Action defines actions  that should occur when a condition is met. These actions include:
    • Assigning a promoted result (similar to a Best Bet in SharePoint Server 2010).
    • Creating and displaying a result block.
    • Changing the query that returns the core results.
  3. Publishing Option:Publishing option decides when a query is used. This is particularly useful in commerce sites, Because the publishing options can set a time period on when a rule is available, such as special offer events or sales.

There are several query rules available out-of-the-box with SharePoint 2013. In an environment that is upgrading from SharePoint Server 2010, SharePoint Server 2013 automatically migrates all search keywords to query rules.

We will look into configuring Sharepoint 2013 Enterprise Search using Query Rules in upcoming blogs.

Import-Export Meta Data Taxonomy Terms in SharePoint 2010/SharePoint 2013

Hi,

I have made one window form application that providing export Meta Data Taxonomy Terms from Terms Set Group and also be providing import terms functionality in application.
When you run the project or Application of ImportExportSPTerm Project form and form look like below.

Download Source Code Over Here..

Export Terms
When you export terms from Managed Metadata Service on that required to given fours options on application.
Location Path (give directory Path where xml will be store),Web Application URL, Group Name, Termsetname.
Here is I am going to export terms in XML format. So my Taxonomy Group Name is : Intranet and Term Set Name is : Country and there are some Terms

So I want to export below Terms Group with terms.

Export Terms will be done on TermsBK folder of C:\ Drive.

XML Export Format like this:

XML
<?xml version="1.0" encoding="utf-16" ?>
<Groups>
 <Group Name="Intranet">
  <TermSet Name="Country" NameFr="">
    <Terms>
      <Term Name="USA">
        <Labels>
          <Label lcid="1033" Name="USA" Description="" />
        </Labels>
      </Term>
      <Term Name="CANADA">
        <Labels>
          <Label lcid="1033" Name="CANADA" Description="" />
        </Labels>
       </Term>
      <Term Name="INDIA">
        <Labels>
          <Label lcid="1033" Name="INDIA" Description="" />
        </Labels>
       </Term>
     </Terms>
    </TermSet>
  </Group>
</Groups>

Import Terms

For Import You should follow same XML formatting I have describing on exporting terms so code should be worked.

Problem to getting  Termstore??

TaxonomySession session = new TaxonomySession(site);
// 1st way;
termStore = session.TermStores["Managed Metadata Service"];
// 2nd way;
// termStore = session.DefaultKeywordsTermStore; //Try session.DefaultSiteCollectionTermStore

I have used static TermStore name “Managed Metadata Service”. You can change as on your services name. New comers getting problem to Term Store from TexonomySession. Below couple of link to be helpful.

Is it Work in SharePoint 2013??

Source Code is Okay with SharePoint 2013. problem is in Target Framework of Window Application. you need to few steps to working on SharePoint 2013.

1) Open Source code on Visual Studio 2012.
2) right click on project > Properties > Target Framework to 4.5.

now build project than Hit F5. enjoy…. :)

Hope it helps!!!

SharePoint 2010: PDF Open in browser Instead of Downloaded

Hi,
There are two to prevent PDF downloaded and open in directly Browser.

Using OOTB :

Sweet steps from Central Administration.

1) Open Central Administration Site
2) Click Application Management–> Manage WebApplication
3) Select the required Web Application name, it will enable options for WebApplicaiton in the ribbon.
4) Click on the General Settings, or chose the first option of the General Settings in the drop down list
5) It will open the model dialogue, scroll down to the Browser file handling. Select Permissive Option.

Select Okay. That’s It!!!!!!!

Bad advice! You should not just blindly enable permissive mode.

PDF allows for Javascript execution, and though to some degree the threath model is the same as with SP2007, CLient object model makes it a lot easier to create potential malicious code in PDF’s.

Read a thorough post of the potential dangers here.

Using PowerShell

We can enable to open pdf directly on browser using Powershell command. The PowerShell commands to do this is fairly straightforward:

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$webApp = Get-SPWebApplication “http://contoso.com/”

If($webApp.AllowedInlineDownloadedMimeTypes -notcontains "application/pdf")
  {
    Write-Host -ForegroundColor White "Adding PDF MIME Type..."
    $webApp.AllowedInlineDownloadedMimeTypes.Add("application/pdf")
    $webApp.Update()
    Write-Host -ForegroundColor White "Added and saved."
} Else {
    Write-Host -ForegroundColor White "PDF MIME type is already added."
}

after run above powershell using SharePoint Management Shell you can able to see PDF in broswer.

hops it helps!!

Column ordering in SharePoint 2010

Hi,

The default order of columns in New/Edit forms for lists and document libraries is typically the order they are added. In many cases you may want to change this order, or to remove columns from these forms.
pretty and simple way using SharePoint Providing OOTB for ordering the Column.

Steps:

1) Open the list and select Settings + List Settings
2) on list setting page you can see column ordering link below of columns sections.

3) click on column ordering link and set order on your field

But If want to hide column ordering link or if enable your Content Type of list/library than column ordering does not able to see above steps.

1) Open the list and select Settings + List Settings
2) Select Advanced settings
3) Click Yes for “Allow management of content types” and then click OK.
4) there will be see new section content Types on your list setting page.

below screenshot i have used custom list definition with custom site content Types that’y my custom name is TimeKeeper.

5) select your content Types.in content type there would be link column order that ordering your field.

I know below all steps are easy for end users. but if you want to doing using powershell than…. :)

PowerShell :

#####################################################################################

# eg : 1st ways: .\ColumnOrdering.ps1 -weburl "http://spdev/" -listname "TimeKeeper" -contentTypename "Item" -$fieldStaticNameColl "Title,CAALastName"
# 2st ways(Perticular Field): .\ColumnOrdering.ps1 -weburl "http://spdev/" -listname "TimeKeeper" -contentTypename "Item" -SpecificCol true -fieldInternalName "Title" -field0BasedIndex "1"
###################################################################################

param(
[string]$weburl=$(Throw "String Parameter missing: $weburl"),
[string]$listname=$(Throw "String Parameter missing: $listname"),
[string]$contentTypename =$(Throw "String Parameter missing: $listname"),
[switch]$SpecificCol,
[string]$field0BasedIndex,
[string]$fieldInternalName,
[string]$fieldStaticNameColl

)

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
   {
      Add-PSSnapin "Microsoft.SharePoint.PowerShell"
   }

#get spsite from url
$site = new-Object Microsoft.SharePoint.SPSite($weburl)
$currentweb = get-spweb $weburl
#$web = $currentweb

  function columnordering($web)
    {

      if ($web.Lists[$listname])
          {
           $web.AllowUnsafeUpdates = $true;
           $list = $web.Lists[$listname];
           $contentType = $list.ContentTypes[$contentTypename];
           if($contentType -ne $null)
             {
               [Microsoft.SharePoint.SPFieldLinkCollection]$flinks = $contentType.FieldLinks;

               #array object
               $fieldsArray = New-Object 'System.Collections.Generic.List[string]';

               if($SpecificCol)
                 {

                  #Read all the InternalNames of the FieldLinks into a list
                  foreach($fieldLink in $flinks){
                       $fieldsArray.Add($contentType.Fields[$fieldLink.ID].InternalName);
                  }
                  if($fieldsArray.Contains($fieldInternalName)){

                      $indexFound = $fieldsArray.IndexOf($fieldInternalName)

                      #convert field0BasedIndex string to Integer coming from param.
                      [int]$FieldIndxValue = $field0BasedIndex -as [int]
                      if($indexFound -ne $FieldIndxValue )
                        {
                           $fieldsArray.RemoveAt($indexFound)
                           #insert or append the field
                           if($FieldIndxValue -le $fieldsArray.Count -1){
                              $fieldsArray.Insert($FieldIndxValue,$fieldInternalName)
                            }
                          else{
                              $fieldsArray.Add($fieldInternalName);
                            }

                     #Add the array to the reorder
                     $flinks.Reorder($fieldsArray.ToArray());
                     #Update the ContentYpe
                     $contentType.Update($false)
                     Write-Host SuccessFully set spefic Field Ordering based on argument Index on $web.Title $listname Lists -foregroundcolor green
              }
            }
       }

     else
     {

       $fieldStaticNameColl.split(',') | ForEach {
            $fieldsArray.Add($_)
        }

       #Add the array to the reorder
       $flinks.Reorder($fieldsArray.ToArray());

       #Update the ContentYpe
       $contentType.Update($false)

       Write-Host SuccessFully set Ordering on $web.Title $listname Lists -foregroundcolor green
    }

   $web.Update();
   $web.AllowUnsafeUpdates = $false
    }
  }
  #Dispose web
  $web.Dispose();
}

# call columnordering function with current web argument.
columnordering -web $currentweb

below script run two ways.
first ways :
if you want to ordering multiple column than execute ps1 file with below parameter.

.\ColumnOrdering.ps1 -weburl “weburl” -listname “listname” -contentTypename “contentTypeName” -$fieldStaticNameColl “Title,CAALastName(mutiple columns with comma-seperated)”

second ways :
if you want to ordering single column than execute ps1 file with below parameter.

.\ColumnOrdering.ps1 -weburl “http://spdev/” -listname “TimeKeeper” -contentTypename “Item” -SpecificCol true -fieldInternalName “Title” -field0BasedIndex “1″

hope it helps!!!

SharePoint 2010 Customizing Alert Notifications and Alert Templates

Hi,

There are good series of article to showing that how to Customize Alert Templates on SharePoint 2010. I have just described step by step procedure to apply our Custom Alert Templates on SharePoint 2010.

Let’s begin……

Step 1:

Add a new xml file to this folder called ‘customalerttemplates.xml’. Open the alerttemplates.xml file from C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\, copy all of its contents into your newly created customalerttemplates.xml file.

If want to master in “Alert templates” than read below articles:

Step 2:

All things are done in your custom xml file and let’s to do apply on SharePoint. So open command prompt(Run > cmd) than go to “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN” directory

stsadm -o updatealerttemplates -filename “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\ customalerttemplates.xml” -url http://contoso.com

Step 3:

IISRESET (Run > iisreset)

Step 4:

Restart SharePoint Timer Job Service.

NoteNote
for run below command u need to open Management Shell.

Start > All Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell > right click > run as Administrator

Stop SharePoint timer service
net stop “SPTimerV4″
Start SharePoint timer service
net start “SPTimerV4″

Step 5:

Hope you are done!!! But your Custom Alert Template will be able to see only Those subscriber which subscribe for list’s Alert after Applying our Custom Template.But existing subscriber (subscribe for list’s Alert before Applying our Custom Template) Will not see update Custom Template. They will see OOTB Alert Template. For that we need to Run Power Shell.

PowerShell
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
  {
     Add-PSSnapin "Microsoft.SharePoint.PowerShell"
  }
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService

$AlertsTemplateCollection = new-object Microsoft.SharePoint.SPAlertTemplateCollection($contentService)

$weburl = "http://contoso.com/Sales/"
$spWeb = Get-SPWeb -Identity $weburl
$spWeb.AllowUnsafeUpdates = $true;
$splists = $spWeb.lists
$alertslist = $splists["Tasks"]
$alertslist.AlertTemplate = $AlertsTemplateCollection["<<Your Custom Alert Template >>"]
$alertslist.Update()

$alerts = $spWeb.Alerts
# if more than 0 alerts, iterate through these alerts to see if there is one for the user

if ($alerts.Count -gt 0)
{
   foreach($alert in $spWeb.Alerts)
        {
        if (($alert.AlertTemplateName -eq "SPAlertTemplateType.Tasks") -and ($alert.ListUrl -eq "Lists/Tasks"))
           {
            echo "Updating" + $alert.AlertTemplateName
            $alert.AlertTemplate = $AlertsTemplateCollection["<<Your Custom Alert Template >>"]
            $alert.Update($false)
            echo "Updated $alert.AlertTemplateName"
          }
       }
 }
$spWeb.AllowUnsafeUpdates = $false;
$spWeb.Dispose()

Step 6:

Check Immediate Timer Job associate on your Web Application.
Browse to the Central Administration site > Monitoring > Review job definitions

Find the ‘Immediate Alerts’ time job for your web application and click on the link. (There will be one for each web application so make sure you click the correct one).If not  than execute Below commands.

In my case Immediate Timer job does not exist :( so I have run command (below command should be run on same which execute on Step1).

  1. stsadm -o setproperty -propertyname alerts-enabled -propertyvalue false -url  “http://contoso.com”
  2. stsadm -o setproperty -propertyname alerts-enabled -propertyvalue true -url  “http://contoso.com”
  3. stsadm -o setproperty -propertyname job-immediate-alerts -propertyvalue “every 2 minutes” -url yourURL
  4. stsadm -o execadmsvcjobs

Have you try to restart the timer job with the command line below? Please again follow my Step No: 4.

Your Immediate Timer job should be attached to your target webapplication. Clieck on Timerjob and trigger the ‘Run Now’ button on this page which will trigger the alert emails saving you a bit of time. (You can also configure the timer job to run more often if that suits you better)

You should now receive your custom template alert email.

Hope its helps!!!

Drop-off Library in SharePoint 2010

Brief Intro:

The Drop Off Library is created when you activate the Content Organizer feature.  As soon as you configure the Content Organizer to start routing documents (which, actually it does when you activate the feature), all uploads to the site are automatically sent to the Drop Off Library.  It is just a typical SharePoint document library with a timer job that will process outstanding items.  Whenever you create a rule and select a content type, the Content Organizer checks to see if that content type has been added to the Drop Off Library yet.  If it hasn’t, the type is added to the library so that when the edit form is displayed after an item has been uploaded, users can select any one of the content types that are used in the routing rules.

A standard document library was used because it allows one to take advantage of all the typical document library features, such as:

  • Workflow – users can start workflows on items in the Drop Off Library to approve a document, for example, before it is routed
  • Content Approval – items can be forced through a content approval process prior to it being routed
  • Check In / Check Out – allows items to stay in the Drop Off Library until all required properties for the content type have been filled out.  Once the properties are all completed though, items are routed whether or not they are checked in.
  • Alerts – get notified when a new item is added to the Drop Off Library
  • Permissions – create custom permissions for the drop off library.  If you have set the Redirect Users to the Drop Off Library property in the Content Organizer settings, then this allows you to effectively control who can upload content in the entire site, since all uploads get routed to the Drop Off Library

Configure Drop-off Library in SharePoint 2010 :

Before understand utilize Drop-Off Library also be look forward on Content Organizer Feature in SharePoint 2010.

What is Content Organizer??

The Content Organizer feature is a new routing feature that extends, enhances, and makes more broadly available the routing engine used in the Records Center site template from SharePoint 2007.  It not only allows you to automatically route documents to different libraries and folders within those libraries, it can also be used for mundane housekeeping type activities such as making sure that no folder within a document library contains more than 5000 items, for example.  When item number 5001 is added to the library, the Content Organizer can automatically create a new folder and put the document in that folder.  All of this routing and folder creation can be handled automatically without further user intervention.  After a document is uploaded and the required metadata applied, the upload form displays a Url to a document that has been routed so the user knows where to find it in the future.

Unfortunately the Content Organizer will only work on content types that are or derive from the Document content type.  So it does not work for automatically organizing large lists.

For more Information see over here: http://blogs.technet.com/b/speschka/archive/2009/10/30/sharepoint-2010-content-organizer-part-1-a-cool-new-feature-for-managing-your-content.aspx

 Activated Content Organizer

There is one feature Content Organizer exists on Scope Web Features Collection SharePoint Site.

Feature should be on http://www.contoso.com/_layouts/ManageFeatures.aspx. Activate It.

After you activate the feature there are two new menus added to the Site Administration section(http://www.contoso.com/_layouts/settings.aspx) of your site settings:  Content Organizer Settings and Content Organizer Rules.

Content Organizer Settings :  Content Organizer Settings is where you configure whether to route documents that are added to the site collection based on rules.  Any changes made here affect routing for the entire site.

Content Organizer Rules:   Content Organizer Rules is where you go to create the rules that are used when routing documents.  Any rules created here are used to route individual documents based on metadata attributes that you choose.

In addition, there is also a document library that is created when the feature is activated, called the Drop Off Library.  It is:

  • A library that users or custom code can use to submit new items that need to be routed
  • Where all uploads may be temporarily routed if so configured in the Content Organizer settings (more info on that below)
  • A temporary staging area for items that do not have all required metadata.  For example, when multiple items are uploaded to a document library they will go into the Drop Off Library by default, in a state where they are waiting to be checked in.  You need to edit the properties on the item, fill out any required properties and submit the changes in order to have the routing rules applied.

 Utility of Drop-Off-Library :

First create one new Content organizer rule that check document title. And if Document title and our defined title on our Content Organizer rule both are same than executed our Rule and Copy or Move Document to Destination Path.

Make sure we have created “Send to Connection” in Central Administration:

Go to Central Administration > General Administration Settings > Configure send to connection.

Add new Connection.

There are three options on Sent to Action. I have select move action. On that document move to destination path. If you select copy action than copy document to destination path.

What is Send to URL?

That is SharePoint OOTB web service url which you can find it out from content organizer setting on your site.

Create Content Organizer Rule:

Go to site setting > Site Administration > Content Organizer rules > Add new Item

Set proper name of your content Organizer rule. I have used DropTest.

I have set Conditions. On that when Document title will be “DocTest” than move to destination path which we have declared on path.

My Destination path is DropOffDocs.

Than Okay…

Using Programmatically Create Content Organizer Rule :

 using (SPSite osite = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb oweb = osite.OpenWeb())
                {
                    oweb.AllowUnsafeUpdates = true;

                    //We must get the EcmDocumentRoutingWeb object that corresponds to the current SPWeb
                    EcmDocumentRoutingWeb routingWeb = new EcmDocumentRoutingWeb(oweb);

                    //Get handles on the Document content type and the Shared Documents list
                    SPContentType contentTypeForRule = oweb.ContentTypes["Document"];
                    //SPList listForRule = currentWeb.Lists["Shared Documents"];

                    SPListItem listItem = listforRule.GetItemById(Itemid);

                    if (listItem.Folder != null)
                    {

                        //Create a rule object
                        EcmDocumentRouterRule newRule = new EcmDocumentRouterRule(oweb);

                        //Set the properties
                        newRule.Name = listItem.Folder.Name;
                        newRule.Description = "";
                        newRule.ContentTypeString = contentTypeForRule.Name;
                        newRule.RouteToExternalLocation = false;
                        newRule.ConditionsString = string.Format("", txtEmail.Text);
                        newRule.Priority = "5";
                        newRule.TargetPath = listItem.Folder.ServerRelativeUrl;

                        //Commit your changes
                        newRule.Update();

                    }

                }
            }

Upload Document to Drop off Library

Go to Drop off library > add new Document > title should be DocTitle.

Now see on your destination path location. Here is I have set destination path Shared Documents > DropOffDocs(Folder). So document automatically moves on that location.

That’s it!!!!!!!

See Video Link :  http://www.youtube.com/watch?v=5f4DYD1xvNA

Hope its Helps!!!!

Create custom SharePoint 2010 list form for deployment in a Visual Studio 2010 project

Hi,

Today I would like to publish Small article for How to Customize SharePoint list form using visual studio 2010.
There are two ways to customize our SharePoint 2010 list form.

1)   1st way : Here is excellent article written by ikarstein.I am always follow him update blogs and also be Big Fan ;) .

2)   2nd way I am describing over here:

My Requirement:
I have one Announcement List Template and displaying different type of Announcement. Something like

I.E Alert, InternalAnnouncement, Spotlight, New Release etc..

So on that time I have created different type of Content Types and that Content Types associate with Announcement List Template with different Designing Form Template.so Below approved better for me.

I have taken Empty SharePoint project (deploy as farm solution). My project name is : SP2010CustomListForm On this project I have create one Custom Site Content Type, Custom List Definition than inherited Content type to List Template.

Download Source Code Over Here.


Create Site Content Type :

Right click on project (SP2010CustomListForm) > Add new Item > Content Type > (Inherited from Item) > Okay

Create List Definition:

  Right click on project (SP2010CustomListForm) > Add new Item > List Definition > Provide name to Template

I am taking Template Type is Custom List also be attach
list instance for list definition. Now go on Schema.xml of MyListDef(list
definition)


Than modify list definition schema. Find it out below line on Schema.xml

XML
<ContentTypeRef ID="0x01">
        <Folder TargetName="Item" />
    </ContentTypeRef>
And Replace with your Site Content Type. For Me my Site Content Type
XML
<!-- Parent ContentType: Item (0x01) -->
  <ContentType ID="0x0100ca617ed5b05a4ded890902bbf86e3886"
               Name="MyContentType"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="FALSE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title"/>
      <FieldRef ID="{03E7B8FC-8BD8-48D9-BB07-A9FB5F86F277}" Name="MyCustom"/>
    </FieldRefs>
  </ContentType>

You can see on below screenshot of MyConentType.than I have add
XmlDocuments Element (ContentType)
on that content type.

What is XmlDocuments???

The XmlDocuments element contains a collection of XmlDocument elements. You can include custom information in content type definitions by adding special XML nodes. These XML nodes are represented by the XmlDocument element in the content type definition and can be accessed programmatically through the object model. A content type can include any number of XmlDocument elements. The contents of each XmlDocument element can conform to any given schema; they only need to be valid XML. Here is example for Item Content Type.

XML
<XmlDocuments>
          <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
            <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
              <Display>ListForm</Display>
              <Edit>ListForm</Edit>
              <New>ListForm</New>
            </FormTemplates>
          </XmlDocument>
 </XmlDocuments>

 

For more details see on MSDN(http://msdn.microsoft.com/en-us/library/aa543904.aspx)

So Finally MyContentType become like: 

Create custom list form template :
Now we have create new form template and that associate to content type for accomplish our requirement. For that we need to add User Control on Control Template that project. So right click on

Project(SP2010CustomListForm) > Add > SharePoint Mapped Folder > Template > Control Template > OK


Than right click on ControlTemplates > Add New Item > ListFormEditTemplate.ascx Again add one more User Control (ListFormEditRender.ascx) on Control Templates and render your HTML. Here screenshot of my ListFormEditRender.ascx control.

Operation on ListFormEditTemplate.ascx :  Open ListFormEditTemplate.ascx for doing register SharePoint Ribbon Toolbar below line adds on your User Control.

HTML
<%@ Register TagPrefix="wssuc" TagName="ToolBar" Src="~/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" Src="~/_controltemplates/ToolBarButton.ascx" %>

Register ListFormEditRender.ascx control on this ascx control using like:

HTML
<%@ Register TagPrefix="myCustomForm" TagName="AddForm" Src="~/_controltemplates/ListFormEditRender.ascx" %>

The templates used for the UI in the ListViewWewPart are contained in  RenderingTemplates that can be found in <SharePoint Root>\14\TEMPLATE\CONTROLTEMPLATES\DefautlTemplates.ascx. This UserControl contains 145 RenderingTemplates that are used to display fields, such as NumberField and CurrencyField, and UI for forms, such as SurveyForm or WkiEditForm. For this discussion, we are interested in the  RenderingTemplate with ID  ListForm.

RenderingTemplate ID is ListFormEdit. It’s should be unique if you want to use multiple.

HTML
<SharePoint:RenderingTemplate ID="ListFormEdit" runat="server">
    <Template>
        <span id='part1'>
            <SharePoint:InformationBar ID="InformationBar1" runat="server" />
            <div id="listFormToolBarTop">
                <wssuc:ToolBar CssClass="ms-formtoolbar" ID="toolBarTbltop" RightButtonSeparator="&amp;#160;"
                    runat="server">
                    <Template_RightButtons>
                        <SharePoint:NextPageButton ID="NextPageButton1" runat="server" />
                        <SharePoint:SaveButton ID="SaveButton1" runat="server" />
                        <SharePoint:GoBackButton ID="GoBackButton1" runat="server" />
                    </Template_RightButtons>
                </wssuc:ToolBar>
            </div>
            <SharePoint:FormToolBar ID="FormToolBar1" runat="server" />
            <SharePoint:ItemValidationFailedMessage ID="ItemValidationFailedMessage1" runat="server" />
            <table class="ms-formtable" style="margin-top: 8px;" border="0" cellpadding="0" cellspacing="0"
                width="100%">
                <SharePoint:ChangeContentType ID="ChangeContentType1" runat="server" />
                <SharePoint:FolderFormFields ID="FolderFormFields1" runat="server" />

      <!-- myCustomForm ListFormEditRender.ascx render -->
                <myCustomForm:AddForm runat="server" />
     <!-- myCustomForm ListFormEditRender.ascx render -->

                <SharePoint:ListFieldIterator ID="ListFieldIterator1" runat="server" />
                <SharePoint:ApprovalStatus ID="ApprovalStatus1" runat="server" />
                <SharePoint:FormComponent ID="FormComponent1" TemplateName="AttachmentRows" runat="server" />
            </table>
            <table cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td class="ms-formline">
                        <img src="/_layouts/images/blank.gif" width='1' height='1' alt="" />
                    </td>
                </tr>
            </table>
            <table cellpadding="0" cellspacing="0" width="100%" style="padding-top: 7px">
                <tr>
                    <td width="100%">
                        <SharePoint:ItemHiddenVersion ID="ItemHiddenVersion1" runat="server" />
                        <SharePoint:ParentInformationField ID="ParentInformationField1" runat="server" />
                        <SharePoint:InitContentType ID="InitContentType1" runat="server" />
                        <wssuc:ToolBar CssClass="ms-formtoolbar" ID="toolBarTbl" RightButtonSeparator="&amp;#160;"
                            runat="server">
                            <Template_Buttons>
                                <SharePoint:CreatedModifiedInfo ID="CreatedModifiedInfo1" runat="server" />
                            </Template_Buttons>
                            <Template_RightButtons>
                                <SharePoint:SaveButton ID="SaveButton2" runat="server" />
                                <SharePoint:GoBackButton ID="GoBackButton2" runat="server" />
                            </Template_RightButtons>
                        </wssuc:ToolBar>
                    </td>
                </tr>
            </table>
        </span>
        <SharePoint:AttachmentUpload ID="AttachmentUpload1" runat="server" />
    </Template>
</SharePoint:RenderingTemplate>
 That’s it!!! Now we need only 1 more Change.

Again Edit Schema.xml File of MyListDef(List Definition) :
Replace your

XML
<XmlDocuments>
          <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
            <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
              <Display>ListForm</Display>
              <Edit>ListFormEdit</Edit>
              <New>ListForm</New>
            </FormTemplates>
          </XmlDocument>
 </XmlDocuments>

 

  RenderingTemplate ID is  ListFormEdit replace on XMlDocument of Content Type.


Deployed your solution!!!!

 OutPut :

Are you able to see Custom Form Tempalte??
If not than

There are two very big and not well documented issues that may present themselves when using a custom RenderingTemplate. First, you may notice the default RenderingTemplate is used rather than the custom one you have created. This is because of the Inherits attribute on the ContentType. For an as yet to be explained reason, it must be either removed or set to false so the custom RenderingTemplate will be used.

Set on your Content Type attribute Inherite to “False”

Inherits=”FALSE”

Hope Its Helps!!!

Access SharePoint 2013 list item from remote apps using the cross-domain library

This article intend for:

This article helps it out to new comer when getting starting developing app on SharePoint 2013. Also be brief describe regarding auto- Hosted app in SharePoint 2013. Here I have created demo on SharePoint 2013 Online Preview and if you don’t have SharePoint 2013 Online (office 365 Preview) than visit my previous Post regarding registration. I have accomplished requirement by the help from MSDN article.

Before starting creating app on Visual studio 2012. I hope you have already installed on your machine.If not than kindly download from here. Also need to download Microsoft Office Developer Tools for Visual Studio 2012(OfficeToolsForVS2012GA.exe) or go here.

The cross-domain library is a client-side alternative in the form of a JavaScript file (SP.RequestExecutor.js) that is hosted in the SharePoint website that you can reference in your remote app.

Let’s Start….

  1. Open Visual Studio 2012 as administrator. (To do this, right-click the Visual Studio 2012 icon in the Start menu, and choose Run as administrator.)
  2. Create a new project using the App for SharePoint 2013 template.shows the location of the App for SharePoint 2013 template in Visual Studio 2012, under Templates, Visual C#, Office SharePoint, Apps.


App for SharePoint 2013 Visual Studio template

  1. Provide the URL of the SharePoint website that you want to use for debugging. Select auto- hosted or provider-hosted as the hosting option for your app.

  1. after click on finish wizard. You should your project solution explorer structure like this.

  1. Now I have created new list template with list instance.  We will do same as working in sp2010.So right click on CrossDomainAPP_CSOM > Add >  New Item > Select List

ListName : CSOMList
After selected new blank template. I have added one more field (Description) on this list.

  1.   Now go to on CrossDomainApp_CSOMWeb project and add one HTML page. I have taken CSOM.html
My HTML file is 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <div id="renderListResults"></div>
  <script src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>

  <script type="text/javascript">
  // The all  CSOMList variable is used by more than one 
  //  function to retrieve and process the results.
  var listData
  var hostweburl;
  var appweburl;
  var listname = "CSOMList";
  // Load the required SharePoint libraries
  $(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(
                getQueryStringParameter("SPHostUrl")
            );

    appweburl = decodeURIComponent( 
                getQueryStringParameter("SPAppWebUrl")
           );
   // resources are in URLs in the form:
   // web_url/_layouts/15/resource
   var scriptbase = hostweburl + "/_layouts/15/";

  // Load the js files and continue to the successHandler
  $.getScript(scriptbase + "SP.Runtime.js",
       function () {
          $.getScript(scriptbase + "SP.js",
           function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
          );

     });
 });

   // Function to prepare and issue the request to get
   //  SharePoint data
   function execCrossDomainRequest() {
        // context: The ClientContext object provides access to
        //the web and lists objects.
        // factory: Initialize the factory object with the
        //app web URL.
        var context = new SP.ClientContext(appweburl);
        var factory = new SP.ProxyWebRequestExecutorFactory(
                            appweburl
                      );
       context.set_webRequestExecutorFactory(factory);

       // Get the web and list objects
       // and prepare the query
       var web = context.get_web();
       var list = web.get_lists().getByTitle(listname);
       var camlString = "<View><ViewFields>" +
                        "<FieldRef Name='Title' />" +
                        "<FieldRef Name='CSOM_Description' />" +
                        "</ViewFields></View>";
       var camlQuery = new SP.CamlQuery();
       camlQuery.set_viewXml(camlString);
       listData = list.getItems(camlQuery);
       context.load(listData, "Include(Title, CSOM_Description)");

       //Execute the query with all the previous
       //  options and parameters
       context.executeQueryAsync(
              successHandler, errorHandler
       );
  }

  // Function to handle the success event.
  // Prints the data to the page.
  function successHandler(data, req) {
     var listDataHTML = "";
     var enumerator = listData.getEnumerator();
     while (enumerator.moveNext()) {
        var listrecords = enumerator.get_current();
        listDataHTML = listDataHTML + 
                 "<p><h1>" + listrecords.get_item("Title") +
                 "</h1>" + listrecords.get_item("CSOM_Description") +
          "</p><hr>";
      }
    $('#renderListResults').html(listDataHTML);
  }

  // Function to handle the error event.
  // Prints the error message to the page.
  function errorHandler(data, error, errorMessage) {
       document.getElementById("renderListResults").innerText = "Could not complete cross-domain call: " +   errorMessage;
  }

  // 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>
</body>
</html>

To edit the app manifest file of your App project

  • Double-click the AppManifest.xml file in app project

  • Select the HTML page you created from the Start Page drop-down menu.

In the Query String field, enter {StandardTokens}.

NoteNote
{StandardTokens} is replaced by a number of query string parameters, including SPAppWebUrl, which the HTML page uses to obtain the app web URL.

Go to Permission tab and add web > Full Control.

Right-click the AppManifest.xml file in Solution Explorer, and select View code.Copy the following app principal definition, and substitute the default.

<AppPrincipal>
    <Internal AllowedRemoteHostUrl="~remoteAppUrl"/>
</AppPrincipal>
NoteNote
The AllowedRemoteHostUrl attribute is used to specify the remote domain. The ~remoteAppUrl resolves to the remote app URL. For more information about tokens, see Explore the app manifest and the package of an app for SharePoint.
  1. Make sure that the app for SharePoint project is set as the startup project. And  Hit F5

My Output looks like:

Okay fine!!!

Where is my List??

After successfully installed app and displayed records from SharePoint list (listname : CSOMList).
Than going to searching my List on normally /_layouts/viewlsts.aspx in the URL bar. I can’t see this list on that page. I am little bit confuse afterward investigate on Google and found on excellent article written by MR.Chris.

Instead, just paste the URL of the list directly into the browser address bar after the app URL and you should be taken to your newly-provisioned list:

In app output url, it’s should be some argument like SPHostUrl, SPAppWebUrl(Decrypted Format).

You can download my stuff over here.
Hope it helps!!!!

Deploying solutions to a specific Web Application

Hi,
I have created one SharePoint project. I want to Deployed that wsp to specific Web-Application.
When I have used PowerShell for installing wsp solution to specific function using below command.

Install-SPSolution –Identity $wsp -GACDeployment -force -WebApplication "http://contoso.com"

In that time got error like this:

- This solution contains no resources scoped for a Web application and cannot be deployed to a particular Web application.

After some investigation on Google and its seem to my Package Manifest file look like this.so there are not available any SafeControl in AssemblyLocation.

<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="baa138bf-ebb3-4841-8b8c-de7a699d6b94" SharePointProductVersion="14.0">
  <Assemblies>
    <Assembly Location="SharePointProject1.dll" DeploymentTarget="GlobalAssemblyCache" />
  </Assemblies>
  <FeatureManifests>
    <FeatureManifest Location="SharePointProject1_Feature2\Feature.xml" />
  </FeatureManifests>
</Solution>

You can found it out on Project Solution > Package(Click on) > Manifest. Than when deploying this solution using visual studio 2010. And check on Central Administration > System Settings > Farm Management > Manage Farm Solutions.

my wsp delpoyed as Globally

.

What I have do so far

SharePoint checks whether there are items which have to be deployed to a specific web application when your solution is added to the solution gallery. One of the elements that SharePoint checks for are safe control entries. These have to be merged into a web.config for a specific web application. So if you add Dummy Safe Control Entry to your manifest file.
1) Open your manifest file of Package

 

2)  (+ Edit Options) Expand it. Click on Overwrite generated XML and edit manifest in the XML editor link. > Edit manifest in the XML editor.

 3)  In Edit mode <Assemblies> node look like.

<Assemblies>
    <Assembly Location="SharePointProject1.dll" DeploymentTarget="GlobalAssemblyCache" />
</Assemblies>

4) Just add dummy SafeControl to the Assembly node.

SafeControl Means??

When you solution SafeControl than registering your solution as a web application scoped solution. SharePoint checks whether there are items which have to be deployed to a specific web application when your solution is added to the solution gallery. One of the elements that SharePoint checks for are safe control entries. These have to be merged into a web.config for a specific web application.

<SafeControls>
  <SafeControl Assembly="[Assembly Name]" Namespace="[Namespace]" TypeName="*" Safe="True" />
</SafeControls>

For further details you can see here.

So Finally I have added dummy SafeControl entry to my solution and my Manifest.xml Look like this:

<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="baa138bf-ebb3-4841-8b8c-de7a699d6b94" SharePointProductVersion="14.0">
  <Assemblies>
    <Assembly Location="SharePointProject1.dll" DeploymentTarget="GlobalAssemblyCache">
     <SafeControls>
      <SafeControl Assembly="SharePointProject1,Version=1.0.0.0, Culture=neutral, PublicKeyToken=****************" Namespace="SharePointProject1" TypeName="*" />
    </SafeControls>
    </Assembly>
  </Assemblies>
  <FeatureManifests>
    <FeatureManifest Location="SharePointProject1_Feature2\Feature.xml" />
  </FeatureManifests>
</Solution>

Deployed and again check on Central Administration > System Settings > Farm Management > Manage Farm Solutions.

Hops it helps!!!

PowerShell Attach or detach content databases

This article describes how to attach or detach Microsoft SharePoint Server 2010 content databases by using the SharePoint Management Shell.

You might want to attach or detach content databases in the following situations:

  • You want to add a new content database for new site collections to keep content databases at a manageable size.
  • You have restored a content database from another farm and you want the sites that it contains to be accessible from a Web application.
  • You have archived site collections and you no longer need as many content databases. You can move the remaining site collections out of a content database and then detach the content database from the Web application. For more information, see Move site collections between databases (SharePoint Server 2010)

Here is I have done So Far

restore your content database on your SQL Server which you want to attach your web-application

for doing that first find it out current attach database name of your web application. though on
Central Administration > Application Management > Manage Content Database And select your webapplication.

suppose : ⦁ During creation “http://sp2010:9997” web application I have given content database name was “wss_content_LCWP_OldCloud”.

dismount above database using like this:
Open SharePoint Management Shell(as Administrator)

Dismount-SPContentDatabase “wss_content_LCWP_OldCloud”

Than attach your new content databases to your web-application

Mount-SPContentDatabase "" -DatabaseServer "" -WebApplication http://SiteName

For Example :

Mount-SPContentDatabase "wss_content_5000" -DatabaseServer "DBSERVERNAME" -WebApplication http://sp2010:9997 

That’s It!!!!