niedziela, 21 czerwca 2015

Create SendTo connection programmatically

private const string CONTENT_ORGANIZER_URL = "/_vti_bin/officialfile.asmx";

/// To run this code without Access Denied error, RemoteAdministratorAccessDenied must be set False. Do it with PowerShell:
/// $contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
/// $contentService.RemoteAdministratorAccessDenied = $false
/// $contentService.Update()
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWebApplication webapp = newRC.WebApplication;
       var newhost = new SPOfficialFileHost(true);
       newhost.OfficialFileUrl = new Uri("url of site with content organizer feature on" + CONTENT_ORGANIZER_URL);
       newhost.OfficialFileName = "Your connection name";
       newhost.Explanation = "Your connection description";
       newhost.ShowOnSendToMenu = false;
       newhost.Action = SPOfficialFileAction.Move;
webapp.OfficialFileHosts.Add(newhost);
webapp.Update();
});


Code snippet adding javascript that maximizes dialog window

if (SPContext.Current.IsPopUI)
{
   if (!Page.ClientScript.IsClientScriptBlockRegistered(GetType(), "ScriptWinMax"))
   {
      string script = @"function _maximizeWindow() {
         var currentDialog = SP.UI.ModalDialog.get_childDialog();
         if (currentDialog != null && !currentDialog.$S_0)
            currentDialog.$z();
         }       
         ExecuteOrDelayUntilScriptLoaded(_maximizeWindow, 'sp.ui.dialog.js');";

      Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptWinMax", script, true);
   }
}

jQuery 'Hello world' snippet


<script type="text/javascript">
   $(document).ready(function () {
      // simple test jquery is here
      $("#hello").html("Hello World by JQuery");
      });
   });
</script>

<div id="hello"></div>

Code sample of using ListViewWebPart

Application Page:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
   <asp:UpdatePanel ID="panelLV" runat="server" UpdateMode="Conditional"></asp:UpdatePanel>
</asp:Content>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   { 
      createLVWP();
   }
}

private void createLVWP()
{
   SPWeb web = SPContext.Current.Web;
   SPList list = web.GetList(
         SPUrlUtility.CombineUrl(web.ServerRelativeUrl, myListUrl));

   lvwp = new ListViewWebPart();
   lvwp.ListName = list.ID.ToString("B").ToUpper();
   lvwp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
   lvwp.ChromeType = PartChromeType.None;
   
   filterLVWP();
   this.panelLV.ContentTemplateContainer.Controls.Add(lvwp);
}

private void filterLVWP()
{
   string query = string.Format(
@"<Contains>
<FieldRef Name='myFieldName' /><Value Type='Text'>{0}</Value>
</Contains>", myFieldValue);

   XmlDocument doc = new XmlDocument();
   doc.LoadXml(lvwp.ListViewXml);
   XmlNode queryNode = doc.SelectSingleNode("//Query");
   XmlNode whereNode = queryNode.SelectSingleNode("Where");
   if (whereNode != null)
      queryNode.RemoveChild(whereNode);

   XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "Where", String.Empty);
   newNode.InnerXml = query.ToString();
   queryNode.AppendChild(newNode);
   lvwp.ListViewXml = doc.OuterXml;
}

How to use UpdatePanel with LVWP in SharePoint 2010 WebPart?

This is example of classic Web Part (i.e. not Visual Web Part) with UpdatePanel and ListViewWebPart put on it.

First assure that you have this using statement:
using System.Web.UI;
and you reference in your project System.Web.Extensions library. Otherwise you won’t be able to use UpdatePanel control.
Here is the sample WebPart class:

[ToolboxItemAttribute(false)]
public class MyWP : System.Web.UI.WebControls.WebParts.WebPart
{
    TextBox txtExample1;
    TextBox txtExample1;
    ListViewWebPart lvwp;
    SPList list;
    UpdatePanel panelMain;
   
