Search This Blog

Tuesday, June 13, 2017

Copy files from SharePoint document library to local folder using c#

1-    Create A Library (FileDumpConfigurationSettings ) To set Timer Job Configuration





2-    Create Class


Code :
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
namespace NGOFileDumpProcess
{
    class NGOFileDumpTimmerJobSPJobDefinition
    {
        public NGOFileDumpTimmerJob() : base()
        { }
        public NGOFileDumpTimmerJob(string jobName, SPService service) : base(jobName, service, nullSPJobLockType.None)
        {
            this.Title = "NGO File Dump Process";
        }
        public NGOFileDumpTimmerJob(string jobName, SPWebApplication webapp) : base(jobName, webapp, nullSPJobLockType.ContentDatabase)
        {
            this.Title = " NGO File Dump Process";
        }
        #region Excute Method Of Timer Jobs
        public override void Execute(Guid targetInstanceId)
        {
            // Start Getting All Library Name From List
            //document library name to download
            try
            {
                DownLoadFiles();
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void DownLoadFiles()
        {
            string UrlandDumpLocation = GetSiteUrlandDumpLocation();
            if(UrlandDumpLocation!="")
            {
                string siteUrl = UrlandDumpLocation.Split('|')[0].ToString();
                string filePath = UrlandDumpLocation.Split('|')[1].ToString();
                string LibraryName = UrlandDumpLocation.Split('|')[2].ToString();
                // getting Record of Curret month
                string Month = DateTime.Now.ToString("MM");
                string Year = DateTime.Now.ToString("yyyy");
                //
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // get the required document library
                        SPList docLib = web.Lists[LibraryName];
                        // code to download documents
                        // loop through each item or document in the document library
                        foreach (SPListItem item in docLib.Items)
                        {
                            string FolderPathLocation = "";
                            // Access the file
                            SPFile file = item.File;
                            string fileCreateiondateMonth = Convert.ToDateTime(item["Created"].ToString()).ToString("MM");
                            string fileCreateiondateYear = Convert.ToDateTime(item["Created"].ToString()).ToString("yyyy");
                            if(Month== fileCreateiondateMonth && Year== fileCreateiondateYear)
                            {
                                if (file != null)
                                {
                                    // retrieve the file as a byte array
                                    try
                                    {
                                        SPFieldLookupValueCollection values = new SPFieldLookupValueCollection(item["Location"].ToString());
                                        foreach (SPFieldLookupValue value in values)
                                        {
                                            Directory.CreateDirectory(filePath + value.LookupValue);
                                            byte[] bArray = file.OpenBinary();
                                            FolderPathLocation = Path.Combine(filePath + value.LookupValue, file.Name);
                                            //open the file stream and write the file
                                            using (FileStream fs = new FileStream(FolderPathLocation, FileMode.Create, FileAccess.ReadWrite))
                                            {
                                                fs.Write(bArray, 0, bArray.Length);
                                            }
                                        }
                                    }
                                    catch (IOException ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                }

                            }
                          
                        }
                    }
                }
            }
        }
        public string GetSiteUrlandDumpLocation()
        {
            string UrlandDumpLocation = string.Empty;
            try
            {
                SPWebApplication webApp = this.Parent as SPWebApplication;
                SPWeb web = webApp.Sites[0].RootWeb;
                SPList spList = null;
                web.AllowUnsafeUpdates = true;
                try
                {
                    spList = web.Lists.TryGetList("FileDumpConfigurationSettings");
                }
                catch (Exception ex)
                {
                    string Title = "Library Name is not found or miss matched";
                    //ErrorLog(Title, ex.Message);
                }

                SPListItemCollection items = spList.GetItems();
                foreach (SPListItem spListItem in items)
                {
                    if (UrlandDumpLocation == "")
                    {
                        UrlandDumpLocation = spListItem["Title"].ToString().Trim() + "|" + spListItem["DumpLocationPath"].ToString().Trim()+ "|" + spListItem["LibraryName"].ToString().Trim();
                    }
                }
            }
            catch (Exception ex)
            {
                string Title = "Function-GetSiteUrlandDumpLocation() error";
               // ErrorLog(Title, ex.Message);
            }
            return UrlandDumpLocation;
        }
    }
}

