Thursday, 30 January 2014

Run Timer Job in button Click event without go to Central Admin

This is mainly used to run Timer Job in button Click event without going to Central Admin


//To check whether the Timer job in currently Running or not
                            if (site.WebApplication.RunningJobs.Cast<Microsoft.SharePoint.Administration.SPRunningJob>().Any(curRunningJob => curRunningJob.JobDefinitionTitle.Equals("JobName")))
                            {
}
}
                            else
                            {

//Collect all job in SharePoint Central Admin
                                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                                {
                                    if (job.Name == "JobName")
                                    {
                                        var strStatus = job.Status;

                                        // THE ORIGINAL VALUE OF REMOTE ADMINISTRATOR
                                        var remoteAdministratorAccessDenied = SPWebService.ContentService.RemoteAdministratorAccessDenied;
                                        try
                                        {

                                            // SET THE REMOTE ADMINISTATOR ACCESS DENIED FALSE
                                            //  SPWebService.ContentService.RemoteAdministratorAccessDenied = false;

                                            if (remoteAdministratorAccessDenied == true)
                                            {
                                                SPWebService myService = SPWebService.ContentService;
                                                myService.RemoteAdministratorAccessDenied = false;
                                                myService.Update();
                                                job.RunNow();


                                            }

                                            else
                                            {

                                                job.RunNow();

                                            }


                                        }
                                        catch (Exception ex)
                                        { }

                                        finally
                                        {

                    // SET THE REMOTE ADMINISTRATOR ACCESS DENIED BACK WHAT IT WAS

                                            SPWebService.ContentService.RemoteAdministratorAccessDenied = remoteAdministratorAccessDenied;
                                        }

                                    }
                                }
                            }



Before Deploy that we fallow below steps
1. Create .ps1 file and paste Below Code into that file and Run that file
                                          (or)
Copy and paste below Code in Power shell


#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                          Configuring RemoteAdministratorAccessDenied
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
function LoadSharePointPowerShellEnvironment
{
   write-host
   write-host "Setting up PowerShell environment for SharePoint..." -foregroundcolor Yellow
   write-host
   Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
   write-host "SharePoint PowerShell Snapin loaded." -foregroundcolor Green
}

