Exemple #1
0
        static void Main(string[] args)
        {
            var parsedResult = Parser.Default.ParseArguments <Options>(args);

            parsedResult.WithParsed(options =>
            {
                try
                {
                    using (Impersonation.LogonUser(options.Domain, options.Username, options.Password, LogonType.Interactive))
                    {
                        var process = new Process();
                        process.StartInfo.FileName  = options.Command;
                        process.StartInfo.Arguments = options.Arguments;
                        process.Start();
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            });

            parsedResult.WithNotParsed((error) =>
            {
                Console.ReadKey();
            });
        }
        // TODO-osy: Use Entity Framework
        public IList <Contact> FindAccountContacts(string accountId)
        {
            const string storedProcedureName = "sp_findAccountContacts";
            var          contacts            = new List <Contact>();

            // IMPORTANT: You have to use LogonType.NewCredentials!!!
            // http://stackoverflow.com/questions/559719/windows-impersonation-from-c-sharp
            using (var impersonation = Impersonation.LogonUser(DOMAIN, USERNAME, PASSWORD, LogonType.NewCredentials))
            {
                using (DbConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = storedProcedureName;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.Parameters.Add(new SqlParameter("@accountID", accountId));
                        using (var dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                var contact = new Contact();
                                contact.ContactId   = Convert.ToString(dataReader["contactID"]);
                                contact.FirstName   = Convert.ToString(dataReader["firstName"]);
                                contact.LastName    = Convert.ToString(dataReader["lastName"]);
                                contact.ContactType = Convert.ToString(dataReader["contactType"]);
                                contact.Function    = Convert.ToString(dataReader["function"]);
                                contacts.Add(contact);
                            }
                        }
                    }
                }
            }
            return(contacts);
        }
Exemple #3
0
        public WSUS()
        {
            // I use impersonation to use other logon than mine. Remove the following "using" if not needed
            using (Impersonation.LogonUser("mydomain.local", "admin_account_wsus", "Password", LogonType.Batch))
            {
                ComputerTargetScope      scope   = new ComputerTargetScope();
                IUpdateServer            server  = AdminProxy.GetUpdateServer("wsus_server.mydomain.local", false, 80);
                ComputerTargetCollection targets = server.GetComputerTargets(scope);
                // Search
                targets = server.SearchComputerTargets("any_server_name_or_ip");

                // To get only on server FindTarget method
                IComputerTarget target = FindTarget(targets, "any_server_name_or_ip");
                Console.WriteLine(target.FullDomainName);
                IUpdateSummary summary      = target.GetUpdateInstallationSummary();
                UpdateScope    _updateScope = new UpdateScope();
                // See in UpdateInstallationStates all other properties criteria
                _updateScope.IncludedInstallationStates = UpdateInstallationStates.Downloaded;
                UpdateInstallationInfoCollection updatesInfo = target.GetUpdateInstallationInfoPerUpdate(_updateScope);

                int updateCount = updatesInfo.Count;

                foreach (IUpdateInstallationInfo updateInfo in updatesInfo)
                {
                    Console.WriteLine(updateInfo.GetUpdate().Title);
                }
            }
        }
        public void ImpersonateUser()
        {
            string currentUser = WindowsIdentity.GetCurrent().Name;

            using (var impersonation = Impersonation.LogonUser(DOMAIN, USERNAME, PASSWORD, LogonType.Network))
            {
                var impersonatedUser = WindowsIdentity.GetCurrent().Name;
            }
        }
Exemple #5
0
 public void ImpersonateContainerUser(Action f)
 {
     using (Impersonation.LogonUser("", user.UserName, user.GetCredential().Password, LogonType.Interactive))
     {
         lock (_ioLock)
         {
             f();
         }
     }
 }
Exemple #6
0
        public string SaveFile(HttpPostedFileBase file, string path, string documento, out string exception, out string pathsaved, string ejercicio)
        {
            string ex = "";
            //string exdir = "";
            // Get the name of the file to upload.
            string fileName = Path.GetFileName(file.FileName); // must be declared in the class above

            // Specify the path to save the uploaded file to.
            //string savePath = path + documento + "\\";//RSG 01.08.2018
            string savePath = path + ejercicio + "\\" + documento + "\\";//RSG 01.08.2018

            // Create the path and file name to check for duplicates.
            string pathToCheck = savePath;

            // Append the name of the file to upload to the path.
            savePath += fileName;

            string saveFileDev = ConfigurationManager.AppSettings["saveFileDev"];

            try
            {
                if (saveFileDev == "1")
                {
                    //Guardar el archivo
                    file.SaveAs(savePath);
                }
                else
                {
                    //file to domain
                    //Parte para guardar archivo en el servidor
                    string serverDocs     = ConfigurationManager.AppSettings["serverDocs"],
                           serverDocsUser = ConfigurationManager.AppSettings["serverDocsUser"],
                           serverDocsPass = ConfigurationManager.AppSettings["serverDocsPass"];
                    using (Impersonation.LogonUser(serverDocs, serverDocsUser, serverDocsPass, LogonType.NewCredentials))
                    {
                        //Guardar el archivo
                        file.SaveAs(savePath);
                    }
                }
            }
            catch (Exception e)
            {
                ex = "";
                ex = fileName;
                Log.ErrorLogApp(e, "Files", "SaveFile");
            }

            pathsaved = savePath;
            exception = ex;
            return(fileName);
        }
Exemple #7
0
        public void ObserveAFCachePerUser()
        {
            AFElement element1 = AFObject.FindObject(elementPath) as AFElement;
            AFElement element2 = AFObject.FindObject(elementPath) as AFElement;

            Assert.Same(element1, element2);

            // You'll need a local user named 'testuser' with password
            // '@bcd1234' to run this case.
            using (Impersonation.LogonUser(
                       null, "testuser", "@bcd1234", LogonType.Network))
            {
                element2 = AFObject.FindObject(elementPath) as AFElement;
            }

            Assert.NotSame(element1, element2);
        }
