Tuesday, April 14, 2015

How to change the SharePoint master page for wiki page at runtime



public class ChangeMasterPage : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            string requestUrl = HttpContext.Current.Request.Url.ToString();
            if (!requestUrl.Contains("aspx"))
                return;
            Page page = HttpContext.Current.CurrentHandler as Page;

            if (page != null)
            {
                // register handler for PreInit event
                page.PreInit += new EventHandler(page_PreInit);
            }
        }

        void page_PreInit(object sender, EventArgs e)
        {
            Page page = sender as Page;

            if (page != null)
            {
               
                   
                    string strMasterUrl = string.Empty;

                   
                        strMasterUrl = "_catalogs/masterpage/MyMasterPage.master";
                   
                    // if (Context.Request.LogonUserIdentity.IsAnonymous)
                    {
                        SPWeb web = SPContext.Current.Web;
                        page.MasterPageFile = web.ServerRelativeUrl + strMasterUrl;
                    }


               
            }
        }
        public void Dispose() { }
    }

Thursday, April 9, 2015

Copy Documents from One Library to another including Nested folder in Sharepoint


1. Program file

 #region global variables
        static SPListItem objItemDisp;
        static SPWeb objSourceWeb;
        static SPWeb objDestinationWeb;
        static SPFileCollection spFileCol = null;
        static string strStrsourceLib ;
        static string strStrdestinationLib ;
        static string strSiteUrl ;
        #endregion
        static void Main(string[] args)
        {
            ///Getting site url form Config File
            strSiteUrl = ConfigurationManager.AppSettings["SiteURL"].ToString();
            ///Reading Source Library Name form Config File
            strStrsourceLib = ConfigurationManager.AppSettings["SourceLib"].ToString();
            ///Reading Destination Library Name form Config File
            strStrdestinationLib = ConfigurationManager.AppSettings["DestiLib"].ToString();
            /// Start Process
            StartCopyDoc();
        }
        /// <summary>
        /// Initiate the process...
        /// </summary>
        private static void StartCopyDoc()
        {
            using (SPSite site = new SPSite(strSiteUrl))
            {
                try
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        objSourceWeb = web;
                        objDestinationWeb = web;
                        objDestinationWeb.AllowUnsafeUpdates = true;
                        SPDocumentLibrary source_lib = objSourceWeb.Lists[strStrsourceLib] as SPDocumentLibrary;
                        SPFileCollection source_files = source_lib.RootFolder.Files;
                        RootFolderFile(source_files);
                        SPFolderCollection folders = web.GetFolder(strStrsourceLib).SubFolders;
                        SubFolders(folders);
                        objDestinationWeb.AllowUnsafeUpdates = false;
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

        /// <summary>
        /// Iteration method to fetch the doc. from nested folder
        /// </summary>
        /// <param name="folders"></param>
        private static void SubFolders(SPFolderCollection folders)
        {
                foreach (SPFolder spFolder in folders)
                {
                    if (!spFolder.Name.Equals("Forms"))
                    {
                        int len = spFolder.ToString().IndexOf('/');
                        string folderName = spFolder.ToString().Substring(len + 1);
                        SPFileCollection source_SubFolderfiles = spFolder.Files;
                        CreateFolder(spFolder, folderName);
                        RootFolderFile(source_SubFolderfiles, folderName);
                        SubFolders(spFolder.SubFolders);
                    }
                }
        }

        /// <summary>
        /// Add doc. to destination lib. in root level
        /// </summary>
        /// <param name="source_files"></param>
        private static void RootFolderFile(SPFileCollection source_files)
        {
            SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;
            foreach (SPFile file in source_files)
            {
                object modified_by = file.Item["Editor"];
                object modified = file.Item["Modified"];
                object created_by = file.Item["Author"];
                SPFileCollection destination_files = destination_lib.RootFolder.Files;
                byte[] filebytes = file.OpenBinary();
                SPFile disp_file = destination_files.Add(destination_lib.RootFolder.Url + "/" + file.Name, filebytes, true);
             
                objItemDisp = disp_file.Item as SPListItem;
                objItemDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Created By"].ReadOnlyField = false;

                objItemDisp["Editor"] = modified_by;
                objItemDisp["Modified"] = modified;
                objItemDisp["Author"] = created_by;
                disp_file.Item.Update();
            }
        }

        /// <summary>
        /// Add doc. to Destination lib. in folder level
        /// </summary>
        /// <param name="source_files"></param>
        /// <param name="strFolder"></param>
        private static void RootFolderFile(SPFileCollection source_files,string strFolder)
        {
           SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;
            foreach (SPFile file in source_files)
            {
                object modified_by = file.Item["Editor"];
                object modified = file.Item["Modified"];
                object created_by = file.Item["Author"];
                SPFolderCollection folders = objDestinationWeb.GetFolder(strStrdestinationLib).SubFolders;
                spFileCol = null;
                SPFileCollection destination_files = DestinFileCollection(folders,strFolder);
             
                byte[] filebytes = file.OpenBinary();

                SPFile disp_file = destination_files.Add(destination_lib.RootFolder.Url + "/" +strFolder+"/"+ file.Name, filebytes, true);

                objItemDisp = disp_file.Item as SPListItem;
                objItemDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Created By"].ReadOnlyField = false;

                objItemDisp["Editor"] = modified_by;
                objItemDisp["Modified"] = modified;
                objItemDisp["Author"] = created_by;
                disp_file.Item.Update();
            }
        }
     
        /// <summary>
        /// get distination nested folder filecollection
        /// </summary>
        /// <param name="folders"></param>
        /// <param name="fdUrl"></param>
        /// <returns></returns>
        private static SPFileCollection DestinFileCollection(SPFolderCollection folders, string fdUrl)
        {
            foreach (SPFolder spFolder in folders)
            {
                if (!spFolder.Name.Equals("Forms"))
                {
                    int len = spFolder.ToString().IndexOf('/');
                    string folderName = spFolder.ToString().Substring(len + 1);
                    if (folderName.Equals(fdUrl))
                    {
                        spFileCol = spFolder.Files;
                        break;
                    }

                    DestinFileCollection(spFolder.SubFolders, fdUrl);
                }
            }
            return spFileCol;
        }

        /// <summary>
        /// Create folders at destination lib.
        /// </summary>
        /// <param name="spFolder"></param>
        /// <param name="fldURL"></param>
      private static void CreateFolder(SPFolder spFolder,string fldURL)
        {
            using (SPSite site=new SPSite(strSiteUrl))
            {
                using (SPWeb web=site.OpenWeb())
                {
                    object modified_by = spFolder.Item["Editor"];
                    object modified = spFolder.Item["Modified"];
                    object created = spFolder.Item["Created"];
                    object created_by = spFolder.Item["Author"];

                      SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;

                      SPFolderCollection spFolderCol = web.Folders;
                      spFolderCol.Add(strSiteUrl + "/" + strStrdestinationLib + "/" + fldURL + "/");
                    SPFolder spf=web.GetFolder(strSiteUrl + "/" + strStrdestinationLib + "/" + fldURL );
                    SPListItem objDisp = spf.Item as SPListItem;
                    objDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                    objDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                    objDisp.ParentList.Fields["Created By"].ReadOnlyField = false;
                    objDisp["Editor"] = modified_by;
                objDisp["Modified"] = modified;
                objDisp["Author"] = created_by;
                spf.Item.Update();

                      destination_lib.Update();
                }
               
            }
       
        }

2. configuration file

 <appSettings>
    <add key="SiteURL" value="http://sp2013vm:1616/sites/HSE"/>
    <add key="SourceLib" value="Test1"/>
    <add key="DestiLib" value="Test2"/>
  </appSettings>

Tuesday, December 23, 2014

Monday, November 18, 2013

Get Concurrent User list from IIS


1.       Enable the IIS Logs in the Server.
2. After Enable the log. Need to check whether the Fields are enabled or not.

3. Select your appropriate fields
4. After completed the above steps, need to install the “LogParser” tool to our server.
The log parser can be downloaded from the below location
5. Run “getConcurrentUser.bat” file.
code in bat file:
----------------------------------------------------------------------------------------------------------------------------------
cd\
c:
if exist c:\concurrentUser goto use_e
md concurrentUser
:use_e
cd C:\Program Files (x86)\Log Parser 2.2
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
set fdtm=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%
set fpath=c:\concurrentUser\userList_%fdtm%.csv
logparser -i:IISW3C -o:CSV "select distinct cs-username from C:\inetpub\logs\LogFiles\*.log" >%fpath% -recurse
Powershell.exe -executionpolicy remotesigned -File C:\britto\iislogdec\sendEmail.ps1 %fpath%
pause
-----------------------------------------------------------------------------------------------------------------------------
6. can able to get the output file from  “c:\concurrentUser” path. This “CSV” file is generated in the name of “userList_<current Date and Time>.csv”
7. To send this report to email through power shell (save file name as sendEmail.ps1)
###########Define Variables######## 

$fromaddress = "bretto.be@gmail.com" 
$toaddress = "bretto.be@gmail.com" 
$bccaddress = "bretto.be@gmail.com" 
$CCaddress = "bretto.be@gmail.com" 
$Subject = "Concurrent user report" 
#$body = get-content .\content.htm 
$body = "Please find the Concurrent user report file" 
$attachment =$args[0] 
$smtpserver = "smtp.gmail.com" 

#################################### 

$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress) 
$message.CC.Add($CCaddress) 
$message.Bcc.Add($bccaddress) 
$message.IsBodyHtml = $True 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$smtp.EnableSsl = $true

$smtp.Credentials = New-Object System.Net.NetworkCredential("bretto.be@gmail.com", "xyz");
$smtp.Send($message) 

#################################################################################

run the batch file we will get the mail with attachment.

Wednesday, November 13, 2013

Steps to Activate the custom timer job => Access denied when deploying a timer Job or activating a feature from SharePoint 2010 content web application


The following step i have used to followed to active the timer job.

Step 1: run the script in powershell command
function Set-RemoteAdministratorAccessDenied-False()
{
    # load sharepoint api libs
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $null

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

Set-RemoteAdministratorAccessDenied-False

step 2: activate the timer job feature in site collection feature.

Friday, August 10, 2012

SharePoint Branding

1. Sharepoint 2010 Fixed width Master Page Styling, no scrollbar issues.

Recently I have created my custom MasterPage in SharePoint Server. I have faced lots of issues to fix the fixed width. I have noticed when the Page load the SharePoint run the JavaScript function it search the <div> tag widh id  #s4-workspace and it fix the width and height for the page.

I have searched in google and got a reference, using that refernce i have commented <div id="s4-workspace"> open tag and end tag. It was working fine but it gives problem while using some webparts, means it never suport chat and repots webparts. So, i get failed.

Again i googled and get nice reference, as per the reference i have overright some class, after that my page was looking good what i expected.
Steps for below:
1. I have create one .css file and added into siteassets library.
2. Then Open that css file in SPD (SharePoint designer)
3. The following styles are write in that css file:
html{
    background-color:#55A0A7;
    overflow/**/:auto;   
}
body.v4master {
    width:1024px;
    margin:0px auto;
    overflow:visible;
    background-color: transparent !important;
}
.ms-dialog body.v4master {
    height: 100%;
    overflow: hidden;
    width: 100%;
}
body #s4-workspace {
    left: 0;
    overflow: auto !important;
    overflow/**/: visible !important;
    position: relative;
    width: 100% !important;
    display:table;
    border-spacing:0px;
}
.ms-dialog body #s4-workspace{
    display:block !important;
    overflow/**/: auto !important;
}

4. Then i have registed my css file into my custom MasterPage. like below line of code
<SharePoint:CssRegistration Name="SiteAssets/customStyle.css" runat="server" After="corev4.css" ></SharePoint:CssRegistration>