Thursday, October 30, 2014

Merge two pdf files using itextsharp


using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;

static void Main(string[] args)
        {
            String[] files = @"file1.pdf,file2.pdf".Split(',');
            MergeFiles(@"file1.pdf", files);
        }

        public static void MergeFiles(string destinationFile, string[] sourceFiles)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {    
                    PdfCopyFields copy = new PdfCopyFields(ms);  
                    copy.Writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
                    ArrayList outlines = new ArrayList();
                    int pageOffset = 0;
                    int f = 0;
                   
                    while (f < sourceFiles.Length)
                    {                 
                        string file = sourceFiles[f];
                        PdfReader reader = new PdfReader(file);                     
                        copy.AddDocument(reader);                      
                        pageOffset += reader.NumberOfPages;
                        f++;
                    }                  
                    copy.Close();
                    MemoryStreamToFile(ms, destinationFile);
                }
            }
            catch (System.Exception e)
            {
                System.Console.Error.WriteLine(e.Message);
                System.Console.Error.WriteLine(e.StackTrace);
                System.Console.ReadLine();
            }
        }
        public static void MemoryStreamToFile(MemoryStream MS, string FileName)
        {
            using (FileStream fs = new FileStream(@FileName, FileMode.Create))
            {
                byte[] data = MS.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Close();
            }
  }

Wednesday, October 1, 2014

Log javascript error into sharepoint ULS

catch (e) {
        logMessageToULS(e.message, 'Custom.js');
}

Error Log File

// Registering the ULS logging function on a global level.
window.onerror = logErrorToULS;

// Set default value for teamName.
var teamName = "Biraj Office App";

// Further add the logErrorToULS method at the end of the script.

function logMessageToULS(message, fileName) {
    if (message != null) {
        var ulsObj = new ulsObject();
        ulsObj.message = message;
        ulsObj.file = fileName;
        ulsObj.line = 0; // We don't know the line, so we set it to zero.
        ulsObj.stack = getCallStack(logMessageToULS.caller);
        //ulsObj.client = getClientInfo();
        ulsObj.team = teamName;
        ulsObj.originalFile = ulsObj.file;

        var soapPacket = generateErrorPacket(ulsObj);
        postMessageToULSSvc(soapPacket);
    }
}
// Function to log messages to Diagnostic web service.
// Invoked by the window.onerror message.
function logErrorToULS(msg, url, linenumber) {
    var ulsObj = new ulsObject();
    ulsObj.message = "Error occurred: " + msg;
    ulsObj.file = url.substring(url.lastIndexOf("/") + 1); // Get the current file name.
    ulsObj.line = linenumber;
    ulsObj.stack = getCallStack(logErrorToULS.caller); // Create error call stack.   
    ulsObj.team = teamName; // Declared in the consumer script.
    ulsObj.originalFile = ulsObj.file;

    var soapPacket = generateErrorPacket(ulsObj); // Create the soap packet.
    postMessageToULSSvc(soapPacket); // Post to the web service.

    return true;
}
// Creates a custom ulslog object
// with the required properties.
function ulsObject() {
    this.message = null;
    this.file = null;
    this.line = null;
    this.client = null;
    this.stack = null;
    this.team = null;
    this.originalFile = null;
}
function getCallStack(functionDef, depth) {
    if (functionDef != null) {
        var signature = '';
        functionDef = functionDef.toString();
        signature = functionDef.substring(0, functionDef.indexOf("{"));
        if (signature.indexOf("function") == 0) {
            signature = signature.substring(8);
        }

        if (depth == 0) {
            var stack = "<stack><function depth='0' signature='{0}'>{1}</function></stack>";
            stack = String.format(stack, signature, functionDef);
        }
        else {
            var stack = "<stack><function depth='1' signature='{0}'></function></stack>";
            stack = String.format(stack, signature);
        }

        return stack;
    }

    return "";
}

