Sunday, 21 February 2016

PowerShell Command

Activate site collection feature

$site = Get-SPSite http://sp2010
 Enable-SPFeature -Identity “FeatureName” -Url $site.Url
 $site.Dispose()





Activate site collection features for all site collections in a Web Application 

$webApp = Get-SPWebApplication -Identity http://sp2010
 $webApp | Get-SPSite -limit all | ForEach-Object {Enable-SPFeature -Identity “FeatureName” -Url $_.Url}



Activate site feature 

$web = Get-SPWeb http://sp2010
 Enable-SPFeature -Identity “FeatureName” -Url $web.Url
 $web.Dispose()



Backup of site

Backup-SPSite -Identity "http://myspsite" -Path "C:\backups\myspsite.bak" -Force -Confirm:$False


Restore of site 

Restore-SPSite "http://myspsite:81" -Path C:\backups\myspsite-81.bak -Force -Confirm:$False



backup-spsite
identity http://server:site/
path c:\folder\filename.bak


export-spweb
identity http://server/site
path c:\folder\filename.cmp


import-spweb
identity http://server/restoresite
path c:\folder\filename.cmp

restore-spsite
identity http://server:site/
path c:\folder\filename.bak


Set Custom Message  for Access Denied

Set-SPCustomLayoutsPage -Identity AccessDenied 
-RelativePath "/_layouts/1033/Custom_Page.html" 
-WebApplication "http://indel3003:8004/"


Get SPLog Using PowerShell

Get-SPLogevent -starttime (get-date).addminutes(-20) | where-object {$_.correlation -eq "bd76559d-84a4-d0d9-a606-c30fe16cad3c"} | fl message > c:\users\userName\desktop\errors.txt



Change Database Instance 

$db = get-spdatabase -identity 04d5b4bc-5341-4388-a870-7922a01928fe
$db.ChangeDatabaseInstance(“<YourNewServer\InstanceNameHere”)
$db.Update()

Write-Host $db.DatabaseConnectionString


ReadFromInfoPathForm PRogramatically

        /// <summary>
        /// Get Coma delimitated value set form InfoPath form item
        /// </summary>
        /// <param name="url">Site URL for the InfoPath form library</param>
        /// <param name="InfoPathFormLibraryName">InfoPath form library Name</param>
        /// <param name="itemID">InfoPath form library item</param>
        /// <returns>Coma delimitated value set</returns>
private static string ReadFromInfoPathForm(string url, string InfoPathFormLibraryName, int itemID)
        {
            string output = string.Empty;
            //Open site which contains InfoPath form library
            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Open InfoPath form library
                    SPList list = web.Lists[InfoPathFormLibraryName];
                    //Get Correspondent list item
                    SPListItem item = list.GetItemById(itemID);
                    //Read InfoPath from
                    SPFile infoPathFrom = item.File;
                    //Get xml Transformation
XmlTextReader infoPathform = new     XmlTextReader(infoPathFrom.OpenBinaryStream());
                    infoPathform.WhitespaceHandling = WhitespaceHandling.None;
                    string nodeKey = string.Empty;

                    //Read each node in InfoPath
                    while (infoPathform.Read())
                    {
                        if (!string.IsNullOrEmpty(infoPathform.Value))
                        {
                            switch (nodeKey)
                            {
                                #region Assigning values
                                case "my:txtFistName":
                                case "my:txtLastName":
                                case "my:txtEmailAddress":
output = string.Concat(output, nodeKey.Length > 3 ? nodeKey.Substring(3) : nodeKey, "=", infoPathform.Value, ",\n");
                                    break;
                                #endregion
                            }
                        }
                        nodeKey = infoPathform.Name;
                    }
                }
            }
            return output;
        }


My First Customized XSLT in sharepoint

<xsl:stylesheet version="1.0"

              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

              xmlns:msxsl="urn:schemas-microsoft-com:xslt"

              exclude-result-prefixes="msxsl" xmlns:ddwrt2="urn:frontpage:internal">
<xsl:output method='html' indent='yes'/>
  <xsl:template match='dsQueryResponse'>
<table id="tbl1" cellpadding="10" cellspacing="0" border="1" style="padding:25px;">
<tr>
<td>Asset Information</td></tr>
<xsl:apply-templates select='Rows/Row'/>
</table>
</xsl:template>
  <xsl:template match='Row'>
<tr>
 <xsl:choose>
              <xsl:when test="position()=1">
            <td>
<b>Full Name :</b><xsl:value-of select="@FullName"></xsl:value-of><br />
</td>
 </xsl:when>
<xsl:otherwise>
<td>
<b>Full Name :</b><xsl:value-of select="@FullName"></xsl:value-of><br />
</td>
              </xsl:otherwise>
  </xsl:choose>
</tr>
</xsl:template>

</xsl:stylesheet>


How to write a log in txt File

Using System.Diagnostic;

 public void WriteLogg(string errorDescription)
        {
            System.IO.StreamWriter objWriteLog = System.IO.File.AppendText("C:\\temp" + "\\log.txt");
            try
            {
                FileInfo fileInfo = new FileInfo("C:\\temp\\log.txt");
                if (!fileInfo.Exists)
                {
                    File.Create("C:\\temp\\log.txt");
                }
                objWriteLog.WriteLine("Date and Time : " + DateTime.Now.ToString());
                objWriteLog.WriteLine("errorDescription : " + errorDescription);

            }
            catch (Exception ex)
            {
                EventLog eventLog = new EventLog();
                eventLog.Source = "DocEvent";
                eventLog.WriteEntry(errorDescription + "- er: " + ex, EventLogEntryType.Warning);
            }
            finally
            {
                objWriteLog.Close();
            }
        }

