Wednesday, 24 February 2016

Retrive Allfiles from document library and subfolder with metadatacolumns

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

using Microsoft.Office.InfoPath;

using System.IO;
using System.Xml;
using System.Xml.XPath;

using System.Collections;
using System.Data;
using System.Data.Common;


using System.Security.Principal;
using Microsoft.SharePoint.Utilities;
namespace DeleteAllitem
{
    class Program
    {
        static List<DocumentName> doclist = new List<DocumentName>();
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://win-0c3p6kepvck:100/kkk/"))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
               
                    web.AllowUnsafeUpdates = true;
                    SPDocumentLibrary list =(SPDocumentLibrary)web.Lists["JS"];
                    SPListItemCollection  itemcoll = list.Items;
                    foreach (SPListItem  item in itemcoll)
                    {

                     
                        DocumentName d = new DocumentName
                        {
                           Name1= Convert.ToString(item["Name"]),
                           Title1=Convert.ToString(item["Title"]),
                           FileUrl=item.File.ServerRelativeUrl,
                           Department=Convert.ToString(item["Department"])
                        };
                        doclist.Add(d);
                 
                    }
                    Console.WriteLine("Please Enter FileName....");
                    string s=Console.ReadLine();
                    Console.WriteLine("Please Enter Department....");
                    string departmentt=Console.ReadLine();
                    var fileName=doclist.Where(w=>w.Name1.Contains(s) && w.Department==departmentt);
                    foreach (var c in fileName)
                    {

                        Console.WriteLine(c.Name1);
                        Console.WriteLine(c.FileUrl);
                    }
                    Console.WriteLine("end....");
                    Console.Read();




                    web.AllowUnsafeUpdates = false;
                 
                }
                site.AllowUnsafeUpdates = false;
            }
        }
        public class DocumentName
        {

            private string Name;

            public string Name1
            {
                get { return Name; }
                set { Name = value; }
            }
            private string Title;

            public string Title1
            {
                get { return Title; }
                set { Title = value; }
            }
            private string fileUrl;



            public string FileUrl
            {
                get { return fileUrl; }
                set { fileUrl = value; }
            }
            private string department;

            public string Department
            {
                get { return department; }
                set { department = value; }
            }
        }
     
         
           


    }
}

Sunday, 21 February 2016

Copy List Item Source List to Destination List

public void CopyList(SPList src)
{
    //Copy items from source List to Destination List
    foreach (SPListItem item in src.Items)
    {
        if(isUnique(item.UniqueId))
        {
          newDestItem = DestinationList.Items.Add();

          foreach (SPField field in src.Fields)
          {
             try
              {
                if ((!field.ReadOnlyField) && (field.InternalName!="Attachments"))
                  newDestItem[field.InternalName] = item[field.InternalName];
               }
             catch (Exception ex)
              {
              //you should save the "ex" somewhere to see its outputs
               ex.ToString();
              }
           }
           newDestItem.Update();  //only now you call update!
        }
       }
      } 

Delete attached Event reciver from list

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

$web = Get-SPWeb -Identity http://siteURL/
$list = $web.GetList($web.Url + "/Lists/" + "ListName")

$type = "ItemDeleting"

$numberOfEventReceivers = $list.EventReceivers.Count

if ($numberOfEventReceivers -gt 0)
{
   for( $index = $numberOfEventReceivers -1; $index -gt -1; $index–-)
   {
      $receiver = $list.EventReceivers[$index] ;
      $name = $receiver.Name
      $typ = $receiver.Type ;

      if($name -eq "EventReceiver1ItemDeleting")
      {
         $receiver.Delete()
         Write-Host "Event receiver " $name " is deleted"
      }
   }
}
else
{
   Write-Host " There is no EventReceivers of type " $type " registered for this list "
}

$web.Dispose()

Get Attached Event Reciver to List/Library

$spWeb = Get-SPWeb http://siteUrl/ ;
$spList = $spWeb.Lists["LisName"];
$spList.EventReceivers | Select Name, Assembly, Type;

