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 ,Edit and Delete in GridView with People picker and DateTime Picker control

using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.IO;
using System.Collections;
namespace CustomPageForLibrary.Layouts.CustomPageForLibrary
{
    public partial class TaskFormForLirary : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownBind();
                BindData();
             
             
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
           
            GridView1.EditIndex = e.NewEditIndex;
            BindData();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int i = e.RowIndex;

            //using (SPSite site = new SPSite("siteurl"))
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["MOMListt"];
                    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
                    SPListItem item = list.GetItemById(id);
               
                  //  item["Meeting"] = new SPFieldLookupValue(Convert.ToInt32(txtMeetingId.Text),txtMeetingName.Text);
                    item["Minutes"] = ((TextBox)GridView1.Rows[i].FindControl("txtMinutes")).Text;
                    PeopleEditor ppAuthor = ((PeopleEditor)GridView1.Rows[i].FindControl("ActionByUser"));
                    PickerEntity ActionUser = (PickerEntity)ppAuthor.ResolvedEntities[0];
                    SPUser actionByUser = Web.EnsureUser(ActionUser.Key);
                    item["Actionby"] = actionByUser;
                    if (((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date.ToString() != "" || ((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date.ToString() !=null)
                    {
                    item["TargetDate"] = ((DateTimeControl)GridView1.Rows[i].FindControl("targetdateuser")).SelectedDate.Date;
                    }
                    item["Status"] = ((DropDownList)GridView1.Rows[i].FindControl("DropDownList1")).SelectedItem.Text;
                    CheckBox chk = ((CheckBox)GridView1.Rows[i].FindControl("Assigned"));
                    string blActive = "";
                    if (chk.Checked == true)
                    {
                        blActive = "True";
                        item["assignedtask"] = blActive;
                    }
                    else
                    {
                        blActive = "False";
                        item["assignedtask"] = blActive;
                    }
                    item["Issues"] = TextBox7.Text;
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;

            }
            GridView1.EditIndex = -1;
            BindData();
        }
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    SPSite site = new SPSite(SPContext.Current.Web.Url);
                    SPWeb web = site.OpenWeb();
                    PeopleEditor pplEditor = ((PeopleEditor)e.Row.FindControl("ActionByUser"));
                    ArrayList alApprover = new ArrayList();
                    PickerEntity pentApprover = new PickerEntity();
                    char[] delimiterChars = { '#' };
                    string text = drview[2].ToString();
                    string[] words = text.Split(delimiterChars);
                    pentApprover.Key = words[1];
                    alApprover.Add(pentApprover);
                    pplEditor.UpdateEntities(alApprover);
                    DateTimeControl dtc = ((DateTimeControl)e.Row.FindControl("targetdateuser"));
                    dtc.SelectedDate=Convert.ToDateTime(drview[3].ToString());
                    DropDownList dpEmpdept = (DropDownList)e.Row.FindControl("DropDownList1");
                    DataTable dt = GetStatus();
                    dpEmpdept.DataSource = GetStatus();
                    dpEmpdept.DataTextField = "DepName";
                    dpEmpdept.DataValueField = "DepName";
                    dpEmpdept.DataBind();
                    dpEmpdept.SelectedValue = drview[4].ToString();
                    CheckBox chkb = (CheckBox)e.Row.FindControl("Assigned");
                    if (drview[5].ToString() == "True")
                    { chkb.Checked = true; }
                    else { chkb.Checked = false; }
             
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList dp = (DropDownList)e.Row.FindControl("DropDownList14");
                dp.DataSource = GetStatus();
                dp.DataTextField = "DepName";
                dp.DataValueField = "DepName";
                dp.DataBind();
            }
        }
        private DataTable GetStatus()
        {
           
            DataTable dt = new DataTable();
            dt.Columns.Add("DepName");
            DataRow rw1 = dt.NewRow();
            rw1[0] = "Open";
            dt.Rows.Add(rw1);
            DataRow rw2 = dt.NewRow();
            rw2[0] = "Closed";
            dt.Rows.Add(rw2);
            return dt;
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;

            BindData();

        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int i = e.RowIndex;
           // BindData();
        }
        public void BindData()
        {
            using (SPSite s = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb sw = s.OpenWeb())
                {
                    SPList sl = sw.Lists["MOMListt"];
                    SPQuery query=new SPQuery();
                    if (txtMeetingId.Text != "")
                    {
                        query.Query = @"<Where>" +
          "<Eq>" +
             "<FieldRef Name='Meeting' LookupId='True' />" +
             "<Value Type='Lookup'>" + Convert.ToInt32(txtMeetingId.Text) + "</Value>" +
          "</Eq>" +
       "</Where>";
                    }
                    SPListItemCollection itemCollection = sl.GetItems(query);
                    DataTable ResTable = new DataTable();
                    ResTable.Columns.Add(new DataColumn("ID"));
                    ResTable.Columns.Add(new DataColumn("Minutes"));
                    ResTable.Columns.Add(new DataColumn("Actionby"));
                    ResTable.Columns.Add(new DataColumn("TargetDate"));
                    ResTable.Columns.Add(new DataColumn("Status"));
                    ResTable.Columns.Add(new DataColumn("TaskAssigned"));
               
                    foreach (SPListItem item in itemCollection)
                    {
                        DataRow dr = ResTable.NewRow();
                        dr["ID"] = item["ID"].ToString();
                        dr["Minutes"] = item["Minutes"];
                        dr["ActionBy"] = item["Actionby"].ToString();
                        dr["TargetDate"] = item["TargetDate"];
                        dr["Status"] = item["Status"].ToString();
                        dr["TaskAssigned"] = item["assignedtask"].ToString();
                        ResTable.Rows.Add(dr);
                    }
                    if (ResTable.Rows.Count > 0)
                    {
                        GridView1.DataSource = ResTable;
                        GridView1.DataBind();
                     
                    }
                    else
                    {
                        DataRow dr = ResTable.NewRow();
                        dr["ID"] = "";
                        dr["Minutes"] = "";
                        dr["ActionBy"] = "";
                        dr["TargetDate"] = "";
                        dr["Status"] = "";
                        dr["TaskAssigned"] = "";
                        ResTable.Rows.Add(dr);
                        GridView1.DataSource = ResTable;
                        GridView1.DataBind();
                    }
                 
                }
            }
        }
     
       
        public void DropDownBind()
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    DataSet ds = new DataSet();
                    SPList list = web.Lists["Board Events"];
                    SPListItem item = list.Items.GetItemById(Convert.ToInt32(Request.QueryString["Mid"].ToString()));
                    txtMeetingName.Text = item["Title"].ToString();
                    txtMeetingId.Text = item["ID"].ToString();
                 
                }
            }
        }
     
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Add")
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    site.AllowUnsafeUpdates = true;
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists["MOMListt"];
                        SPListItem item = list.Items.Add();
                        item["Meeting"] = new SPFieldLookupValue(Convert.ToInt32(txtMeetingId.Text), txtMeetingName.Text);
                        item["Minutes"] = ((TextBox)GridView1.FooterRow.FindControl("txtMinuteFooter")).Text;
                        PeopleEditor ppAuthor = ((PeopleEditor)GridView1.FooterRow.FindControl("ActionBy"));
                        PickerEntity ActionUser = (PickerEntity)ppAuthor.ResolvedEntities[0];
                        SPUser actionByUser = Web.EnsureUser(ActionUser.Key);
                        item["Actionby"] = actionByUser;
                        item["TargetDate"] = ((DateTimeControl)GridView1.FooterRow.FindControl("targetdate")).SelectedDate.Date;
                        item["Status"] = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList14")).SelectedItem.Text;
                        CheckBox chk = ((CheckBox)GridView1.FooterRow.FindControl("AssignedFilter"));
                        string blActive = "";
                        if (chk.Checked == true)
                        {
                            blActive = "True";
                            item["assignedtask"] = blActive;
                        }
                        else
                        {
                            blActive = "False";
                            item["assignedtask"] = blActive;
                        }
                        if (TextBox7.Text != "")
                        {
                            item["Issues"] = TextBox7.Text;
                        }
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                    site.AllowUnsafeUpdates = false;
               
                }
                BindData();
            }
            else if (e.CommandName == "Delete")
         {
             using (SPSite site = new SPSite(SPContext.Current.Web.Url))
           {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                 
                    SPList taskList = web.Lists["Tasks"];
                    SPQuery query = new SPQuery();
                    query.Query = @"<Where>" +
         "<Eq>" +
            "<FieldRef Name='MinuteofMeetingId'/>" +
            "<Value Type='Number'>" + Convert.ToInt32(e.CommandArgument.ToString()) + "</Value>" +
         "</Eq>" +
      "</Where>";

                    SPListItemCollection itemcollection = taskList.GetItems(query);

                    for (int i = itemcollection.Count - 1; i >= 0; i--)
                    {
                        SPListItem item = itemcollection[i];
                        item.Delete();
                    }
                    SPList list = web.Lists["MOMListt"];
                    list.Items.DeleteItemById(Convert.ToInt32(e.CommandArgument.ToString()));
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;
           }
             BindData();
             
        }
         

        }
     

       
    }
}