function SetRemoteAdministratorAccessDenied()
{
       # load sharepoint API libs
       [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
       [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $null

  # First get the content web service
 $contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
  # Now set the remote administration security to off
 $contentService.RemoteAdministratorAccessDenied = $false
  # Also update the web service
 $contentService.Update()
     
}


write-host
LoadSharePointPowerShellEnvironment

SetRemoteAdministratorAccessDenied

2. Create another .ps1 file and paste Below Code into that file and Run that file
                                          (or)
Copy and paste below Code in PowerShell

#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                          Attempting to set the status of the service instance to online
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
$farm  = Get-SPFarm
$disabledTimers = $farm.TimerService.Instances | where {$_.Status -ne "Online"}
if ($disabledTimers -ne $null)
{
    foreach ($timer in $disabledTimers)
    {
        Write-Host "Timer service instance on server " $timer.Server.Name " is not Online. Current status:" $timer.Status
        Write-Host "Attempting to set the status of the service instance to online"
        $timer.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Online
        $timer.Update()
    }
}
else
{
    Write-Host "All Timer Service Instances in the farm are online! No problems found"

}

Fetching Data From Excel sheet using Open XML

Fetching Data From Excel sheet using Open XML

using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Collections.Generic;

Create dataSet and Fetching Data From Excel using ReadData Method

DataSet ds = new DataSet("Details");
DataTable dt = ReadData("FileTotalPath", "SheetName");
dt.TableName = "TableName ";
ds.Tables.Add(dt);


public DataTable ReadData(string xlsxFilePath, string sheetName)
        {
            DataTable dt = new DataTable();
            try
            {

                using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(xlsxFilePath, false))
                {
                    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
                    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                    string relationshipId = sheets.First().Id.Value;
                    WorksheetPart worksheetPart = null;
                    if (!string.IsNullOrEmpty(sheetName))
                    {
                        Sheet ss = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).SingleOrDefault<Sheet>();
                        worksheetPart = (WorksheetPart)workbookPart.GetPartById(ss.Id);
                    }
                    else
                    {
                        worksheetPart = (WorksheetPart)workbookPart.GetPartById(relationshipId);
                    }
                    //WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                    Worksheet workSheet = worksheetPart.Worksheet;
                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = sheetData.Descendants<Row>();




                    foreach (Cell cell in rows.ElementAt(0))
                    {
                        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell).Trim());
                    }
                    foreach (Row row in rows) //this will also include your header row...
                    {
                        DataRow tempRow = dt.NewRow();
                        int columnIndex = 0;
                        foreach (Cell cell in row.Descendants<Cell>())
                        {
                            // Gets the column index of the cell with data
                            int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));
                            cellColumnIndex--; //zero based index
                            if (columnIndex < cellColumnIndex)
                            {
                                do
                                {
                                    tempRow[columnIndex] = ""; //Insert blank data here;
                                    columnIndex++;
                                }
                                while (columnIndex < cellColumnIndex);
                            }
                            tempRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);

                            columnIndex++;
                        }
                        dt.Rows.Add(tempRow);
                    }
                }
                dt.Rows.RemoveAt(0); //...so i'm taking it out here.


            }
            catch (Exception ex)
            {
            }
            return dt;

        }


        /// <summary>
        /// Given a cell name, parses the specified cell to get the column name.
        /// </summary>
        /// <param name="cellReference">Address of the cell (ie. B2)</param>
        /// <returns>Column Name (ie. B)</returns>

        public static string GetColumnName(string cellReference)
        {
            // Create a regular expression to match the column name portion of the cell name.
            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(cellReference);
            return match.Value;
        }

        /// <summary>
        /// Given just the column name (no row index), it will return the zero based column index.
        /// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ). 
        /// A length of three can be implemented when needed.
        /// </summary>
        /// <param name="columnName">Column Name (ie. A or AB)</param>
        /// <returns>Zero based index if the conversion was successful; otherwise null</returns>

        public static int? GetColumnIndexFromName(string columnName)
        {

            //return columnIndex;
            string name = columnName;
            int number = 0;
            int pow = 1;
            for (int i = name.Length - 1; i >= 0; i--)
            {
                number += (name[i] - 'A' + 1) * pow;
                pow *= 26;
            }
            return number;
        }
        public static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            if (cell.CellValue == null)
            {
                return "";
            }
            string value = cell.CellValue.InnerXml;
            if (cell.DataType != null && cell.DataType == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            //else if (cell.DataType != null && cell.DataType == CellValues.Date)
            //{

            //    return Convert.ToString(Convert.ToDateTime(stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText));
            //}
            else
            {
                return value;
            }
        }

Note: Add Windows Base Reference also.
Download DocumentFormat.OpenXML.dll file

Wednesday, 29 January 2014

Creating Custom Timer Job in SharePoint

Steps
Description
Step 1
Creation timerjob solution
Step 2
Adding Feature
Step 3
Activating the timerjob feature
Step 4
Running Timer Job
Step 5
Debugging timerjob


Step 1:  Creation Timer job solution

Select “Empty SharePoint Project”  and click OK

Select “Deploy as a Farm Solution” and click Finish

Add class file

For Excel component, add the interop reference

Add Reference as WindowsBase

Include the below references and code in the class file. Replace “SampleTimerJob_Class” with your class filename.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Configuration;
using System.Data;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
using Microsoft.SharePoint.Utilities;

namespace SampleTimerJob
{
    public class SampleTimerJob_Class : SPJobDefinition
    {
         public SampleTimerJob_Class() : base() { }
         public SampleTimerJob_Class(string jobName, SPWebApplication webApp)
            : base(jobName, webApp, null, SPJobLockType.Job)
        {
            this.Title = "OTS Journal Timer Job"; //This will be your timerjob name
        }

                string SiteUrl = string.Empty;
         public override void Execute(Guid targetInstanceId)
         {
            SiteUrl = Convert.ToString(this.Properties["SiteCollectionUrl"]);
               //Here is your code starts
         }

    }
}

Step 2 : Adding Feature


Right click on “Feature” and Click “Add Feature”

This title will be appeared in “Site Collection Features”, Select “Site” in Scope

Save the feature

Add the event receiver
Add the namespace
using Microsoft.SharePoint.Administration;

Replace this method by the below code and do the necessary changes