    protected override void CreateChildControls()
    {
        panelMain = new UpdatePanel();
        panelMain.UpdateMode = UpdatePanelUpdateMode.Conditional;

        txtExample1 = new TextBox();
        txtExample2 = new TextBox();

        list = SPContext.Current.Web.GetList(SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, "Lists/MyList"));
        lvwp = new ListViewWebPart();
        lvwp.ListName = list.ID.ToString("B").ToUpper();
        lvwp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
        lvwp.ChromeType = PartChromeType.None;

        Controls.Add(new LiteralControl(" Label1: "));
        Controls.Add(txtExample1);
        Controls.Add(new LiteralControl(" Label2: "));
        Controls.Add(txtExample1);
        panelMain.ContentTemplateContainer.Controls.Add(lvwp);
        this.Controls.Add(panelMain);
    }
}



czwartek, 10 kwietnia 2014

Visual Studion: Install to GAC on Post Build event

In Visual Studio 2012:
"$(FrameworkSDKDir)bin\NETFX 4.0 Tools\gacutil.exe" /i "$(TargetPath)" /f

In Visual Studio 2010:
"$(FrameworkSDKDir)bin\gacutil.exe" /i "$(TargetPath)" /f

Change rendering of the List using XSL

I have a list definition in Visual Studio. Now I want to modify the rendering of the list views using XSL.
First I point my custom xsl file in the XslLink attribute in the list Schema.xml file:

<XslLink Default="TRUE">CustomLibrary.xsl</XslLink>

MailType is a custom column of type Choice and has the following options to choose: In, Out, Other.
I’d like to change two things:
  •  the way its values are displayed in the ListView: show icons instead of text
  • the column header of the ListView: instead of the default DisplayName, I want custom text “In/Out”


Here is the XSL file:

<xsl:stylesheet
       xmlns:x="http://www.w3.org/2001/XMLSchema"
       xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt"
       xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:msxsl="urn:schemas-microsoft-com:xslt"
       xmlns:SharePoint="Microsoft.SharePoint.WebControls"
       xmlns:ddwrt2="urn:frontpage:internal"
       xmlns:o="urn:schemas-microsoft-com:office:office">

<xsl:include href="/_layouts/xsl/main.xsl"/>
       <xsl:include href="/_layouts/xsl/internal.xsl"/>

       <xsl:template name="FieldRef_header.MailType" match="FieldRef[@Name='MailType']" mode="header">
             <th nowrap="nowrap" scope="col" onmouseover="OnChildColumn(this)">
                    <xsl:attribute name="class">ms-vh2</xsl:attribute>
                    <xsl:call-template name="dvt_headerfield">
                           <xsl:with-param name="fieldname">
                                  <xsl:value-of select="@Name"/>
                           </xsl:with-param>
                           <xsl:with-param name="fieldtitle">
                                  <xsl:value-of select="'In/Out'"/>
                           </xsl:with-param>
                           <xsl:with-param name="displayname">
                                  <xsl:value-of select="@DisplayName"/>
                           </xsl:with-param>
                           <xsl:with-param name="fieldtype">x:string</xsl:with-param>
                    </xsl:call-template>
             </th>
       </xsl:template>


<xsl:template name="FieldRef_body.MailType" match="FieldRef[@Name='MailType']" mode="body">
             <xsl:param name="thisNode" select="."/>
             <xsl:choose>
                    <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'In'">
                           <img src="/_layouts/images/gbwwain.png" alt="Typ: {$thisNode/@MailType}" title="{$thisNode/@MailType}" />
                    </xsl:when>
                    <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'Out'">
                           <img src="/_layouts/images/gbwwaoof.png" alt="Typ: {$thisNode/@MailType}" title="{$thisNode/@MailType}" />
                    </xsl:when>
                    <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'Other'">
                           <img src="/_layouts/images/generaldocument.gif" alt="Typ: {$thisNode/@MailType}" title="{$thisNode/@MailType}" />
                    </xsl:when>
                    <xsl:otherwise>
                           <span></span>
                    </xsl:otherwise>
             </xsl:choose>
       </xsl:template>