Exemple #8
0
        public string createDir(string path, string documento, string ejercicio)
        {
            string ex = "";

            // Specify the path to save the uploaded file to.
            string savePath = path + ejercicio + "\\" + documento + "\\";//RSG 01.08.2018

            // Create the path and file name to check for duplicates.
            string pathToCheck = savePath;

            Log.Info(pathToCheck);
            try
            {
                string saveFileDev = ConfigurationManager.AppSettings["saveFileDev"];
                if (!System.IO.File.Exists(pathToCheck))
                {
                    //No existe, se necesita crear
                    if (saveFileDev == "1")
                    {
                        Directory.CreateDirectory(pathToCheck);
                    }
                    else
                    {
                        string serverDocs     = ConfigurationManager.AppSettings["serverDocs"],
                               serverDocsUser = ConfigurationManager.AppSettings["serverDocsUser"],
                               serverDocsPass = ConfigurationManager.AppSettings["serverDocsPass"];
                        using (Impersonation.LogonUser(serverDocs, serverDocsUser, serverDocsPass, LogonType.NewCredentials))
                        {
                            Directory.CreateDirectory(pathToCheck);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.ErrorLogApp(e, "Files", "createDir");
                ex = "No se puede crear el directorio para guardar los archivos";
            }

            return(ex);
        }
        private bool ValidateIOPermission(string path)
        {
            string user = "";
            string pass = "";
            string dom  = "";

            user = getUserPrel();
            pass = getPassPrel();
            dom  = getDomPrel();
            try
            {
                using (Impersonation.LogonUser(dom, user, pass, LogonType.NewCredentials))
                {
                    try
                    {
                        if (Directory.Exists(path))
                        {
                            return(true);
                        }

                        else
                        {
                            Directory.CreateDirectory(path);
                            return(true);
                        }
                    }

                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemple #10
0
        public List <Byte[]> GetViolationImagesById(long ViolationNotificationId)
        {
            try
            {
                using (Impersonation.LogonUser("AGHQSRV453", @"AUH-POLICE\stcadmin", "P@ssword1", LogonType.Network))
                {
                    List <Byte[]> lst = new List <byte[]>();
                    Byte[]        img = null;

                    var lstImages = stcDataContext.ViolationImageViews
                                    .Where(image => image.ActivityId == ViolationNotificationId && image.ImageCategoryId == (int)STC.Projects.ClassLibrary.DAL.Utilities.ImageCategory.Photo)
                                    .Select(url => url.BinaryLocationURI).ToList();

                    if (lstImages != null)
                    {
                        foreach (var uriString in lstImages)
                        {
                            img = (new WebClient()).DownloadData(new Uri(uriString));

                            if (img != null)
                            {
                                lst.Add(img);
                            }
                        }

                        return(lst);
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            return(null);
        }
        /// <summary>
        /// Copy the source folder content into a destination folder
        /// </summary>
        /// <param name="srcPath">source folder</param>
        /// <param name="destPath">destination folder</param>
        /// <returns>true if success</returns>
        private bool CopyFolderAndFilesWithImpersonation(string configID, string srcPath, string domainSrc, string userSrc, string passSrc,
                                                         string destPath, string domainDest, string userDest, string passDest, out Exception outEx)
        {
            outEx        = null;
            myCollection = new ConcurrentQueue <CopyOperation>();

            byte[]    buffer    = new byte[bufferSize];
            bool      finished  = false;
            Exception srcError  = null;
            Exception destError = null;
            Thread    thSource  = new Thread(() =>
            {
                try
                {
                    //FileLogging.Log($"begin thSrc.", LogLevel.Info);
                    using (Impersonation.LogonUser(domainSrc, userSrc, passSrc, LogonType.Network))//LogonType.Interactive
                    {
                        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                        //FileLogging.Log($"impersonated thSrc.  {wid_current.Name}", LogLevel.Info);
                        //scan all of the directories
                        var lstDirectories = Directory.GetDirectories(srcPath, "*", SearchOption.AllDirectories);
                        dirCount           = lstDirectories.LongCount();
                        foreach (string dirPath in lstDirectories)
                        {
                            CopyOperation coFolder = new CopyOperation
                            {
                                Operation = OperationType.WriteFolder,
                                Argument  = dirPath.Replace(srcPath, string.Empty)
                            };
                            FillQueue(myCollection, queueTHRESHOLD, destError, coFolder);
                            if (forceExceptionalStop)
                            {
                                return;
                            }
                            //FileLogging.Log($"q-d: {coFolder.Argument}", LogLevel.Info);
                        }
                        //scan all files
                        var lstFiles = Directory.GetFiles(srcPath, "*.*", SearchOption.AllDirectories);
                        fileCount    = lstFiles.LongCount();
                        foreach (string newPath in lstFiles)
                        {
                            using (FileStream fs = File.Open(newPath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read))
                            {
                                int readB;
                                long offset = 0;
                                while ((readB = fs.Read(buffer, 0, bufferSize)) > 0)
                                {
                                    CopyOperation coFile = new CopyOperation
                                    {
                                        Operation = OperationType.WriteFile,
                                        Argument  = newPath.Replace(srcPath, string.Empty),
                                        Offset    = offset,
                                        Content   = buffer.SubArray(0, readB)
                                    };
                                    FillQueue(myCollection, queueTHRESHOLD, destError, coFile);
                                    if (forceExceptionalStop)
                                    {
                                        return;
                                    }
                                    //FileLogging.Log($"q-f: {coFile.Argument} - {coFile.Offset}", LogLevel.Info);
                                    offset += readB;
                                }
                            }
                        }
                        //YEY!
                        finished = true;

                        //wic.Undo();
                    }
                }
                catch (Exception err)
                {
                    srcError             = err;
                    forceExceptionalStop = true;
                    finished             = true;
                }
            });


            Thread thDest = new Thread(() =>
            {
                try
                {
                    //FileLogging.Log($"begin thDest.", LogLevel.Info);
                    Thread.Sleep(200);

                    long dirIndex     = 0, fileIndex = 0;
                    string lastFile   = string.Empty;
                    DateTime lastSent = DateTime.MinValue;
                    int copyPercent;
                    using (Impersonation.LogonUser(domainDest, userDest, passDest, LogonType.NewCredentials))//LogonType.NewCredentials
                    {
                        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                        //FileLogging.Log($"impersonated thDest.  {wid_current.Name}", LogLevel.Info);
                        while (!finished || myCollection.Count > 0)
                        {
                            while (myCollection.Count == 0 && !forceExceptionalStop)
                            {
                                Thread.Sleep(100);
                            }
                            if (forceExceptionalStop)
                            {
                                return;
                            }

                            CopyOperation item = null;
                            if (myCollection.TryDequeue(out item))
                            {
                                switch (item.Operation)
                                {
                                case OperationType.WriteFolder:
                                    string newFolder = UncCombine(destPath, item.Argument);
                                    Directory.CreateDirectory(newFolder);
                                    dirIndex++;
                                    break;

                                case OperationType.WriteFile:
                                    string destFile = UncCombine(destPath, item.Argument);
                                    using (var fs = ((item.Offset == 0) && File.Exists(destFile)) ? File.Create(destFile) : File.OpenWrite(destFile))
                                    {
                                        fs.Seek(item.Offset, SeekOrigin.Begin);
                                        fs.Write(item.Content, 0, item.Content.Length);
                                    }
                                    if (destFile != lastFile)
                                    {
                                        fileIndex++;
                                        lastFile = destFile;
                                    }
                                    break;

                                default:
                                    break;
                                }
                                //update report status
                                DateTime now = DateTime.UtcNow;
                                if (now > lastSent)
                                {
                                    copyPercent = Convert.ToInt32(20 * (dirCount > 0 ? (double)dirIndex / dirCount : 1) + 80 * (fileCount > 0 ? (double)fileIndex / fileCount : 1));
                                    lastSent    = now + TimeSpan.FromMilliseconds(SignalRController.SIGNALR_REFRESH_INTERVAL);
                                    ReportAgentStatus(item.Operation == OperationType.WriteFolder ? StatusType.CopyFolders : StatusType.CopyFiles,
                                                      item.Operation == OperationType.WriteFolder ? $"Copy folders in progress {dirIndex}/{dirCount} ..." : $"Copy files in progress {fileIndex}/{fileCount} ..."
                                                      , copyPercent, configID);
                                }
                            }
                            else
                            {
                                throw new ArgumentException("Could not extract item from queue");
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    destError            = err;
                    forceExceptionalStop = true;
                }
            });

            //clear exception
            forceExceptionalStop = false;

            thDest.Start();
            thSource.Start();

            //wait to complete or fail
            thSource.Join();
            thDest.Join();


            myCollection = new ConcurrentQueue <CopyOperation>();


            if (srcError != null)
            {
                outEx = srcError;
                logger.Error($"srcErr: {srcError}");
                return(false);
            }
            if (destError != null)
            {
                outEx = destError;
                logger.Error($"destErr: {destError}");
                return(false);
            }
            if (externalError != null)
            {
                outEx = externalError;
                logger.Debug($"externalError: {destError}");
                return(false);
            }


            logger.Error($"LAN Copy completed!");

            return(true);
        }
        public string generarArchivo(decimal docum, string accion, string fechacon)//MGC-14-12-2018 Modificación fechacon
        {
            string errorMessage = "";

            try
            {
                string    dirFile = "";
                DOCUMENTO doc     = db.DOCUMENTOes.Where(x => x.NUM_DOC == docum).Single();
                TSOL      ts      = db.TSOLs.Where(tsi => tsi.ID == doc.TSOL_ID).FirstOrDefault();

                string   txt = "";
                string   msj = "";
                string[] cc;
                string   cta = "";

                string carpeta = "in";//MGC 22-10-2018 Archivo local en servidor

                //Obtener la configuración de la url desde app setting
                string url_prel = "";
                try
                {
                    //url_prel = db.APPSETTINGs.Where(aps => aps.NOMBRE.Equals("URL_PREL") && aps.ACTIVO == true).FirstOrDefault().VALUE.ToString();//MGC 22-10-2018 Archivo local en servidor
                    //url_prel += @"POSTING";//MGC 22-10-2018 Archivo local en servidor
                    url_prel = getDirPrel(carpeta);
                    dirFile  = url_prel;
                }
                catch (Exception e)
                {
                    dirFile = ConfigurationManager.AppSettings["URL_PREL"].ToString() + @"in";
                }


                //MGC 22-10-2018 Archivo local en servidor
                //Verificar si el directorio existe y si hay permiso
                bool existd = ValidateIOPermission(dirFile);

                //El direcorio existe
                if (existd)
                {
                    //dirFile = ConfigurationManager.AppSettings["URL_PREL"].ToString() + @"POSTING";
                    string docname = dirFile + @"\INBOUND_PREL" + ts.ID.Substring(0, 3) + docum.ToString().PadLeft(10, '0') + "-1";

                    //MGC 11-10-2018 Acciones para el encabezado -->

                    string variable   = "";
                    string accionhead = "";
                    //Preliminar
                    if (accion == "P")
                    {
                        variable = "ACCION_CREAR";
                        fechacon = "";//MGC-14-12-2018 Modificación fechacon
                    }
                    else if (accion == "R")
                    {
                        variable = "ACCION_BC";
                        fechacon = "";//MGC-14-12-2018 Modificación fechacon
                    }
                    else if (accion == "A")
                    {
                        variable = "ACCION_CONTABILIZAR";
                    }

                    //Obtener el nombre de la acción desde la bd en APPSETTING
                    try
                    {
                        accionhead = db.APPSETTINGs.Where(aps => aps.NOMBRE.Equals(variable) && aps.ACTIVO == true).FirstOrDefault().VALUE.ToString();
                    }
                    catch (Exception e)
                    {
                    }

                    //MGC 11-10-2018 Acciones para el encabezado <--


                    doc.FECHAC = Fecha("D", Convert.ToDateTime(doc.FECHAC));

                    List <DetalleContab> det = new List <DetalleContab>();

                    //MemoryStream stIn = new MemoryStream();
                    string user = "";
                    string pass = "";
                    string dom  = "";

                    user = getUserPrel();
                    pass = getPassPrel();
                    dom  = getDomPrel();
                    using (Impersonation.LogonUser(dom, user, pass, LogonType.NewCredentials))
                    {
                        try
                        {
                            FileStream fs = null;
                            fs = new FileStream(docname, FileMode.CreateNew);
                            using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII))
                            {
                                string belnr = "";
                                string bjahr = "";
                                string bukrs = "";

                                if (accion == "R")
                                {
                                    belnr = doc.NUM_PRE + "";
                                    bjahr = doc.EJERCICIO_PRE + "";
                                    bukrs = doc.SOCIEDAD_PRE + "";
                                }

                                //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado -->
                                sw.WriteLine(
                                    "1" + "|" +
                                    ts.TIPO_DOCFILE.Trim() + "|" +
                                    doc.NUM_DOC + "|" +
                                    accionhead.Trim() + "|" +
                                    belnr + "|" +
                                    bjahr + "|" +
                                    bukrs //MGC 19-10-2018 Cambio en archivo
                                    );
                                //sw.WriteLine(""); //MGC 17-10-2018.2 Adaptación a archivo

                                //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado <--

                                //Formato a fecha mes, día, año
                                sw.WriteLine(
                                    "2" + "|" +
                                    doc.DOCUMENTO_SAP + "|" +
                                    doc.SOCIEDAD_ID.Trim() + "|" +
                                    String.Format("{0:dd.MM.yyyy}", doc.FECHAC).Replace(".", "") + "|" + //Formato MGC
                                    doc.MONEDA_ID.Trim() + "|" +
                                    //+ "|" + //MGC 11-10-2018 Acciones para el encabezado
                                    doc.REFERENCIA.Trim() + "|" +
                                    doc.CONCEPTO + "|" + //MGC 11-10-2018 Acciones para el encabezado
                                    "" + "|" +
                                    "" + "|" +
                                    doc.TIPO_CAMBIO  //MGC 11-10-2018 Acciones para el encabezado
                                    + "|" + fechacon //MGC-14-12-2018 Modificación fechacon//MGC 13-10-2018 Modificaión fecha
                                    );
                                //sw.WriteLine("");//MGC 17-10-2018.2 Adaptación a archivo
                                //for (int i = 0; i < det.Count; i++)

                                //Obtener los rows H
                                List <DOCUMENTOP> lh = doc.DOCUMENTOPs.Where(docl => docl.ACCION == "H").ToList();
                                List <DOCUMENTOP> ld = doc.DOCUMENTOPs.Where(docl => docl.ACCION == "D").ToList();

                                //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------>
                                List <CLAVES_CONTA> cls = new List <CLAVES_CONTA>();

                                //MGC 30-10-2018 Obtener las claves a partir del tipo de solicitud
                                cls = db.CLAVES_CONTA.Where(clsi => clsi.TSOL == doc.TSOL_ID).ToList();

                                //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------<

                                //MGC 30-10-2018 Valores en el renglón H
                                for (int i = 0; i < lh.Count; i++)
                                {
                                    string post  = "";
                                    string postk = "";

                                    //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------>
                                    CLAVES_CONTA clsi = cls.Where(c => c.DH == lh[i].ACCION).FirstOrDefault();

                                    if (clsi != null)
                                    {
                                        post  = clsi.BSCHLL;
                                        postk = clsi.BSCHL;
                                    }

                                    //if (lh[i].ACCION == "H")
                                    //{
                                    //    post = "P";
                                    //    if (doc.TSOL_ID == "NCC" | doc.TSOL_ID == "NCS")
                                    //    {
                                    //        postk = "50";
                                    //    }
                                    //    else
                                    //    {
                                    //        postk = "31";
                                    //    }
                                    //}
                                    //else if (lh[i].ACCION == "D")
                                    //{
                                    //    post = "G";
                                    //    if (doc.TSOL_ID == "NCC" | doc.TSOL_ID == "NCS")
                                    //    {
                                    //        postk = "21";
                                    //    }
                                    //    else
                                    //    {
                                    //        postk = "40";
                                    //    }

                                    //}

                                    //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------<

                                    string cuenta     = lh[i].CUENTA + "";
                                    string ccosto     = lh[i].CCOSTO + "";
                                    string imputacion = lh[i].IMPUTACION + "";

                                    sw.WriteLine(
                                        //det[i].POS_TYPE + "|" +
                                        "3" + "|" +
                                        post + "|" +
                                        doc.SOCIEDAD_ID.Trim() + "|" + //det[i].COMP_CODE + "|" + //
                                                                       //det[i].BUS_AREA + "|" +
                                        "|" +
                                        //det[i].POST_KEY + "|" +
                                        postk + "|" +
                                        cuenta.Trim() + "|" + //det[i].ACCOUNT + "|" +
                                        ccosto.Trim() + "|" + //det[i].COST_CENTER + "|" +
                                        imputacion.Trim() + "|" +
                                        lh[i].MONTO + "|" +   //det[i].BALANCE + "|" +
                                        lh[i].TEXTO + "|" +   //det[i].TEXT + "|" +
                                                              //det[i].SALES_ORG + "|" +
                                                              //det[i].DIST_CHANEL + "|" +
                                        "|" +
                                        "|" +
                                        //det[i].DIVISION + "|" +
                                        "|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //det[i].INV_REF + "|" +
                                        //det[i].PAY_TERM + "|" +
                                        //det[i].JURIS_CODE + "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        //"|" +
                                        //det[i].CUSTOMER + "|" +
                                        //det[i].PRODUCT + "|" +
                                        "|" +
                                        "|" +
                                        lh[i].MWSKZ + "|" + //det[i].TAX_CODE + "|" +
                                                            //det[i].PLANT + "|" +
                                                            //det[i].REF_KEY1 + "|" +
                                                            //det[i].REF_KEY3 + "|" +
                                                            //det[i].ASSIGNMENT + "|" +
                                                            //det[i].QTY + "|" +
                                                            //det[i].BASE_UNIT + "|" +
                                                            //det[i].AMOUNT_LC + "|" +
                                                            //det[i].RETENCION_ID + "|"
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|"
                                        );
                                }

                                //MGC 30-10-2018 Valores en el renglón D
                                for (int i = 0; i < ld.Count; i++)
                                {
                                    string post  = "";
                                    string postk = "";

                                    //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------>
                                    CLAVES_CONTA clsi = cls.Where(c => c.DH == ld[i].ACCION).FirstOrDefault();

                                    if (clsi != null)
                                    {
                                        post  = clsi.BSCHLL;
                                        postk = clsi.BSCHL;
                                    }

                                    //if (ld[i].ACCION == "H")
                                    //{
                                    //    post = "P";
                                    //    if (doc.TSOL_ID == "NCC" | doc.TSOL_ID == "NCS")
                                    //    {
                                    //        postk = "50";
                                    //    }
                                    //    else
                                    //    {
                                    //        postk = "31";
                                    //    }
                                    //}
                                    //else if (ld[i].ACCION == "D")
                                    //{
                                    //    post = "G";
                                    //    if (doc.TSOL_ID == "NCC" | doc.TSOL_ID == "NCS")
                                    //    {
                                    //        postk = "21";
                                    //    }
                                    //    else
                                    //    {
                                    //        postk = "40";
                                    //    }

                                    //}

                                    //MGC 30-10-2018 Obtener las claves de contabilización ------------------------------------------------<

                                    string cuenta     = ld[i].CUENTA + "";
                                    string ccosto     = ld[i].CCOSTO + "";
                                    string imputacion = ld[i].IMPUTACION + "";

                                    sw.WriteLine(
                                        //det[i].POS_TYPE + "|" +
                                        "3" + "|" +
                                        post + "|" +
                                        doc.SOCIEDAD_ID.Trim() + "|" + //det[i].COMP_CODE + "|" + //
                                                                       //det[i].BUS_AREA + "|" +
                                        "|" +
                                        //det[i].POST_KEY + "|" +
                                        postk + "|" +
                                        cuenta.Trim() + "|" + //det[i].ACCOUNT + "|" +
                                        ccosto.Trim() + "|" + //det[i].COST_CENTER + "|" +
                                        imputacion.Trim() + "|" +
                                        ld[i].MONTO + "|" +   //det[i].BALANCE + "|" +
                                        ld[i].TEXTO + "|" +   //det[i].TEXT + "|" +
                                                              //det[i].SALES_ORG + "|" +
                                                              //det[i].DIST_CHANEL + "|" +
                                        "|" +
                                        "|" +
                                        //det[i].DIVISION + "|" +
                                        "|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //"|" +
                                        //det[i].INV_REF + "|" +
                                        //det[i].PAY_TERM + "|" +
                                        //det[i].JURIS_CODE + "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        //"|" +
                                        //det[i].CUSTOMER + "|" +
                                        //det[i].PRODUCT + "|" +
                                        "|" +
                                        "|" +
                                        ld[i].MWSKZ + "|" + //det[i].TAX_CODE + "|" +
                                                            //det[i].PLANT + "|" +
                                                            //det[i].REF_KEY1 + "|" +
                                                            //det[i].REF_KEY3 + "|" +
                                                            //det[i].ASSIGNMENT + "|" +
                                                            //det[i].QTY + "|" +
                                                            //det[i].BASE_UNIT + "|" +
                                                            //det[i].AMOUNT_LC + "|" +
                                                            //det[i].RETENCION_ID + "|"
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|" +
                                        "|"
                                        );
                                }

                                //MGC 11-10-2018 Acciones para el encabezado RETENCIONES -->
                                for (int i = 0; i < doc.DOCUMENTORs.Count; i++)
                                {
                                    sw.WriteLine(
                                        "4" + "|" +
                                        "W" + "|" +
                                        doc.DOCUMENTORs.ElementAt(i).WITHT + "|" +
                                        doc.DOCUMENTORs.ElementAt(i).WT_WITHCD + "|" +
                                        doc.DOCUMENTORs.ElementAt(i).BIMPONIBLE + "|" +
                                        doc.DOCUMENTORs.ElementAt(i).IMPORTE_RET //+ "|" //MGC 17-10-2018.2 Adaptación a archivo

                                        );
                                }
                                //MGC 11-10-2018 Acciones para el encabezado RETENCIONES <--

                                //sw.Close();
                                sw.Close();

                                //using (Stream stOut = reqFTP.GetRequestStream())
                                //{
                                //    stOut.Write(stIn.GetBuffer(), 0, (int)stIn.Length);
                                //}
                            }
                        }
                        catch (Exception e)
                        {
                            errorMessage = "Error al generar el archivo txt preliminar " + e.Message;
                        }
                    }
                }
                else
                {
                    errorMessage = "Error con el directorio para crear archivo";
                }



                ////MGC 11-10-2018 Acciones para el encabezado -->

                //string variable = "";
                //string accionhead = "";
                ////Preliminar
                //if(accion == "P")
                //{
                //    variable = "ACCION_CREAR";
                //}else if(accion == "R")
                //{
                //    variable = "ACCION_BC";
                //}
                //else if (accion == "A")
                //{
                //    variable = "ACCION_CONTABILIZAR";
                //}

                ////Obtener el nombre de la acción desde la bd en APPSETTING
                //try
                //{
                //    accionhead = db.APPSETTINGs.Where(aps => aps.NOMBRE.Equals(variable) && aps.ACTIVO == true).FirstOrDefault().VALUE.ToString();

                //}catch(Exception e)
                //{

                //}

                ////MGC 11-10-2018 Acciones para el encabezado <--


                //doc.FECHAC = Fecha("D", Convert.ToDateTime(doc.FECHAC));

                //List<DetalleContab> det = new List<DetalleContab>();

                //var dir = new Files().createDir(dirFile);//RSG 01.08.2018

                ////Evaluar que se creo el directorio
                //if (dir.Equals(""))
                //{
                //    using (StreamWriter sw = new StreamWriter(docname))
                //    {
                //        string belnr = "";
                //        string bjahr = "";
                //        string bukrs = "";

                //        if (accion == "R")
                //        {
                //            belnr = doc.NUM_PRE + "";
                //            bjahr = doc.EJERCICIO_PRE + "";
                //            bukrs = doc.SOCIEDAD_PRE + "";
                //        }

                //        //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado -->
                //        sw.WriteLine(
                //            "1"+ "|" +
                //            ts.TIPO_DOCFILE.Trim() + "|" +
                //            doc.NUM_DOC+"|" +
                //            accionhead.Trim() + "|"+
                //            belnr + "|"+
                //            bjahr + "|"+
                //            bukrs + "|"
                //            );
                //        sw.WriteLine("");

                //        //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado <--

                //        //Formato a fecha mes, día, año
                //        sw.WriteLine(
                //            "2" + "|" +
                //            doc.DOCUMENTO_SAP + "|" +
                //            doc.SOCIEDAD_ID.Trim() + "|" +
                //            String.Format("{0:MM.dd.yyyy}", doc.FECHAC).Replace(".", "") + "|"+
                //            doc.MONEDA_ID.Trim() + "|" +
                //            //+ "|" + //MGC 11-10-2018 Acciones para el encabezado
                //            doc.REFERENCIA + "|"+
                //            doc.CONCEPTO + "|" + //MGC 11-10-2018 Acciones para el encabezado
                //            "X" + "|"+
                //            doc.TIPO_CAMBIO + "|" //MGC 11-10-2018 Acciones para el encabezado
                //            + ""
                //            );
                //        sw.WriteLine("");
                //        //for (int i = 0; i < det.Count; i++)
                //        for (int i = 0; i < doc.DOCUMENTOPs.Count; i++)
                //        {
                //            string post = "";
                //            string postk = "";

                //            if (doc.DOCUMENTOPs.ElementAt(i).ACCION == "H")
                //            {
                //                post = "P";
                //                postk = "31";
                //            }
                //            else if (doc.DOCUMENTOPs.ElementAt(i).ACCION == "D")
                //            {
                //                post = "G";
                //                postk = "40";

                //            }
                //            sw.WriteLine(
                //                //det[i].POS_TYPE + "|" +
                //                "3" + "|" +
                //                post + "|" +
                //                doc.SOCIEDAD_ID.Trim() + "|" + //det[i].COMP_CODE + "|" + //
                //                                               //det[i].BUS_AREA + "|" +
                //                "|" +
                //                //det[i].POST_KEY + "|" +
                //                postk + "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).CUENTA + "|" +//det[i].ACCOUNT + "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).CCOSTO + "|" +//det[i].COST_CENTER + "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).IMPUTACION + "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).MONTO + "|" +//det[i].BALANCE + "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).TEXTO + "|" + //det[i].TEXT + "|" +
                //                                            //det[i].SALES_ORG + "|" +
                //                                            //det[i].DIST_CHANEL + "|" +
                //                "|" +
                //                "|" +
                //                //det[i].DIVISION + "|" +
                //                "|" +
                //                //"|" +
                //                //"|" +
                //                //"|" +
                //                //"|" +
                //                //"|" +
                //                //det[i].INV_REF + "|" +
                //                //det[i].PAY_TERM + "|" +
                //                //det[i].JURIS_CODE + "|" +
                //                "|" +
                //                "|" +
                //                "|" +
                //                //"|" +
                //                //det[i].CUSTOMER + "|" +
                //                //det[i].PRODUCT + "|" +
                //                "|" +
                //                "|" +
                //                doc.DOCUMENTOPs.ElementAt(i).MWSKZ + "|" +//det[i].TAX_CODE + "|" +
                //                                                          //det[i].PLANT + "|" +
                //                                                          //det[i].REF_KEY1 + "|" +
                //                                                          //det[i].REF_KEY3 + "|" +
                //                                                          //det[i].ASSIGNMENT + "|" +
                //                                                          //det[i].QTY + "|" +
                //                                                          //det[i].BASE_UNIT + "|" +
                //                                                          //det[i].AMOUNT_LC + "|" +
                //                                                          //det[i].RETENCION_ID + "|"
                //                "|" +
                //                "|" +
                //                "|" +
                //                "|" +
                //                "|" +
                //                "|" +
                //                "|" +
                //                "|"
                //                );
                //        }
                //        //MGC 11-10-2018 Acciones para el encabezado RETENCIONES -->
                //        for (int i = 0; i < doc.DOCUMENTORs.Count; i++)
                //        {
                //            sw.WriteLine(
                //            "4" + "|" +
                //            "W" + "|" +
                //            doc.DOCUMENTORs.ElementAt(i).WITHT + "|" +
                //            doc.DOCUMENTORs.ElementAt(i).WT_WITHCD + "|" +
                //            doc.DOCUMENTORs.ElementAt(i).BIMPONIBLE + "|" +
                //            doc.DOCUMENTORs.ElementAt(i).IMPORTE_RET + "|" +
                //            ""
                //            );
                //        }
                //        //MGC 11-10-2018 Acciones para el encabezado RETENCIONES <--

                //        sw.Close();
                //    }

                //}
                //else
                //{
                //    errorMessage = dir;
                //}

                //MGC prueba FTP---------------------------------------------------------------------------------------------------------------------------------------->

                //Obtener la configuración de la url desde app setting
                //string ftpServerIP = "";
                //try
                //{
                //    ftpServerIP = db.APPSETTINGs.Where(aps => aps.NOMBRE.Equals("URL_FTP_PRELIMINAR") && aps.ACTIVO == true).FirstOrDefault().VALUE.ToString();
                //    url_prel += @"POSTING";
                //    dirFile = url_prel;
                //}
                //catch (Exception e)
                //{

                //}
                //string targetFileName = "/SAP/POSTING/INBOUND_PREL" + ts.ID.Substring(0, 2) + docum.ToString().PadLeft(10, '0') + "-1.txt";

                ////string ftpServerIP = "192.168.32.207:21";
                ////string targetFileName = "/SAP/POSTING/prueba.txt";
                //string username = "******";
                //string password = "******";

                //Uri uri = new Uri(String.Format("ftp://{0}/{1}", ftpServerIP, targetFileName));
                //FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                //reqFTP.Credentials = new NetworkCredential(username, password);
                //reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                //reqFTP.KeepAlive = false;
                //reqFTP.UsePassive = false;


                //MemoryStream stIn = new MemoryStream();
                //using (StreamWriter sw = new StreamWriter(stIn))
                //{
                //    string belnr = "";
                //    string bjahr = "";
                //    string bukrs = "";

                //    if (accion == "R")
                //    {
                //        belnr = doc.NUM_PRE + "";
                //        bjahr = doc.EJERCICIO_PRE + "";
                //        bukrs = doc.SOCIEDAD_PRE + "";
                //    }

                //    //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado -->
                //    sw.WriteLine(
                //        "1" + "|" +
                //        ts.TIPO_DOCFILE.Trim() + "|" +
                //        doc.NUM_DOC + "|" +
                //        accionhead.Trim() + "|" +
                //        belnr + "|" +
                //        bjahr + "|" +
                //        bukrs //MGC 19-10-2018 Cambio en archivo
                //        );
                //    //sw.WriteLine(""); //MGC 17-10-2018.2 Adaptación a archivo

                //    //DETDOC	|TIPODOC|ACCION|BELNR|GJAHR|BUKRS DETDOC EJE	FACSINOC|CONTABILIZAR|10000000|2018|1010| //MGC 11-10-2018 Acciones para el encabezado <--

                //    //Formato a fecha mes, día, año
                //    sw.WriteLine(
                //        "2" + "|" +
                //        doc.DOCUMENTO_SAP + "|" +
                //        doc.SOCIEDAD_ID.Trim() + "|" +
                //        String.Format("{0:dd.MM.yyyy}", doc.FECHAC).Replace(".", "") + "|" + //Formato MGC
                //        doc.MONEDA_ID.Trim() + "|" +
                //        //+ "|" + //MGC 11-10-2018 Acciones para el encabezado
                //        doc.REFERENCIA.Trim() + "|" +
                //        doc.CONCEPTO + "|" + //MGC 11-10-2018 Acciones para el encabezado
                //        "" + "|" +
                //        "" + "|" +
                //        doc.TIPO_CAMBIO  //MGC 11-10-2018 Acciones para el encabezado
                //        );
                //    //sw.WriteLine("");//MGC 17-10-2018.2 Adaptación a archivo
                //    //for (int i = 0; i < det.Count; i++)

                //    //Obtener los rows H
                //    List<DOCUMENTOP> lh = doc.DOCUMENTOPs.Where(docl => docl.ACCION == "H").ToList();
                //    List<DOCUMENTOP> ld = doc.DOCUMENTOPs.Where(docl => docl.ACCION == "D").ToList();

                //    for (int i = 0; i < lh.Count; i++)
                //    {
                //        string post = "";
                //        string postk = "";

                //        if (lh[i].ACCION == "H")
                //        {
                //            post = "P";
                //            postk = "31";
                //        }
                //        else if (lh[i].ACCION == "D")
                //        {
                //            post = "G";
                //            postk = "40";

                //        }

                //        string cuenta = lh[i].CUENTA+"";
                //        string ccosto = lh[i].CCOSTO + "";
                //        string imputacion = lh[i].IMPUTACION + "";

                //        sw.WriteLine(
                //            //det[i].POS_TYPE + "|" +
                //            "3" + "|" +
                //            post + "|" +
                //            doc.SOCIEDAD_ID.Trim() + "|" + //det[i].COMP_CODE + "|" + //
                //                                           //det[i].BUS_AREA + "|" +
                //            "|" +
                //            //det[i].POST_KEY + "|" +
                //            postk + "|" +
                //            cuenta.Trim() + "|" +//det[i].ACCOUNT + "|" +
                //            ccosto.Trim() + "|" +//det[i].COST_CENTER + "|" +
                //            imputacion.Trim() + "|" +
                //            lh[i].MONTO + "|" +//det[i].BALANCE + "|" +
                //            lh[i].TEXTO + "|" + //det[i].TEXT + "|" +
                //                                                       //det[i].SALES_ORG + "|" +
                //                                                       //det[i].DIST_CHANEL + "|" +
                //            "|" +
                //            "|" +
                //            //det[i].DIVISION + "|" +
                //            "|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //det[i].INV_REF + "|" +
                //            //det[i].PAY_TERM + "|" +
                //            //det[i].JURIS_CODE + "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            //"|" +
                //            //det[i].CUSTOMER + "|" +
                //            //det[i].PRODUCT + "|" +
                //            "|" +
                //            "|" +
                //            lh[i].MWSKZ + "|" +//det[i].TAX_CODE + "|" +
                //                                                      //det[i].PLANT + "|" +
                //                                                      //det[i].REF_KEY1 + "|" +
                //                                                      //det[i].REF_KEY3 + "|" +
                //                                                      //det[i].ASSIGNMENT + "|" +
                //                                                      //det[i].QTY + "|" +
                //                                                      //det[i].BASE_UNIT + "|" +
                //                                                      //det[i].AMOUNT_LC + "|" +
                //                                                      //det[i].RETENCION_ID + "|"
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|"
                //            );
                //    }

                //    for (int i = 0; i < ld.Count; i++)
                //    {
                //        string post = "";
                //        string postk = "";

                //        if (ld[i].ACCION == "H")
                //        {
                //            post = "P";
                //            postk = "31";
                //        }
                //        else if (ld[i].ACCION == "D")
                //        {
                //            post = "G";
                //            postk = "40";

                //        }

                //        string cuenta = ld[i].CUENTA + "";
                //        string ccosto = ld[i].CCOSTO + "";
                //        string imputacion = ld[i].IMPUTACION + "";

                //        sw.WriteLine(
                //            //det[i].POS_TYPE + "|" +
                //            "3" + "|" +
                //            post + "|" +
                //            doc.SOCIEDAD_ID.Trim() + "|" + //det[i].COMP_CODE + "|" + //
                //                                           //det[i].BUS_AREA + "|" +
                //            "|" +
                //            //det[i].POST_KEY + "|" +
                //            postk + "|" +
                //            cuenta.Trim() + "|" +//det[i].ACCOUNT + "|" +
                //            ccosto.Trim() + "|" +//det[i].COST_CENTER + "|" +
                //            imputacion.Trim() + "|" +
                //            ld[i].MONTO + "|" +//det[i].BALANCE + "|" +
                //            ld[i].TEXTO + "|" + //det[i].TEXT + "|" +
                //                                //det[i].SALES_ORG + "|" +
                //                                //det[i].DIST_CHANEL + "|" +
                //            "|" +
                //            "|" +
                //            //det[i].DIVISION + "|" +
                //            "|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //"|" +
                //            //det[i].INV_REF + "|" +
                //            //det[i].PAY_TERM + "|" +
                //            //det[i].JURIS_CODE + "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            //"|" +
                //            //det[i].CUSTOMER + "|" +
                //            //det[i].PRODUCT + "|" +
                //            "|" +
                //            "|" +
                //            ld[i].MWSKZ + "|" +//det[i].TAX_CODE + "|" +
                //                               //det[i].PLANT + "|" +
                //                               //det[i].REF_KEY1 + "|" +
                //                               //det[i].REF_KEY3 + "|" +
                //                               //det[i].ASSIGNMENT + "|" +
                //                               //det[i].QTY + "|" +
                //                               //det[i].BASE_UNIT + "|" +
                //                               //det[i].AMOUNT_LC + "|" +
                //                               //det[i].RETENCION_ID + "|"
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|" +
                //            "|"
                //            );
                //    }

                //    //MGC 11-10-2018 Acciones para el encabezado RETENCIONES -->
                //    for (int i = 0; i < doc.DOCUMENTORs.Count; i++)
                //    {
                //        sw.WriteLine(
                //        "4" + "|" +
                //        "W" + "|" +
                //        doc.DOCUMENTORs.ElementAt(i).WITHT + "|" +
                //        doc.DOCUMENTORs.ElementAt(i).WT_WITHCD + "|" +
                //        doc.DOCUMENTORs.ElementAt(i).BIMPONIBLE + "|" +
                //        doc.DOCUMENTORs.ElementAt(i).IMPORTE_RET //+ "|" //MGC 17-10-2018.2 Adaptación a archivo

                //        );
                //    }
                //    //MGC 11-10-2018 Acciones para el encabezado RETENCIONES <--

                //    //sw.Close();
                //    sw.Flush();

                //    using (Stream stOut = reqFTP.GetRequestStream())
                //    {
                //        stOut.Write(stIn.GetBuffer(), 0, (int)stIn.Length);
                //    }



                //}

                //FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                //response.Close();
                //MGC prueba FTP----------------------------------------------------------------------------------------------------------------------------------------<

                //if (tab.RELACION != 0 && tab.RELACION != null)
                //{
                //    return generarArchivo(docum, Convert.ToInt32(tab.RELACION));
                //}
                //else
                //{
                //return "";
                //}
            }
            catch (Exception e)
            {
                //return "Error al generar el documento contable " + e.Message;
                errorMessage = "Error al generar el archivo txt preliminar " + e.Message;
            }

            return(errorMessage);
        }
        /// <summary>
        /// Creates PDF document from given content. See https://github.com/CommunityHiQ/Frends.Community.PdfFromTemplate
        /// </summary>
        /// <param name="outputFile"></param>
        /// <param name="content"></param>
        /// <param name="options"></param>
        /// <returns>Object { bool Success, string FileName, byte[] ResultAsByteArray }</returns>
        public static Output CreatePdf([PropertyTab] FileProperties outputFile,
                                       [PropertyTab] DocumentContent content,
                                       [PropertyTab] Options options)
        {
            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                DocumentDefinition docContent = JsonConvert.DeserializeObject <DocumentDefinition>(content.ContentJson);

                var document = new Document();
                if (!string.IsNullOrWhiteSpace(docContent.Title))
                {
                    document.Info.Title = docContent.Title;
                }
                if (!string.IsNullOrWhiteSpace(docContent.Author))
                {
                    document.Info.Author = docContent.Author;
                }

                PageSetup.GetPageSize(docContent.PageSize.ConvertEnum <PageFormat>(), out Unit width, out Unit height);

                var section = document.AddSection();
                SetupPage(section.PageSetup, width, height, docContent);

                // index for stylename
                var elementNumber = 0;
                // add page elements

                foreach (var pageElement in docContent.DocumentElements)
                {
                    var styleName = $"style_{elementNumber}";
                    var style     = document.Styles.AddStyle(styleName, "Normal");
                    switch (pageElement.ElementType)
                    {
                    case ElementTypeEnum.Paragraph:
                        SetFont(style, ((ParagraphDefinition)pageElement).StyleSettings);
                        SetParagraphStyle(style, ((ParagraphDefinition)pageElement).StyleSettings, false);
                        AddTextContent(section, ((ParagraphDefinition)pageElement).Text, style);
                        break;

                    case ElementTypeEnum.Image:
                        AddImage(section, (ImageDefinition)pageElement, width);
                        break;

                    case ElementTypeEnum.Table:
                        SetFont(style, ((TableDefinition)pageElement).StyleSettings);
                        SetParagraphStyle(style, ((TableDefinition)pageElement).StyleSettings, true);
                        AddTable(section, (TableDefinition)pageElement, width, style);
                        break;

                    case ElementTypeEnum.PageBreak:
                        section = document.AddSection();
                        SetupPage(section.PageSetup, width, height, docContent);
                        break;

                    default:
                        break;
                    }

                    ++elementNumber;
                }

                string fileName      = Path.Combine(outputFile.Directory, outputFile.FileName);
                int    fileNameIndex = 1;
                while (File.Exists(fileName) && outputFile.FileExistsAction != FileExistsActionEnum.Overwrite)
                {
                    switch (outputFile.FileExistsAction)
                    {
                    case FileExistsActionEnum.Error:
                        throw new Exception($"File {fileName} already exists.");

                    case FileExistsActionEnum.Rename:
                        fileName = Path.Combine(outputFile.Directory, $"{Path.GetFileNameWithoutExtension(outputFile.FileName)}_({fileNameIndex}){Path.GetExtension(outputFile.FileName)}");
                        break;
                    }
                    fileNameIndex++;
                }
                // save document

                var pdfRenderer = new PdfDocumentRenderer(outputFile.Unicode)
                {
                    Document = document
                };


                pdfRenderer.RenderDocument();

                if (outputFile.SaveToDisk)
                {
                    if (!options.UseGivenCredentials)
                    {
                        pdfRenderer.PdfDocument.Save(fileName);
                    }
                    else
                    {
                        var domainAndUserName = GetDomainAndUserName(options.UserName);
                        using (Impersonation.LogonUser(domainAndUserName[0], domainAndUserName[1], options.Password, LogonType.NewCredentials))
                        {
                            pdfRenderer.PdfDocument.Save(fileName);
                        }
                    }
                }

                byte[] resultAsBytes = null;

                if (options.GetResultAsByteArray)
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        pdfRenderer.PdfDocument.Save(stream, false);
                        resultAsBytes = stream.ToArray();
                    }
                }

                return(new Output {
                    Success = true, FileName = fileName, ResultAsByteArray = resultAsBytes
                });
            }
            catch (Exception ex)
            {
                if (options.ThrowErrorOnFailure)
                {
                    throw;
                }

                return(new Output {
                    Success = false, ErrorMessage = ex.Message
                });
            }
        }
        public IHttpActionResult PostPrintLabel(LabelToPrintModel dat)
        {
            LabelPrintModels db = new LabelPrintModels();
            DateTime         dt;
            bool             noDate = dat.NoDate;

            if (!noDate)
            {
                dt = (DateTime)dat.SellOrUseBy;
            }
            else
            {
                dt = DateTime.Today;
            }
            DateTime packDate        = dt;
            string   shift           = dat.Shift;
            decimal  dWeight         = 0m;
            int      fullLbs         = 0;
            decimal  remaindOzs      = 0;
            decimal  kgConv          = 0m;
            string   wtStr           = "";
            string   fullItem        = dat.Id.ToString().PadLeft(5, '0');
            bool     incrementJulian = dat.JulianPlusOne;
            string   fakeJulian      = incrementJulian ? ((DateTime.Today.DayOfYear) + 1).ToString().PadLeft(3, '0') : DateTime.Today.DayOfYear.ToString().PadLeft(3, '0');
            bool     isWalMart       = dat.IsWm;
            int      useByDays       = dat.UseByDays;
            string   bCodeDateVal    = "";

            if (isWalMart && dat.UseByDays > 0)
            {
                dt = dt.AddDays(useByDays);
            }
            bCodeDateVal = dt.ToString("yyMMdd");

            if (isWalMart)
            {
                using (JDE_PRODUCTIONEntities dbJDcn = new JDE_PRODUCTIONEntities())
                {
                    ItemsMasterModel im = dbJDcn.F4101
                                          .Where(p => p.IMLITM == fullItem)
                                          .Select(p => new ItemsMasterModel
                    {
                        ItemFull   = p.IMLITM.Trim(),
                        ItemDesc   = p.IMDSC1.Trim(),
                        BrandAbbrv = p.IMSRP4.Trim(),
                        BrandFull  = (from c in dbJDcn.F0005
                                      where c.DRSY == "41" &&
                                      c.DRRT.ToUpper() == "S4" &&
                                      c.DRKY.Trim() == p.IMSRP4.Trim()
                                      select c.DRDL01.Trim()).FirstOrDefault(),
                        GTIN        = p.IMAITM.Trim(),
                        WalmartCode = (from y in dbJDcn.F4104
                                       where y.IVLITM.Trim() == p.IMLITM && y.IVXRT.ToUpper() == "UC"
                                       select y.IVCITM.Trim()).FirstOrDefault() ?? ""
                    }).SingleOrDefault();

                    if (im != null)
                    {
                        string secondBcString = shift + im.ItemFull + fakeJulian + DateTime.Now.Year.ToString().Substring(2, 2) + dat.CooId;

                        //See if we need to use alternate label
                        AltLabelItem useAltTemplate = db.AltLabelItems.FirstOrDefault(p => p.ItemNum == fullItem);

                        string voicePickCode = VoiceCode.Compute(im.GTIN, secondBcString, null);
                        string lilDigits     = voicePickCode.Substring(0, 2);
                        string bigDigits     = voicePickCode.Substring(2, 2);
                        if (dat.UseByDays > 0)
                        {
                            packDate = packDate.AddDays(dat.UseByDays);
                        }
                        string PrintDate      = packDate.ToString("MMM dd"); //useAltTemplate != null && useAltTemplate.ShowJulianNoSellby == true ? fakeJulian : dt.ToString("MMM dd");
                        string PrintDateFixed = dt.ToString("MMM dd");
                        string btwFile        = dat.UseByDays > 0 ?
                                                (im.WalmartCode == ""?
                                                 "Base4by2NEWWalMartdesignWleadTimeNOUPC"
                                    : "Base4by2NEWWalMartdesignWleadTime"
                                                )
                                :im.WalmartCode == "" ?
                                                "Base4by2NEWWalMartdesignNOUPC"
                                : "Base4by2NEWWalMartdesign"
                        ;
                        string cooo = db.COO_List.FirstOrDefault(p => p.idx == dat.CooId).LongName;
                        using (Impersonation.LogonUser("MANN", "bartender", "vodkagimlet", LogonType.Interactive))
                        {
                            StringBuilder sb = new StringBuilder();
                            //Fork if using alternate template
                            sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{0}.btw"" /D=""%Trigger File Name%"" /PRN=""{1}"" /R=3 /P /C={2}", btwFile, dat.PrinterName, dat.Qty.ToString());
                            sb.AppendLine();
                            sb.AppendLine("%END%");
                            sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\",\"{14}\"",
                                            im.ItemFull, im.GTIN.Substring(0, 13), cooo, PrintDate, im.ItemDesc, dat.SrcAddress, secondBcString, im.BrandFull,
                                            dat.Shift, lilDigits, bigDigits, "", im.WalmartCode, dat.CrewNum, bCodeDateVal);

                            sb.AppendLine();
                            try
                            {
                                File.WriteAllText(@"\\mann-forms\Data\FileFromMannLabels.csv", sb.ToString());
                                return(Ok());
                            }
                            catch (Exception ex)
                            {
                                return(BadRequest(ex.Message));
                            }
                            finally
                            {
                                db.Dispose();
                            }
                        }
                    }
                    else
                    {
                        return(BadRequest("Item Not found"));
                    }
                }
            }
            else
            {
                using (JDE_PRODUCTIONEntities dbJDcn = new JDE_PRODUCTIONEntities())
                {
                    ItemsMasterModel im = dbJDcn.F4101
                                          .Where(p => p.IMLITM == fullItem)
                                          .Select(p => new ItemsMasterModel
                    {
                        ItemFull   = p.IMLITM.Trim(),
                        ItemDesc   = p.IMDSC1.Trim(),
                        BrandAbbrv = p.IMSRP4.Trim(),
                        BrandFull  = (from c in dbJDcn.F0005
                                      where c.DRSY == "41" &&
                                      c.DRRT.ToUpper() == "S4" &&
                                      c.DRKY.Trim() == p.IMSRP4.Trim()
                                      select c.DRDL01.Trim()).FirstOrDefault(),
                        GTIN        = p.IMAITM.Trim(),
                        WalmartCode = dat.WalmartCode
                    }).SingleOrDefault();
                    double?waight = dbJDcn.F574101
                                    .Where(p => p.QTLITM == fullItem)
                                    .Select(p => p.QTZ57BINO).FirstOrDefault();

                    if (waight.HasValue)
                    {
                        //TODO test only
                        //waight += 587;
                        dWeight    = Convert.ToDecimal(((double)(waight) / 100));
                        fullLbs    = Convert.ToInt32(Math.Floor(dWeight / 16));
                        remaindOzs = (dWeight % 16);
                        kgConv     = Math.Round(dWeight * 0.0283495231m, 2);
                        if (fullLbs > 0)
                        {
                            if (remaindOzs > 0)
                            {
                                wtStr = $"NET WT. {dWeight} OZ ({fullLbs} LB {remaindOzs} OZ) {kgConv} kg";
                            }
                            else
                            {
                                wtStr = $"NET WT. {dWeight} OZ ({fullLbs} LB) {kgConv} kg";
                            }
                        }
                        else
                        {
                            wtStr = $"NET WT. {dWeight} OZ ({remaindOzs} OZ) {kgConv} kg";
                        }
                    }

                    if (im != null)
                    {
                        string secondBcString = shift + im.ItemFull + fakeJulian + DateTime.Now.Year.ToString().Substring(2, 2) + dat.CooId;

                        //See if we need to use alternate label
                        AltLabelItem useAltTemplate = db.AltLabelItems.FirstOrDefault(p => p.ItemNum == fullItem);

                        string voicePickCode       = VoiceCode.Compute(im.GTIN, secondBcString, null);
                        string lilDigits           = voicePickCode.Substring(0, 2);
                        string bigDigits           = voicePickCode.Substring(2, 2);
                        string PrintDate           = useAltTemplate != null && useAltTemplate.ShowJulianNoSellby == true ? fakeJulian : dt.ToString("MMM dd");
                        string PrintDateFixed      = dt.ToString("MM/dd/yy");
                        string PrintDateFixedShort = dt.ToString("MMMdd");
                        bool   item    = im.WalmartCode != "";
                        string btwFile = item ? "Base4by2WalMartdesign" : "Base4by2design";
                        string cooo    = db.COO_List.FirstOrDefault(p => p.idx == dat.CooId).LongName;
                        using (Impersonation.LogonUser("MANN", "bartender", "vodkagimlet", LogonType.Interactive))
                        {
                            StringBuilder sb = new StringBuilder();
                            if (noDate)
                            {
                                sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\Base4by2designNoDate.btw"" /D=""%Trigger File Name%"" /PRN=""{0}"" /R=3 /P /C={1}", dat.PrinterName, dat.Qty.ToString());
                                sb.AppendLine();
                                sb.AppendLine("%END%");
                                sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"",
                                                im.ItemFull, im.GTIN.Substring(0, 13), cooo, "", im.ItemDesc, dat.SrcAddress, secondBcString, im.BrandFull,
                                                dat.Shift, lilDigits, bigDigits, "", im.WalmartCode, dat.CrewNum);
                            }
                            else
                            {
                                if (useAltTemplate == null)
                                {
                                    sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{0}.btw"" /D=""%Trigger File Name%"" /PRN=""{1}"" /R=3 /P /C={2}", btwFile, dat.PrinterName, dat.Qty.ToString());
                                    sb.AppendLine();
                                    sb.AppendLine("%END%");
                                    sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"",
                                                    im.ItemFull, im.GTIN.Substring(0, 13), cooo, PrintDate, im.ItemDesc, dat.SrcAddress, secondBcString, im.BrandFull,
                                                    dat.Shift, lilDigits, bigDigits, dat.UsebyLang, im.WalmartCode, dat.CrewNum);
                                }
                                else
                                {
                                    if (useAltTemplate.AlterLabel == "Base4by2designHidelocation")
                                    {
                                        sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{0}.btw"" /D=""%Trigger File Name%"" /PRN=""{1}"" /R=3 /P /C={2}", btwFile, dat.PrinterName, dat.Qty.ToString());
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"",
                                                        im.ItemFull, im.GTIN.Substring(0, 13), cooo, PrintDate, im.ItemDesc, "", secondBcString, im.BrandFull,
                                                        dat.Shift, lilDigits, bigDigits, dat.UsebyLang, im.WalmartCode, dat.CrewNum);
                                    }
                                    else if (useAltTemplate.AlterLabel == "CVF_Opt_Format")
                                    {
                                        sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{0}.btw"" /D=""%Trigger File Name%"" /PRN=""{1}"" /R=3 /P /C={2}", useAltTemplate.AlterLabel, dat.PrinterName, dat.Qty.ToString());
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\"",
                                                        im.ItemFull, im.GTIN.Substring(0, 13), cooo, PrintDate, im.ItemDesc, useAltTemplate.CustProdId, secondBcString,
                                                        lilDigits, bigDigits, useAltTemplate.ShowJulianNoSellby == true ? "" : dat.UsebyLang, dat.CrewNum);
                                    }
                                    else if (useAltTemplate.AlterLabel == "USFoods_Opt_Format")
                                    {
                                        int firstDigit = im.ItemDesc.IndexOfAny("0123456789".ToCharArray());
                                        if (firstDigit > 5)
                                        {
                                            firstDigit -= 1;
                                        }
                                        string itemDescMinusNumerical = im.ItemDesc.Substring(0, firstDigit);
                                        sb.Append($@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{useAltTemplate.AlterLabel}.btw"" /D=""%Trigger File Name%"" /PRN=""{dat.PrinterName}"" /R=3 /P /C={dat.Qty.ToString()}");
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.Append($@"""{ im.ItemFull}"",""{ im.GTIN.Substring(0, 13)}"",""{cooo}"",""{PrintDateFixedShort}"",""{itemDescMinusNumerical}"",""{useAltTemplate.CustProdId}"",""{secondBcString}"",""{lilDigits}"",""{bigDigits}"",""{PrintDateFixed}"",""{dat.CrewNum}"",""{wtStr}""");
                                    }
                                    else if (useAltTemplate.AlterLabel == "USFoods_Opt_Format_2")
                                    {
                                        int firstDigit = im.ItemDesc.IndexOfAny("0123456789".ToCharArray());
                                        if (firstDigit > 5)
                                        {
                                            firstDigit -= 1;
                                        }
                                        string itemDescMinusNumerical = im.ItemDesc.Substring(0, firstDigit);
                                        sb.Append($@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{useAltTemplate.AlterLabel}.btw"" /D=""%Trigger File Name%"" /PRN=""{dat.PrinterName}"" /R=3 /P /C={dat.Qty.ToString()}");
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.Append($@"""{ im.ItemFull}"",""{ im.GTIN.Substring(0, 13)}"",""{cooo}"",""{PrintDateFixedShort}"",""{itemDescMinusNumerical}"",""{useAltTemplate.CustProdId}"",""{secondBcString}"",""{lilDigits}"",""{bigDigits}"",""{dat.UsebyLang}"",""{dat.CrewNum}"",""{wtStr}""");
                                    }
                                    else if (useAltTemplate.AlterLabel == "USFoods_Opt_Format-3")
                                    {
                                        int firstDigit = im.ItemDesc.IndexOfAny("0123456789".ToCharArray());
                                        if (firstDigit > 5)
                                        {
                                            firstDigit -= 1;
                                        }
                                        string itemDescMinusNumerical = im.ItemDesc.Substring(0, firstDigit);
                                        sb.Append($@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{useAltTemplate.AlterLabel}.btw"" /D=""%Trigger File Name%"" /PRN=""{dat.PrinterName}"" /R=3 /P /C={dat.Qty.ToString()}");
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.Append($@"""{ im.ItemFull}"",""{ im.GTIN.Substring(0, 13)}"",""{cooo}"",""{PrintDateFixed}"",""{itemDescMinusNumerical}"",""{useAltTemplate.CustProdId}"",""{secondBcString}"",""{lilDigits}"",""{bigDigits}"",""{dat.UsebyLang}"",""{dat.CrewNum}"",""{wtStr}""");
                                    }
                                    else if (useAltTemplate.AlterLabel == "USFoods_Opt_Format_3BG")
                                    {
                                        int firstDigit = im.ItemDesc.IndexOfAny("0123456789".ToCharArray());
                                        if (firstDigit > 5)
                                        {
                                            firstDigit -= 1;
                                        }
                                        string itemDescMinusNumerical = im.ItemDesc.Substring(0, firstDigit);
                                        sb.Append($@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{useAltTemplate.AlterLabel}.btw"" /D=""%Trigger File Name%"" /PRN=""{dat.PrinterName}"" /R=3 /P /C={dat.Qty.ToString()}");
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.Append($@"""{ im.ItemFull}"",""{ im.GTIN.Substring(0, 13)}"",""{cooo}"",""{PrintDateFixed}"",""{itemDescMinusNumerical}"",""{useAltTemplate.CustProdId}"",""{secondBcString}"",""{lilDigits}"",""{bigDigits}"",""{PrintDateFixed}"",""{dat.CrewNum}"",""{wtStr}""");
                                    }
                                    else if (useAltTemplate.AlterLabel == "Base4by2designXtraNote")
                                    {
                                        int firstDigit = im.ItemDesc.IndexOfAny("0123456789".ToCharArray());
                                        if (firstDigit > 5)
                                        {
                                            firstDigit -= 1;
                                        }
                                        string itemDescMinusNumerical = im.ItemDesc.Substring(0, firstDigit);
                                        sb.Append($@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{useAltTemplate.AlterLabel}.btw"" /D=""%Trigger File Name%"" /PRN=""{dat.PrinterName}"" /R=3 /P /C={dat.Qty.ToString()}");
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"",
                                                        im.ItemFull, im.GTIN.Substring(0, 13), cooo, PrintDate, im.ItemDesc, dat.SrcAddress, secondBcString, im.BrandFull,
                                                        dat.Shift, lilDigits, bigDigits, dat.UsebyLang, im.WalmartCode, dat.CrewNum);
                                    }
                                    else
                                    {
                                        sb.AppendFormat(@"%BTW% /AF=""C:\Bottomline Technologies\BarTender\Forms\{0}.btw"" /D=""%Trigger File Name%"" /PRN=""{1}"" /R=3 /P /C={2}", btwFile, dat.PrinterName, dat.Qty.ToString());
                                        sb.AppendLine();
                                        sb.AppendLine("%END%");
                                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"",
                                                        im.ItemFull, im.GTIN.Substring(0, 13), cooo, fakeJulian, im.ItemDesc, dat.SrcAddress, secondBcString, im.BrandFull,
                                                        dat.Shift, lilDigits, bigDigits, "", im.WalmartCode, dat.CrewNum);
                                    }
                                }
                            }

                            sb.AppendLine();
                            try
                            {
                                File.WriteAllText(@"\\mann-forms\Data\FileFromMannLabels.csv", sb.ToString());
                                return(Ok());
                            }
                            catch (Exception ex)
                            {
                                return(BadRequest(ex.Message));
                            }
                            finally
                            {
                                db.Dispose();
                            }
                        }
                    }
                    else
                    {
                        return(BadRequest("Item Not found"));
                    }
                }
            }
        }