public class Feature1EventReceiver : SPFeatureReceiver
    {
        SPSite site = null;
        SPWeb web = null;
        public Feature1EventReceiver()
        {
            // string siteUrl = "http://balaj8t-asus/";
//string siteUrl = "http://siva-pc/"; //This will not work, if it is given Config. Hard //code here

            //SPSecurity.RunWithElevatedPrivileges(delegate()
            //{
            //    using (site = new SPSite(siteUrl))
            //    {
            //        web = site.OpenWeb();
            //    }
            //});
        }
        // Uncomment the method below to handle the event raised after a feature has been //activated.
        const string JobName = "Journal Timer Job";


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            site = properties.Feature.Parent as SPSite;

            // make sure the job isn't already registered

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {

                if (job.Name == JobName)

                    job.Delete();

            }

            // install the job

            SampleTimerJob_Class listLoggerJob = new SampleTimerJob_Class(JobName, site.WebApplication);

           //Adding property for to find Site URL
                     listLoggerJob.Properties.Add("SiteCollectionUrl",site.Url);

            SPMinuteSchedule schedule = new SPMinuteSchedule();

            schedule.BeginSecond = 0;

            schedule.EndSecond = 59;

            schedule.Interval = 5;

            listLoggerJob.Schedule = schedule;

            listLoggerJob.Update();


        }

        private static void DeleteJob(SPSite site)
        {
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                if (job.Name == JobName)
                    job.Delete();
        }
        private static void CreateJob(SPSite site)
        {
            SampleTimerJob_Class job = new SampleTimerJob_Class(JobName, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 5;
            schedule.Interval = 5;

            job.Schedule = schedule;
            job.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            DeleteJob(properties.Feature.Parent as SPSite); // Delete the Job
        }


    }



Step 3 : Activating the Timer job feature


Go to central admin and click on “Site Actions>>Site Settings”

Click on “Site Collection Features”

Click on Activate

Step 4 : Running Timer Job


Click on “Monitoring” after that click on “Review Job Definitions”

Click on “Sample Timer Job”

Can do all the settings and click “Run Now”

Step 5 : Debugging Timer job

Click on “Attach to Process”

Select “OwsTimer.EXE” and click on “Attach”

After attaching click on “Run Now”

The breakpoint fires.

After debugging, click on “Detach All”













Creating Custom Master Page in SharePoint 2013

In SharePoint 2013 we can create our own Html Master Page and convert it to SharePoint master page. In this Document I try explain it briefly.

  •  Open any editor for html example Notepad and write the Following sample code • If you want you can also create Css file for this master page.
  •  Now navigate to the Top Level site in your SharePoint site collection and click settings icon and select Site Settings option. 
  • Open the Master Pages and Page Layouts under web designer galleries category. 
  • Click Upload Document in the Ribbon and browse for your Html file and click upload. Select html Master page as content type of the File.
  • You can add your css style sheet reference in the information form.

  • Upload you style sheet and graphics as design files. You can create a separate for them too.

  • Navigate to the Design Manager in site settings under Look and feel and select Edit Master Pages. Note Your Html Master Page in the list.

  • Click on Convert to Html file to a SharePoint master page and select your master page from the gallery.

  • Click on insert and SharePoint will convert your Html Page into a Master Page, Showing the master page status as conversion successful.
  • You can either download a copy of the converted .html file from the master pages gallery or open the top level site for editing in SharePoint designer 2013 where you can edit the file on the fly and see the changes in the preview right away.

  • In SharePoint Designer Click to open the file, then click the Edit file link. You can see that the conversion, SharePoint added a whole lot of code in the Html version of the file in addition to creation of .master page file .Do not delete the code added by SharePoint!
Add Snippets to your .html Master Page
  • Go to the Design manager which is located under Site settings. Select Edit Master Page .
  • Select your html Master Page and click on it. The preview will be shown as below.
  • Click on snippets in the upper right hand corner of the preview page. This opens a new browser for     selecting and customizing the snippets, i.e. the SharePoint controls.
  • Pick the snippet on the ribbon, customize it as needed, then click on Copy to Clipboard and place the code in the appropriate place in the HTML file.
  • If you are working in SharePoint Designer, save changes and refresh preview to view the changes made by inserting the snippets