HTML Code///////////////////////////////////////////////////////////////////////////////////////////////
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TaskFormForLirary.aspx.cs" Inherits="CustomPageForLibrary.Layouts.CustomPageForLibrary.TaskFormForLirary" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<style type="text/css">
        #DivContent
        {
            margin-top: 30px;
            width: 85%;
            border: .1em;
            border-style: none;
            padding: 15px;
        }
        table
        {
            width: 100%;
        }
        .ControlTD
        {
            width: 20%;
            text-align: left;
        }
        .TextTD
        {
            width: 25%;
            font-size: 12px;
            text-align: left;
            color: #00A1DE;
        }
        .RFVTD
        {
            width: 10%;
            text-align: left;
        }
        p
        {
            text-align: center;
            font-size: 22px;
            color: #3C8A2E;
        }
    </style>
    <script language="javascript" type="text/javascript">

        function ValidateGrid(x) {

            var gridView = document.getElementById('<%=GridView1.ClientID %>');

            var selectedRowIndex = x.parentNode.parentNode.rowIndex;

            var txtName = gridView.rows[parseInt(selectedRowIndex)].cells[0].children[0];

             var pplpicker = gridView.rows[parseInt(selectedRowIndex)].cells[1].children[0];

            if (txtName.value == "" || pplpicker.value=="")
            {

                alert('Please input all required fields');

                return false;

            }

        }

    </script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