Delete Hidden Feature

$feature = Get-SPFeature | ? { $_.DisplayName -eq "FeatureName_Feature1" }
 $feature.Delete()

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>

Create a DashBoard Using XSLT with Statuswise Count to Assignee

<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:key name="Grouping" match="Row" use="@AssignedTo.id" />

<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="10" cellspacing="0" border="0" style="padding:0px;" class="tableRound">
<xsl:apply-templates select='Rows/Row'/>
</table>
</xsl:template>
<xsl:template match='/' xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:ghost="" xmlns:ddwrt2="urn:frontpage:internal">
<tr>
<td style="font-weight:bold; color:#002276">Assign To</td>
<td style="font-weight:bold; color:#002276">Completed</td>
<td style="font-weight:bold; color:#002276">In Progress</td>
<td style="font-weight:bold; color:#002276">Not Started</td>
<td style="font-weight:bold; color:#002276">Waiting on someone else</td>
</tr>

<xsl:for-each select="/dsQueryResponse/Rows/Row[generate-id(.)=generate-id(key('Grouping',@AssignedTo.id))]/@AssignedTo.id">
<xsl:sort />

<tr>

<td width="58%"><xsl:value-of select="key('Grouping',.)/@AssignedTo" disable-output-escaping="yes" /></td>
<td width="10%"><xsl:value-of select="count(key('Grouping',.)[@Status='Completed'])" disable-output-escaping="yes"></xsl:value-of></td>
<td width="10%"><xsl:value-of select="count(key('Grouping',.)[@Status='In Progress'])" disable-output-escaping="yes"></xsl:value-of></td>
<td width="10%"><xsl:value-of select="count(key('Grouping',.)[@Status='Not Started'])" disable-output-escaping="yes"></xsl:value-of></td>
<td width="10%"><xsl:value-of select="count(key('Grouping',.)[@Status='Waiting on someone else'])" disable-output-escaping="yes"></xsl:value-of></td>



</tr>

</xsl:for-each>  

</xsl:template>
</xsl:stylesheet></Xsl>

Open and Close A Model Popup in sharepoint

For Open A PoPUp
<a href="javascript:SP.UI.ModalDialog.ShowPopupDialog('/sitPages.aspx', null, 500, 300);" >
Edit
 </a>

javascript:SP.UI.ModalDialog.ShowPopupDialog('PAgeAddress.aspx?ID={$thisNode/@TRFId}', null, 1000, 800);

javascript:OpenPopUpPageWithTitle('/SitePages/LeaderMessage.aspx',null,null,null,'Leader Message');


and Close A PoPUp from code behinde

public void CloseForm()
        {
            HttpContext context = HttpContext.Current;
            if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                context.Response.Flush();    
                context.Response.End();
            }
        }

Saturday, 20 February 2016

left quick bar menubar styles


.s4-ql UL.root > LI > .menu-item {

PADDING-BOTTOM: 2px;
BORDER-RIGHT-WIDTH: 0px;
OVERFLOW-X: hidden;
TEXT-TRANSFORM: capitalize;
MARGIN: 0px; MIN-HEIGHT: 19px;
 PADDING-LEFT: 10px;
 PADDING-RIGHT: 4px;
 FONT-FAMILY: Arial, Helvetica, sans-serif;
  WORD-WRAP: break-word;
   BORDER-TOP-WIDTH: 0px;
    COLOR:white;
    FONT-SIZE: 12px;
    font-weight: normal;
     BORDER-LEFT-WIDTH: 0px;
     PADDING-TOP: 8px;
        background-color:#3c8a2e;
        border-bottom:1px white solid;
}
.s4-ql UL.root > LI > .menu-item:hover{
background:#cee2cb;
color:#000;
}

BODY #s4-leftpanel {
MARGIN-TOP: 25px;
WIDTH: 150px;
 FLOAT: left;
  MARGIN-LEFT: 5px;
  border-bottom:1px #002776 dotted;
}
BODY #s4-leftpanel-content {
border:none;
}
.s4-ql UL.root UL > LI > A{
 border-bottom:1px dotted;
border-bottom-color:black;

}



