private OASResponse ConvertPPTImmediately(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    byte[]       input     = Convert.FromBase64String(settings.Content);
                    MemoryStream outstream = new MemoryStream();

                    try
                    {
                        Microsoft.Office.Server.PowerPoint.Conversion.FixedFormatSettings ppsettings = FillPowerPointConversionOptions(settings.Options);

                        PdfRequest request = new PdfRequest(new MemoryStream(input), ".pptx", ppsettings, outstream);

                        IAsyncResult result = request.BeginConvert(SPServiceContext.GetContext(site), null, null);

                        // Use the EndConvert method to get the result.
                        request.EndConvert(result);

                        oasResponse.Content   = Convert.ToBase64String(outstream.ToArray());
                        oasResponse.ErrorCode = OASErrorCodes.Success;
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }
        private OASResponse ConvertWordImmediately(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            ConversionJobSettings set = FillWordConversionOptions(settings.Options);

            set.OutputFormat = SaveFormat.PDF;

            SyncConverter syncConv = new SyncConverter(ConfigurationManager.AppSettings["WASName"], set);

            if (userToken != null)
            {
                syncConv.UserToken = userToken;
            }

            byte[]             input = Convert.FromBase64String(settings.Content);
            byte[]             output;
            ConversionItemInfo convInfo = syncConv.Convert(input, out output);

            if (convInfo.Succeeded)
            {
                oasResponse.Content   = Convert.ToBase64String(output);
                oasResponse.ErrorCode = OASErrorCodes.Success;
            }
            else
            {
                oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                oasResponse.Message   = convInfo.ErrorMessage;
            }

            return(oasResponse);
        }
        private OASResponse StartPPTConversion(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;

                        byte[] input = Convert.FromBase64String(settings.Content);

                        SPFolder lib = GetOASLibrary(web);

                        //add source file to library
                        string source  = Guid.NewGuid().ToString();
                        SPFile srcfile = lib.Files.Add(source, input, true);

                        string dest = source + EXTENSION;


                        //Set up the job
                        MemoryStream ms = new MemoryStream();
                        Microsoft.Office.Server.PowerPoint.Conversion.FixedFormatSettings ppsettings = FillPowerPointConversionOptions(settings.Options);

                        PdfRequest request = new PdfRequest(new MemoryStream(input), ".pptx", ppsettings, ms);

                        PPTJob job = new PPTJob();
                        job.source  = source;
                        job.dest    = dest;
                        job.web     = web;
                        job.output  = ms;
                        job.request = request;

                        IAsyncResult result = request.BeginConvert(SPServiceContext.GetContext(web.Site), PPTConversionFinished, job);

                        // put file to the processing list
                        AddFileToList(web, job.jobId.ToString(), dest, DocType.PPTX);

                        oasResponse.FileId    = job.jobId.ToString();
                        oasResponse.ErrorCode = OASErrorCodes.Success;
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }
        private OASResponse StartWordConversion(OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;

                        byte[] input = Convert.FromBase64String(settings.Content);

                        SPFolder lib = GetOASLibrary(web);

                        //add source file to library
                        string source  = Guid.NewGuid().ToString();
                        SPFile srcfile = lib.Files.Add(source, input, true);

                        string dest = source + EXTENSION;


                        //Set up the job
                        ConversionJobSettings set = FillWordConversionOptions(settings.Options);
                        set.OutputFormat = SaveFormat.PDF;

                        ConversionJob syncConv = new ConversionJob(ConfigurationManager.AppSettings["WASName"], set);
                        if (userToken != null)
                        {
                            syncConv.UserToken = userToken;
                        }

                        syncConv.AddFile(web.Url + "/" + lib.Url + "/" + source, web.Url + "/" + lib.Url + "/" + dest);
                        syncConv.Start();

                        // put file to the processing list
                        AddFileToList(web, syncConv.JobId.ToString(), dest, DocType.DOCX);

                        oasResponse.FileId    = syncConv.JobId.ToString();
                        oasResponse.ErrorCode = OASErrorCodes.Success;
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }
        public async Task <OASResponse> GetFile(string fileid, OASModels.ConversionSettings settings)
        {
            OASResponse oasResponse = new OASResponse();

            try
            {
                SPUserToken userToken = GetUserToken(settings, ref oasResponse);
                if (oasResponse.ErrorCode != OASErrorCodes.Success)
                {
                    return(oasResponse);
                }

                // process using provided user token
                oasResponse = GetConvertedFile(fileid, settings, userToken);
            }
            catch (Exception ex)
            {
                oasResponse.ErrorCode = OASErrorCodes.ErrUnknown;
                oasResponse.Message   = ex.Message;
            }

            return(oasResponse);
        }
        public async Task <OASResponse> StartConvertJob(DocType doctype, OASModels.ConversionSettings settings)
        {
            OASResponse oasResponse = new OASResponse();

            try
            {
                SPUserToken userToken = GetUserToken(settings, ref oasResponse);
                if (oasResponse.ErrorCode != OASErrorCodes.Success)
                {
                    return(oasResponse);
                }

                switch (doctype)
                {
                case DocType.DOCX:

                    // process using provided user token
                    oasResponse = StartWordConversion(settings, userToken);

                    break;

                case DocType.PPTX:

                    // process using provided user token
                    oasResponse = StartPPTConversion(settings, userToken);

                    break;
                }
            }
            catch (Exception ex)
            {
                oasResponse.ErrorCode = OASErrorCodes.ErrUnknown;
                oasResponse.Message   = ex.Message;
            }

            return(oasResponse);
        }
        private SPUserToken GetUserToken(OASModels.ConversionSettings settings, ref OASModels.OASResponse oasResponse)
        {
            SPUserToken userToken = null;

            if (settings.Username != string.Empty && settings.Domain != string.Empty)
            {
                OASResponse resp = new OASResponse();

                // check for valid user credentials
                bool isValid = false;

                /*
                 * using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, settings.Domain))
                 * {
                 *  // validate the credentials
                 *  isValid = pc.ValidateCredentials(settings.Username, settings.Password);
                 * }
                 * if (!isValid)
                 * {
                 *  oasResponse.ErrorCode = OASErrorCodes.ErrWrongCredentials;
                 *  oasResponse.Message = "Wrong credentials were passed.";
                 * }
                 */

                IntPtr tokenHandler = IntPtr.Zero;
                isValid = LogonUser(settings.Username, settings.Domain, settings.Password, 2, 0, ref tokenHandler);
                if (!isValid)
                {
                    oasResponse.ErrorCode = OASErrorCodes.ErrWrongCredentials;
                    oasResponse.Message   = "Wrong credentials were passed.";
                    return(userToken);
                }

                WindowsImpersonationContext impersonationContext = WindowsIdentity.Impersonate(tokenHandler);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        SPSite site1 = new SPSite(ConfigurationManager.AppSettings["SiteUrl"]);
                        userToken    = site1.RootWeb.AllUsers["i:0#.w|" + settings.Domain + "\\" + settings.Username].UserToken;
                    }
                    catch (Exception ex)
                    {
                        resp.ErrorCode = OASErrorCodes.ErrWrongCredentials;
                        resp.Message   = ex.Message;
                    }
                });

                if (impersonationContext != null)
                {
                    impersonationContext.Undo();
                }

                if (tokenHandler != IntPtr.Zero)
                {
                    CloseHandle(tokenHandler);
                }

                oasResponse = resp;
            }
            else
            {
                //get current user for AppPool and try get his token
                string usename = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                OASResponse resp = new OASResponse();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        SPSite site1 = new SPSite(ConfigurationManager.AppSettings["SiteUrl"]);
                        userToken    = site1.RootWeb.AllUsers["i:0#.w|" + usename].UserToken;
                    }
                    catch (Exception ex)
                    {
                        resp.ErrorCode = OASErrorCodes.ErrWrongCredentials;
                        resp.Message   = ex.Message;
                    }
                });

                oasResponse = resp;
            }

            return(userToken);
        }
        private OASResponse GetConvertedFile(string fileid, OASModels.ConversionSettings settings, SPUserToken userToken)
        {
            OASResponse oasResponse = new OASResponse();

            using (SPSite site = (userToken == null ? new SPSite(ConfigurationManager.AppSettings["SiteUrl"]) : new SPSite(ConfigurationManager.AppSettings["SiteUrl"], userToken)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        // Get list of "old" file and delete them
                        RemoveOldFiles(web);

                        //check conversion type
                        DocType dtype = GetJobType(web, fileid);
                        switch (dtype)
                        {
                        case DocType.DOCX:

                            // check if the current file conversion is finished
                            ConversionJobStatus status = new ConversionJobStatus(ConfigurationManager.AppSettings["WASName"], Guid.Parse(fileid), null);
                            if (status.Succeeded == 1)
                            {
                                // return finished document
                                SPFile dest = GetFinishedFile(web, fileid);
                                if (dest != null)
                                {
                                    oasResponse.Content   = Convert.ToBase64String(dest.OpenBinary());
                                    oasResponse.ErrorCode = OASErrorCodes.Success;

                                    // remove converted file
                                    RemoveConversionFiles(web, fileid);
                                }
                                else
                                {
                                    oasResponse.ErrorCode = OASErrorCodes.ErrFileNotExists;
                                    oasResponse.Message   = "Converted file not exists";
                                }
                            }
                            else if (status.InProgress == 1 || status.NotStarted == 1)
                            {
                                //file not converted yet
                                oasResponse.ErrorCode = OASErrorCodes.Success;
                            }
                            else
                            {
                                // something went wrong and file was not converted
                                oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                                oasResponse.Message   = "File conversion job error";

                                RemoveConversionFiles(web, fileid);
                            }

                            break;

                        case DocType.PPTX:

                            // check if the current file conversion is finished

                            if (IsJobFinished(web, fileid))
                            {
                                // return finished document
                                SPFile dest = GetFinishedFile(web, fileid);
                                if (dest != null)
                                {
                                    oasResponse.Content   = Convert.ToBase64String(dest.OpenBinary());
                                    oasResponse.ErrorCode = OASErrorCodes.Success;

                                    // remove converted file
                                    RemoveConversionFiles(web, fileid);
                                }
                                else
                                {
                                    oasResponse.ErrorCode = OASErrorCodes.ErrFileNotExists;
                                    oasResponse.Message   = "Converted file not exists";
                                }
                            }

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        oasResponse.ErrorCode = OASErrorCodes.ErrFailedConvert;
                        oasResponse.Message   = ex.Message;
                    }
                }
            }

            return(oasResponse);
        }