// Creates the SOAP packet required by SendClientScriptErrorReport
// web method.
function generateErrorPacket(ulsObj) {
    var soapPacket = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                                       "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                                       "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                          "<soap:Body>" +
                            "<SendClientScriptErrorReport " +
                              "xmlns=\"http://schemas.microsoft.com/sharepoint/diagnostics/\">" +
                              "<message>{0}</message>" +
                              "<file>{1}</file>" +
                              "<line>{2}</line>" +
                              "<stack>{3}</stack>" +
                              "<client>{4}</client>" +
                              "<team>{5}</team>" +
                              "<originalFile>{6}</originalFile>" +
                            "</SendClientScriptErrorReport>" +
                          "</soap:Body>" +
                        "</soap:Envelope>";

    soapPacket = String.format(soapPacket, encodeXmlString(ulsObj.message), encodeXmlString(ulsObj.file),
                 ulsObj.line, encodeXmlString(ulsObj.stack), encodeXmlString(ulsObj.client),
                 encodeXmlString(ulsObj.team), encodeXmlString(ulsObj.originalFile));

    return soapPacket;
}

// Utility function to encode special characters in XML.
function encodeXmlString(txt) {
    txt = String(txt);
    txt = jQuery.trim(txt);
    txt = txt.replace(/&/g, "&amp;");
    txt = txt.replace(/</g, "&lt;");
    txt = txt.replace(/>/g, "&gt;");
    txt = txt.replace(/'/g, "&apos;");
    txt = txt.replace(/"/g, "&quot;");

    return txt;
}

// Function to form the Diagnostics service URL.
function getWebSvcUrl() {
    var serverurl = location.href;
    if (serverurl.indexOf("?") != -1) {
        serverurl = serverurl.replace(location.search, '');
    }

    var index = serverurl.lastIndexOf("/");
    serverurl = serverurl.substring(0, index - 1);
    serverurl = serverurl.concat('/_vti_bin/diagnostics.asmx');

    return serverurl;
}

// Method to post the SOAP packet to the Diagnostic web service.
function postMessageToULSSvc(soapPacket) {
    $(document).ready(function () {
        $.ajax({
            url: getWebSvcUrl(),
            type: "POST",
            dataType: "xml",
            data: soapPacket, //soap packet.
            contentType: "text/xml; charset=\"utf-8\"",
            success: handleResponse, // Invoke when the web service call is successful.
            error: handleError// Invoke when the web service call fails.
        });
    });
}

// Invoked when the web service call succeeds.
function handleResponse(data, textStatus, jqXHR) {
    // Custom code...
    $('#message').html('Something went wrong. Please try after sometime!');
}

// Invoked when the web service call fails.
function handleError(jqXHR, textStatus, errorThrown) {
    //Custom code...
    $('#message').html('Error occurred in executing the web request');

}

Sharepoint updated created by and modified by forcefully


item["Author"] = new SPFieldUserValue(web, SPContext.Current.Web.CurrentUser.ID, SPContext.Current.Web.CurrentUser.LoginName);
                        item["Editor"] = new SPFieldUserValue(web, SPContext.Current.Web.CurrentUser.ID, SPContext.Current.Web.CurrentUser.LoginName);
                        item.Update();

Thursday, August 21, 2014

Instantly Convert docx file into PDF using word automation service in sharepoint 2013

Instantly Convert file into PDF using word automation service in sharepoint 2013


private void SaveAsPDF(SPSite siteAsAdmin, SPWeb web, SPFile DocFile)
        {
            try
            {
                SPFolder destFolder = web.Lists.TryGetList(PdfDocLibName).RootFolder;
                SPFile destFile = null;
                destFile = destFolder.Files.Add(Path.GetFileNameWithoutExtension(DocFile.Url) + ".pdf", ConvertWordToPDF(siteAsAdmin, web, DocFile), false);
                destFile.Item.Update();
                if (destFile.CheckOutType != SPFile.SPCheckOutType.None)
                {
                    destFile.CheckIn("Checked in programatically. Document generation completed.");
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
              
        private byte[] ConvertWordToPDF(SPSite siteAsAdmin, SPWeb web, SPFile DocFile)
        {
            byte[] result = null;
            try
            {
                using (Stream read = DocFile.OpenBinaryStream())
                {
                    using (MemoryStream write = new MemoryStream())
                    {
                        // Initialise Word Automation Service
                        SyncConverter sc = new SyncConverter(wordAutomationServiceName);
                        sc.UserToken = siteAsAdmin.SystemAccount.UserToken;
                        sc.Settings.UpdateFields = true;
                        sc.Settings.OutputFormat = SaveFormat.PDF;

                        // Convert to PDF
                        ConversionItemInfo info = sc.Convert(read, write);
                        if (info.Succeeded)
                            result = write.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
            return result;
        }