Show XSLT in Table Format new Template

<Xsl>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
              exclude-result-prefixes="msxsl" xmlns:ddwrt2="urn:frontpage:internal">
<xsl:output method='html' indent='yes'/>
  <xsl:template match='dsQueryResponse' xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:ghost="" xmlns:ddwrt2="urn:frontpage:internal">

<table id="tbl1" cellpadding="0" cellspacing="0" border="0" style="padding:0px;" class="tableRound" width="1000px">
<tr>
<td style="width:1000px">
<div style="width:1000px; position:relative;vertical-align:top;">
<xsl:apply-templates select='Rows/Row'/>
</div></td></tr>
</table>
</xsl:template>


<xsl:template match='Row'>


<div style="float:left; vertical-align:top; background-color:transparent; width:180px; height:70px; padding-bottom:0px;">
<div style="float:left; width:150px;">

<a class="className" target="_blank">
<xsl:attribute name="href">
<xsl:value-of select="@URL"></xsl:value-of>
</xsl:attribute>
<xsl:value-of select="@URL.desc"></xsl:value-of>
</a>


</div>
</div>

</xsl:template>

</xsl:stylesheet></Xsl>

Send an email with attachment from sharepoint List/Library

using System.Net.Mail;
using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                     
                        MailMessage message = new MailMessage();
                        //Get the Sharepoint SMTP information from the //SPAdministrationWebApplication
                        message.From = new MailAddress(SPAdministrationWebApplication.Local.OutboundMailSenderAddress.ToString());
                        message.To.Add(new MailAddress("user@gmail.com"));
                        message.IsBodyHtml = true;
                       //Set the subject and body of the message
                        message.Body = "Hi there, check out the attachment";
                        message.Subject = "Sent Attachment";
                        //Get the Document Library from where you want to sed the attachment
                        SPList library = web.Lists["MyDocuments"];
                        //Get the Url of the file to be sent as an attachment
                        string strUrl = "http://siteUrl/MyDocuments/Configuring Database Mial  SQL server 2008.doc";
                        //Get the file to be sent as an attachment
                        SPFile file = library.ParentWeb.GetFile(strUrl);
                        //Add the attachment
                        message.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name));
                         //Create the SMTP client object and send the message
                        SmtpClient smtpClient = new SmtpClient(SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address);
                        smtpClient.Send(message);


                        web.AllowUnsafeUpdates = false;
                    }

Send Mail Using Sharepoint Utilities

using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;

public void SendMailUsingUtility(SPWeb web)
        {
            StringDictionary headers = new StringDictionary();
            headers.Add("to", "abc@abc.com");
            headers.Add("cc", "abc@abc.com");
            headers.Add("bcc", "abc@abc.com");
            headers.Add("from", "abc@abc.com");
            headers.Add("subject", "Mail Using Utility");
            headers.Add("content-type", "text/html");

            string bodyText = "body text goes here !";

            SPUtility.SendEmail(web, headers, bodyText.ToString());
        }

remove ribbon in sitepage in popup

 <style type="text/css">
    .ms-dialog #s4-ribbonrow, .ms-dialog .ms-cui-topBar2, .ms-dialog .s4-notdlg, .ms-dialog .s4-pr s4-ribbonrowhidetitle, .ms-dialog .s4-notdlg noindex, .ms-dialog #ms-cui-ribbonTopBars, .ms-dialog #s4-titlerow, .ms-dialog #s4-pr s4-notdlg s4-titlerowhidetitle, .ms-dialog #s4-leftpanel-content {display:none !important;}
    .ms-dialog .s4-ca{margin-left:0px !important; margin-right:0px !important;}
    </style>

Refresh Page After Submition Popup




<script>
var pathh='/Lists/ListName/Item/newifs.aspx';

function ShowDialog()
{

var options = {
url:pathh,
autoSize:true,
allowMaximize:true,
title: 'RequestName',
showClose: true,
 dialogReturnValueCallback:Function.createDelegate(null, CloseCallback)
};

var dialog = SP.UI.ModalDialog.showModalDialog(options);
}
function CloseCallback(result, target) {
        location.reload(true);
    }
</script>
<a href="javascript:ShowDialog()">Add New Request</a>










put alternate color row wise on condition base in LiView Webpart

<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("makeAlternateColor()");

function makeAlternateColor()
{
var table = document.getElementById("Dashboard"); //Get the SharePoint List view's Table id using Firebug or IE Developer Toolbar's help and replace "Dashboard". Otherwise this code wont work!
var rows = table.getElementsByTagName("tr");
//manipulate rows
for(i = 0; i < rows.length; i++)
{
if(i % 2 == 0)
{
rows[i].className = "even";
}else
{
rows[i].className = "odd";
}
}
}
</script>
<style type="text/css">
.odd
{
background-color: white;
}
.even
{
background-color: yellow;
}
</style>