How to set multiUserValueCollection in SPFieldUserValueCollection




public SPFieldUserValue ConvertLoginAccount(string userid)
        {
            SPFieldUserValue uservalue;
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser requireduser = web.EnsureUser(userid);
                    uservalue = new SPFieldUserValue(web, requireduser.ID, requireduser.LoginName);
                }
            }
            return uservalue;
        }


//user collection in array
string[] userarray = lblFunctionTeam.Text.ToString().Split(';');

                                SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
                                for (int i = 0; i < userarray.Length - 1; i++)
                                {
                                    SPFieldUserValue usertoadd = ConvertLoginAccount(userarray[i]);
                                    usercollection.Add(usertoadd);
                                }
                  //set multiuserCollection
                                item["UserCollectionField"] = usercollection;
//single user Value
  SPFieldUserValue usertoadd1= ConvertLoginAccount("userIdentityEmailOrLoginName");
    item["UserField"] =usertoadd1;

how to get user's name ,emaiid ,loginid and id from SPFieldUserValueCollection

  SPFieldUserValueCollection userFieldValueCollectionfunction =new  SPFieldUserValueCollection(web,convert.tostring(item[UserCollectionCoulmnName]));

                            foreach (SPFieldUserValue userFieldValuefunctin in userFieldValueCollectionfunction)
                            {
                                console.writeline( userFieldValuefunctin.User.Name);
                                console.writeline( userFieldValuefunctin.User.Email);
                            }

hide complete ribbon in dialog box using jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("hideItAll");

function hideItAll(){
 if(window.location.search.toLowerCase().indexOf("isdlg=1") > 0){
 $("#s4-ribbonrow").hide(); //ribbon bar
 }
}
</script>

hide cancel button in ribbon Sharepoint listItem form



<script type="text/javascript">
var elem = document.getElementById("Ribbon.DocLibListForm.Edit.Commit.Cancel-Large");
elem.style.display = "none";
setInterval(abc,3000);
function abc()
{
var x=document.getElementsByTagName("input");

for (var i=0; i < x.length; i++)
{
if (x.item(i).type=="button" && x.item(i).value=="Cancel")
{

x.item(i).style.display="none";
}
}
}

</script>

Header with Search textbox in ListView Webpart using Jquery

<script src="http://www.google.com/jsapi"></script>

<script>


google.load("jquery", "1.2.6");

google.setOnLoadCallback(function() {

$(document).ready(function()
{
jQuery.extend(jQuery.expr[':'], {
 containsIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0"
});


$("table.ms-listviewtable tr.ms-viewheadertr").each(function()
{
if($("td.ms-vh-group", this).size() > 0)
{
return;
}

var tdset = "";

var colIndex = 0;

$(this).children("th,td").each(function()
{
if($(this).hasClass("ms-vh-icon"))
{
// attachment
tdset += "<td></td>";
}
else
{
// filterable
tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' /></td>";
}

colIndex++;
});

var tr = "<tr class='vossers-filterrow'>" + tdset + "</tr>";

$(tr).insertAfter(this);
});


$("input.vossers-filterfield")
.css("border", "1px solid #7f9db9")
.css("width", "100%")
.css("margin", "2px")
.css("padding", "2px")
.keyup(function()
{
var inputClosure = this;

if(window.VossersFilterTimeoutHandle)
{
clearTimeout(window.VossersFilterTimeoutHandle);
}

window.VossersFilterTimeoutHandle = setTimeout(function()
{
var filterValues = new Array();

$("input.vossers-filterfield", $(inputClosure).parents("tr:first")).each(function()
{
if($(this).val() != "")
{
filterValues[$(this).attr("filtercolindex")] = $(this).val();
}
});


$(inputClosure).parents("tr.vossers-filterrow").nextAll("tr").each(function()
{
var mismatch = false;

$(this).children("td").each(function(colIndex)
{
if(mismatch) return;

if(filterValues[colIndex])
{
var val = filterValues[colIndex];

// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));

if($(this).is(":not(:containsIgnoreCase('" + val + "'))"))
{
mismatch = true;
}
}
});

if(mismatch)
{
$(this).hide();
}
else
{
$(this).show();
}
});

}, 250);
});
});

});