</xsl:stylesheet>

The above file needs to be deployed to the {SharePointRoot}\Template\Layouts\XSL\ folder.

Problem during deployment of BDC Model

First thing to check is Feature1.Template.xml. Chances are it lacks SiteUrl property. Here is example of correct xml code:
<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/">
  <Properties>
    <Property Key='SiteUrl' Value='http://...'/>
  </Properties>
</Feature>

How to hide Ribbon items

The Ribbon on the SharePoint Forms supports customization of the default tabs, groups, and controls.
In order to customize Ribbon item, you need to know the specific identifier (ID).
The IDs can be found in the CMDUI.xml file in the …\14\TEMPLATE\GLOBAL\XML directory or you can see them here: http://msdn.microsoft.com/en-us/library/ee537543.aspx
Here is the example of how to hide some ribbon items in the form’s code-behind:
protected void Page_Load(object sender, EventArgs e)
{
  SPRibbon rib = SPRibbon.GetCurrent(this);
  if (rib != null)
  {
    rib.TrimById("Ribbon.ListForm.Edit.Actions.DeleteItem");
    rib.TrimById("Ribbon.ListForm.Edit.Actions.EditSeries");
    rib.TrimById("Ribbon.ListForm.Edit.Actions.ClaimReleaseTask");
    rib.TrimById("Ribbon.ListForm.Edit.Actions.DistributionListsApproval");       
  }
}

czwartek, 21 listopada 2013

Change server name on which SharePoint is installed

It may be necessary e.g. when you create new VM with SharePoint as a copy of the existing one.
Use old stsadm tool to achieve the goal:

stsadm -o renameserver -oldservername <current name of the server> -newservername <new name for the server> 

poniedziałek, 18 listopada 2013

IIS configuration for debugging

ASP.NET  > .NET Compilation

Debug: TRUE
Default Language: C#

IIS > ASP

Enable Server-side Debugging: TRUE

Directly in web.config file

CallStack="true"
CustomErrors mode="Off"

Polskie znaki Ł i Ś

W pliku
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1045\FORM.js
zamienić
L_InsertCellLeftKey_TEXT=”L”   na   L_InsertCellLeftKey_TEXT=”false”
oraz
L_SplitCellKey_TEXT=”S”   na   L_SplitCellKey_TEXT=”false”

wtorek, 12 listopada 2013

Add and deploy solution with PowerShell

Add-SPSolution -LiteralPath "<path>\MySolution.wsp" | Out-Null
echo " > Adding MySolution..."
start-sleep -s 10
$sln = get-spsolution -identity MySolution.wsp
Install-SPSolution -Identity $sln -GACDeployment
while($sln.Deployed -eq $false) {
echo " > Deploying in progress..."
start-sleep -s 10
}
echo "MySolution is deployed."
Enable-SPFeature -Identity "MyFeatureName" -Url "<my site url>"

Need to know what exactly is your feature name? This command will display all web-scoped features:

Get-SPFeature | Where-Object { $_.Scope -eq "Web" } | Format-Table -Property DisplayName -AutoSize

Retrack solution with PowerShell

Set-ExecutionPolicy unrestricted
echo " "
echo "MySharepointSolution"
$sln = get-spsolution -identity MySharepointSolution.wsp
uninstall-spsolution -identity MySharepointSolution.wsp -confirm:$false
echo "Started solution retraction..." 
while($sln.JobExists) {
echo " > Working..."
start-sleep -s 10 
}
remove-spsolution -identity MySharepointSolution.wsp -confirm:$false
echo "Removed MySharepointSolution"
echo " "

środa, 30 października 2013

Make Visual Studio to add .dll to GAC after each build

Go to Project > Properties and enter the following into the Post-build event command line:
(on Windows Server 2012)
"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\gacutil.exe" /i
"$(TargetPath)" /f

