Tuesday, 8 March 2016

GroupBy With LinQ

  var mainQuery = finaldocCount.GroupBy(u => new { u.ProjectCode })
                                                                      .Select(grp => new
                                                                      {

                                                                          ProjectCode = grp.Key.ProjectCode,
                                                                          mailList = grp.ToList()
                                                                      }).ToList();


                          foreach (var item in mainQuery)
                                {
                                    foreach (finalNameCount v in item.mailList)
                                    {

                                        v.Name;


                                   
                                    }
                                }

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();
            }
        }