<div id="DivContent">
        <p>
            Minutes of Meeting</p>
            <div><div>&nbsp; Meeting&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
               <%-- <asp:DropDownList ID="DropDownList2" runat="server" style="margin-left: 0px" Width="309px">
                </asp:DropDownList>--%>
                <asp:Label ID="txtMeetingName" runat="server"  Font-Bold="true">
                </asp:Label><asp:Label ID="txtMeetingId" runat="server"
                     ForeColor="White"></asp:Label>
                   
                </div></div>
                <asp:UpdatePanel ID="Panel" runat="server" >
            <ContentTemplate>
            <br />
            <br />
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
    EnableModelValidation="True" ShowFooter="True" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound"  >
    <Columns>
        <asp:TemplateField HeaderText="Minutes">
            <EditItemTemplate>
                <asp:TextBox ID="txtMinutes" runat="server" Text='<%#Eval("Minutes")%>' TextMode="MultiLine" Width="350px" Height="70px"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("Minutes")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
         <asp:TextBox ID="txtMinuteFooter" runat="server" TextMode="MultiLine" Width="350px" Height="70px"></asp:TextBox>
     
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action By">
            <EditItemTemplate>
                <SharePoint:PeopleEditor ID="ActionByUser" runat="server" MultiSelect="false" Width="200px" AllowEmpty="false"  />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%#Eval("ActionBy")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                 <SharePoint:PeopleEditor ID="ActionBy" runat="server" MultiSelect="false" Width="200px" AllowEmpty="false"  />
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Target Date" ItemStyle-Width="150px">
            <EditItemTemplate>
           
                <SharePoint:DateTimeControl EnableViewState="true" ID="targetdateuser" runat="server"
                        DateOnly="true" />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label3" runat="server" Text='<%#Eval("TargetDate")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                 <SharePoint:DateTimeControl EnableViewState="true" ID="targetdate" runat="server"
                        DateOnly="true" />
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Status">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server">
             
               
                </asp:DropDownList>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label4" runat="server" Text='<%#Eval("Status")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
         <asp:DropDownList ID="DropDownList14" runat="server">
             
                </asp:DropDownList>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Assigned Task">
            <EditItemTemplate>
               <asp:CheckBox ID="Assigned" runat="server">
             
                </asp:CheckBox>
            </EditItemTemplate>
            <ItemTemplate>
              <asp:Label ID="Label5" runat="server" Text='<%#Eval("TaskAssigned")%>'></asp:Label>
           
           
            </ItemTemplate>
            <FooterTemplate>
         <asp:CheckBox ID="AssignedFilter" runat="server" >
                </asp:CheckBox>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <EditItemTemplate>
                <asp:LinkButton ID="LinkButton11" runat="server" CausesValidation="true" OnClientClick='javascript:return ValidateGrid(this);'
                    CommandName="Update" Text="Update" CommandArgument='<%#Eval("ID")%>'></asp:LinkButton>
                &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
                    CommandName="Cancel" Text="Cancel"></asp:LinkButton>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                    CommandName="Edit" Text="Edit"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
         
                <asp:LinkButton ID="LinkButton2s" runat="server" CausesValidation="False"
                    CommandName="Delete" Text="Delete" CommandArgument='<%#Eval("ID")%>'></asp:LinkButton>

            </ItemTemplate>
            <FooterTemplate>
             <asp:LinkButton ID="LinkButton21" runat="server"
                    CommandName="Add" Text="Add" CausesValidation="true" OnClientClick='javascript:return ValidateGrid(this);'></asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField>

    </Columns>
 
</asp:GridView>
    </ContentTemplate>
    </asp:UpdatePanel>
<div>
    <table>
        <tr>
            <td valign="top">Pending Issues :</td><td>
                <asp:TextBox ID="TextBox7" runat="server" TextMode="MultiLine" Height="84px" Width="534px"></asp:TextBox></td>

        </tr>

    </table>

</div>
        <br />
        <p>
            &nbsp;</p>
    </div>

</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>