(on Windows Server 2008)
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe" /i "$(TargetPath)" /f

Remember to:
  • run Visual Studio as Administrator
  • sign the assembly

wtorek, 22 października 2013

Replace columns in DataTable and by the way insert at specified position (code snippet)



DataTable table = GetSomeDataTable();

table.Columns.Add("NewNumber", typeof(int)).SetOrdinal(table.Columns["OldColumn1"].Ordinal);
table.Columns.Add("NewText", typeof(string)).SetOrdinal(table.Columns["OldColumn2"].Ordinal);

foreach (DataRow row in table.Rows)
{
  row["NewNumber"] = Transform1(row["OldColumn1"]);
  row["NewText"] = Transform2(row["OldColumn2"]);
}

table.Columns.Remove("OldColumn1");
table.Columns.Remove("OldColumn2");


poniedziałek, 23 września 2013

SharePoint user - when there are changes in AD

When some user data change in AD (e.g. last name) this change in most cases is not properly synchronized to SharePoint site collection.
The following Power Shell commands may help:

$user = get-spuser -Identity domain\username -Web http://server:port
Set-SPuser -Identity $user -SyncFromAD

Sadly it doesn't help in case an account name in AD has been changed. Then we have an orphaned user situation and the solution is to delete the account in SharePoint.
If it's only one site collection with couple of users, the quick way is to do it manually via Site collection - go to this page: http://sitecollection/_catalogs/users/simple.aspx

wtorek, 10 września 2013

Przeniesienie SharePoint Server 2013 na nową maszynę wirtualną

Na poprzedniej maszynie:


  1. Sporządzić listę baz danych używanych przez SharePoint server: Central Administration -> Upgrade and Migration -> Review database status
  2. Shutdown IIS
  3. Zatrzymać wszystkie windows services związane z SharePoint-em.

Przenosiny:


  1. Przenieść wszystkie bazy danych na nowy SQL server (Backup+Restore)
  2. Przenieść obraz maszyny wirtualnej z SharePoint server. Jeśli była to instalacja SharePoint+SQL Express na jednej maszynie, poprzedni punkt jest oczywiście zbędny. 

Na nowej maszynie:

  1. Uruchomić Sql Server Configuration Manager w celu zdefiniowania aliasów. Należy utworzyć identyczne aliasy dla SQL Native Client [VERSION] Configuration (dla 32 i 64 bitowego):
    - w polu Alias Name wpisać nazwę Sql Servera z poprzedniej maszyny,
    - skopiować nazwę do pola Server i zmodyfikować wpis o nazwę bieżącej maszyny.
  2. Aby aliasy działały, trzeba używać protokołu TCP/IP. W Sql Server Configuration Manager wejść do SQL Server Network Configuration>Protocols for SHAREPOINT. TCP/IP powinien być włączony a Shared Memory wyłączony.
  3. Wykonać restart maszyny
  4. Uruchomić sharepoint-owe windows services,  
  5. Odszukać windows service SQL Server Browser i uruchomić/upewnić się że działa.
  6. Sprawdzić czy SharePoint łączy się z właściwym serwerem bazy danych za pomocą procedury składowanej sp_who,
  7. Należy zmienić nazwę serwera ShaerPointa za pomocą programu stsadm.exe. Dla wersji 2013 znajduje się on w folderze: C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN.
    Polecenie zmiany nazwy serwera:
    stsadm -o renameserver -oldservername <YourOldServerName> -newservername <YourNewServerName>

czwartek, 23 maja 2013

Enable Session State in Sharepoint 2013

1. Run in PowerShell:
Enable-SPSessionStateService –DatabaseName "<your database name>"
or, if you don't mind guids in database names:
Enable-SPSessionStateService -DefaultProvision

2. Open web.config of the WebApplication where you want SessionState to be enabled and change line
<pages enableSessionState="false" (...)
to
<pages enableSessionState="true" (...)

3. Restart IIS