</script>

Find CheckOut files In SPLibrary or Folder in sharepoint programatically


        public static void GetCheckOutfile(SPDocumentLibrary docs)
        {
          //  foreach (SPCheckedOutFile spFiles in spFolder.Files)



            foreach (SPCheckedOutFile file in docs.CheckedOutFiles)
            {

                if (file.LeafName != file.Url.ToString().Split('/')[3])
                {
                 

                 
                         
                       console.writeLine( file.LeafName);
                 
                  }


            }




}

Hide link in ECB Menu

function HideFeatureActivatedECBMenuItem() {
    if (!CanExecuteHideForECBMenuItem()) return;

    /* find the ECB menu items which are added via feature activation */
    var ecbId = "ECBItems";
    var listName;
    if ((null != ctx.listName) && (0 < ctx.listName.length)) {
        listName = ctx.listName.toLowerCase();
        ecbId = ecbId + "_" + listName;
    }
    var elemTBody = document.getElementById(ecbId);
    if (elemTBody != null) {
        // iterate each table row to find the ECB menu item to remove (hide)
        for (var iMenuItem = 0; iMenuItem < elemTBody.childNodes.length; iMenuItem++)
 {
            var elemTr = elemTBody.childNodes[iMenuItem];
            var elemTdTitle = elemTr.childNodes[0];
            var title = GetInnerText(elemTdTitle);

            // check the ECB item title
            if (title === "Edit Item")
 {
                elemTBody.removeChild(elemTr);
 }
        }
    }
}

Create Unique Value in SSRS Dropdown Parameter

Public Shared Function RemoveDuplicates(parameter As Parameter) As String()
Dim items As Object() = parameter.Value

System.Array.Sort(items)

Dim k As Integer = 0

For i As Integer = 0 To items.Length - 1

If i > 0 AndAlso items(i).Equals(items(i - 1)) Then
Continue For

End If
items(k) = items(i)

k += 1
Next

Dim unique As [String]() = New [String](k - 1) {}

System.Array.Copy(items, 0, unique, 0, k)

Return unique
End Function






Add in Available value this code


=Code.RemoveDuplicates(parameter!dummyparameter)

change webpart header bg and color

<style>
.ms-WPHeader
{

background-color:green;

}
.ms-WPTitle A
{
  color:white !important;
}
</style>

Change the redirection behavior using jQuery on Submit button in sharepoint ListItem




<script>

$(document).ready(function() {

    var button = $("input[id$=SaveItem]");
    // change redirection behavior
        button.removeAttr("onclick");
        button.click(function() {
            var elementName = $(this).attr("name");
            var aspForm = $("form[name=aspnetForm]");
            var oldPostbackUrl = aspForm.get(0).action;
            var currentSourceValue = GetUrlKeyValue("Source", true, oldPostbackUrl);
            var newPostbackUrl = oldPostbackUrl.replace(currentSourceValue, "MyRedirectionDestination.aspx");

            if (!PreSaveItem()) return false;
            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(elementName, "", true, "", newPostbackUrl, false, true));
        });
   
});
</script>

Add Connection String in Share point TimerJob from web.config file

 add connection string in SPTIMERJOB  




Step -1

add .dll references

Microsoft.SharePoint.Client.ServerRuntime
Path
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.ServerRuntime.dll
System.Configuration
path
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Configuration.dll
System.Web
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Web.dll

Step -2    

add namespace

using System.Web.Configuration;
using System.Configuration;




SPWebApplication webApplication = this.Parent as SPWebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);
string conStr = config.ConnectionStrings.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);