Friday 24 February 2017

Windows Service to Check if any folder is containing any files

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace HelloworldService
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer =  new System.Timers.Timer();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\abhas.txt", true);
            file.WriteLine(DateTime.Now + "Service Has Started");
         
            timer.Interval = 60000; // 60 seconds
            timer.Enabled = true;

            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();

         
            String fileName = string.Empty; String filePath;
         
            filePath = System.Configuration.ConfigurationManager.AppSettings["Folderpath"].ToString();
            string[] filePaths = Directory.GetFiles(filePath);



            DirectoryInfo di = new DirectoryInfo("C:\\Dropbox");
            FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories);
            if (Convert.ToInt32(fi.Length)>0)
            {
                file.WriteLine(DateTime.Now + "There ares ome files");
            }
            else
            {
                file.WriteLine(DateTime.Now + "No Files Present");
            }
         
            file.Close();
         

        }

        private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\abhas.txt", true);
            String fileName = string.Empty; String filePath;
         
            filePath = System.Configuration.ConfigurationManager.AppSettings["Folderpath"].ToString();
            string[] filePaths = Directory.GetFiles(filePath);



            DirectoryInfo di = new DirectoryInfo("C:\\Dropbox");
            FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories);
            if (Convert.ToInt32(fi.Length) > 0)
            {
                file.WriteLine(DateTime.Now + "There ares Some files");
            }
            else
            {
                file.WriteLine(DateTime.Now + "No Files Present");
            }
            file.Close();
        }

     

        protected override void OnStop()
        {
        }
    }
}

Console App to Upload Documents in Document Library

String fileName = string.Empty ; String filePath ;

              filePath = System.Configuration.ConfigurationManager.AppSettings["Folderpath"].ToString();
    string[] filePaths = Directory.GetFiles(filePath);

         
         
    foreach (string filepath in filePaths)
    {
        Console.WriteLine(filepath);
        Console.ReadLine();
    using (SPSite oSite = new SPSite( Your Site name))
        {
            using (SPWeb oWeb = oSite.OpenWeb())
            {
                if (!System.IO.File.Exists(filepath))
                    throw new FileNotFoundException("File not found.", filepath);

                SPFolder myLibrary = oWeb.Folders[Libraryname];

                // Prepare to upload
                Boolean replaceExistingFiles = true;
                 fileName = System.IO.Path.GetFileName(filepath);
                 FileStream fileStream = System.IO.File.OpenRead(filepath);

                // Upload document
                SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

                // Commit
                myLibrary.Update();
            }
        }
   



    }

Wednesday 22 February 2017

Deployment Error

Error occurred in deployment step 'Add Solution': A feature with ID '' has already been installed in this farm. Use the force attribute to explicitly re-install the feature.


There will be  a feature  in the solution called feature1 delete that and retry 

Upload file in SharePoint Library using Jquery

Code to Upload file in SharePoint Document Library using Jquery

<html>
 
<head title="abhas">

    <script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
 
    <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script  type="text/javascript">
           var fileInput;
        $(document).ready(function () {

            fileInput = $("#getFile");
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
        });

        function registerClick() {
            //Register File Upload Click Event
            $("#addFileButton").click(readFile);
        }
       var arrayBuffer;

        function readFile() {
            //Get File Input Control and read th file name
            var element = document.getElementById("getFile");
            var file = element.files[0];
            var parts = element.value.split("\\");
            var fileName = parts[parts.length - 1];
            //Read File contents using file reader
            var reader = new FileReader();
           reader.onload = function (e) {
                uploadFile(e.target.result, fileName);
            }
            reader.onerror = function (e) {
             //   alert(e.target.error);
            }
            reader.readAsArrayBuffer(file);
        }
        var attachmentFiles;

        function uploadFile(arrayBuffer, fileName) {

            //Get Client Context,Web and List object.
            var clientContext = new SP.ClientContext();
            var oWeb = clientContext.get_web();
            var oList = oWeb.get_lists().getByTitle('Documents');
            //Convert the file contents into base64 data
            var bytes = new Uint8Array(arrayBuffer);
            var i, length, out = '';
            for (i = 0, length = bytes.length; i < length; i += 1) {
                out += String.fromCharCode(bytes[i]);
            }
            var base64 = btoa(out);
            //Create FileCreationInformation object using the read file data
            var createInfo = new SP.FileCreationInformation();
            createInfo.set_content(base64);
            createInfo.set_url(fileName);
            //Add the file to the library
            var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
            //Load client context and execcute the batch
            clientContext.load(uploadedDocument);
            clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
        }

        function QuerySuccess() {
            alert('File Uploaded Successfully.');
        }

        function QueryFailure(sender, args) {
            alert('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
        }
    </script>
</head>
 
<body>
    <input id="getFile" type="file" /><br />
    <input id="addFileButton" type="button"
        <%-- onclick="uploadFile()" --%>
        value="Upload" />
</body>
</html>