    #endregion

3-    Add The Feature and Add Event receiver


Code-
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace NGOFileDumpProcess.Features.NGOFileDumpProcessTimmerJob
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid("d38cdefb-0535-410c-bcc8-d515748fc7e4")]
    public class NGOFileDumpProcessTimmerJobEventReceiver : SPFeatureReceiver
    {
        const string JobName = "NGO File Dump Process";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    SPSite site = properties.Feature.Parent as SPSite;
                    CreateJob(parentWebApp);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool CreateJob(SPWebApplication site)
        {
            bool jobCreated = false;
            try
            {
                NGOFileDumpTimmerJob job = new NGOFileDumpTimmerJob(JobName, site);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 15;
                job.Schedule = schedule;
                job.Update();
            }
            catch (Exception)
            {
                return jobCreated;
            }
            return jobCreated;
        }
        public bool DeleteExistingJob(string jobName, SPWebApplication site)
        {
            bool jobDeleted = false;
            try
            {
                foreach (SPJobDefinition job in site.JobDefinitions)
                {
                    if (job.Name == jobName)
                    {
                        job.Delete();
                        jobDeleted = true;
                    }
                }
            }
            catch (Exception)
            {
                return jobDeleted;
            }
            return jobDeleted;
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            lock (this)
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate ()
                    {
                        SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                        DeleteExistingJob(JobName, parentWebApp);
                    });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
       
    }
}

4-       Add Code in Template.xml

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" AlwaysForceInstall="True" ActivateOnDefault="FALSE">
</Feature>

5 – select Scope of Timer Job  : web Application



How to download files from SharePoint document library programmatically using C#

Sometimes, we would want to download multiple files based on a pre-defined query such as a monthly report or a bulk download.
If it is a few files or if it is a complete folder, we can use the explorer view to copy paste the files. However, if we want to customize the query or automate the process, then we need to write custom code to download the files programmatically. This is also true, if we want to access the metadata of the files along with downloading the actual files.

Use the standard object model to access the SharePoint site and web.
string siteUrl = "site url";
using(SPSite site = new SPSite(siteUrl)
{
  using(SPWeb web = site.OpenWeb())
  {
    // code to download documents
  }
}
Retrieve the document library object using the SPWeb object from the above step.
// get the required document library
SPList docLib = web.Lists["Shared Documents"];
Access the items to be downloaded and download the files.
// loop through each item or document in the document library
foreach(SPListItem item in docLib.Items)
{
  // Access the file
  SPFile file = item.File;
  if(file != null)
  {
    // retrieve the file as a byte array
    byte[] bArray = file.OpenBinary();
    string filePath = Path.Combine("c:\\temp", file.Name);
    //open the file stream and write the file
    using(FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
    {
      fs.Write(bArray, 0, bArray.Length);
    }
  }
}
The above server side code can be used if you are using page code behind, event handler, timer job etc. I will do another post for downloading the documents from client side such a console application or a windows application.
In case you do not want to download all the files, you can use CAML query to filter the items in a document library or even a site collection and loop through those items. If it is spanning multiple site collections, you can use search query to retrieve the items.
Instead of using the file object from the SharePoint item, we can also use the file url to download the file from the document library. Following code will download the file located at url fileUrl to C:\Docs folder locally on the server:
FileStream fstream = null;
string fileName = Path.GetFileName(fileUrl);
if (!string.IsNullOrEmpty(fileName))
{
  byte[] data;
  byte[] buffer = new byte[2048];
  WebRequest request = WebRequest.Create(url);
  using (WebResponse response = request.GetResponse())
  {
    using (Stream responseStream = response.GetResponseStream())
    {
      using (MemoryStream ms = new MemoryStream())
      {
        int count = 0;
        do
        {
          count = responseStream.Read(buffer, 0, buffer.Length);
          ms.Write(buffer, 0, count);
        } while (count != 0);
        data = ms.ToArray();
      }
    }
  }
  string filePath = "C:\Docs";
  using (fstream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
  {
    fstream.Write(data, 0, data.Length);
    fstream.Close();
  }
}

HTML 5 Video Player Remove Download

<div id="videoframe" style="background: none;border: 1px solid #939598; border-width: 1px 1px; width:175px;">
<video id="cmmivideo" width="173px" height="140px" style="height:140px;" controls="" controlslist="nodownload">
 
<source src="http://intranet.ngo.com/NGO/HomePageVideos/CMMIMLS.mp4">
 
</video></div>

Friday, May 26, 2017

Datepicker


























   Code  and JS File 

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>
</head>
<body>

<p>Date: <input type="text" id="datepicker"></p>


</body>

</html>