public void SetPackets(Documents.Net.LogPacketCollection packets)
 {
     lock (packets)
     {
         SetPackets(packets.ToArray());
     }
 }
Beispiel #2
0
 public PostSummary(Post post, Documents.Blog blog, int index, int total)
 {
     this.post = post;
     this.blog = blog;
     this.index = index + 1; // not zero indexed from users perspective
     this.total = total;
 }
Beispiel #3
0
 public SelectionManager(Documents.Document doc)
 {
     Document = doc;
     SelectedObjects = new HashSet<MapObject>();
     SelectedFaces = new HashSet<Face>();
     InFaceSelection = false;
 }
        private static decimal CalculateBalance(Documents.Account account, IEnumerable<Documents.Transaction> transactions)
        {
            var accountType = account.Type.IsDebitOrCredit();

            var balance = 0M;
            foreach ( var transaction in transactions )
            {
                var debit = transaction.Debit.Where(x => x.AccountId == account.Id).Sum(x => x.Value);
                var credit = transaction.Credit.Where(x => x.AccountId == account.Id).Sum(x => x.Value);

                switch ( accountType )
                {
                    case EntryType.Debit:
                        balance += debit;
                        balance -= credit;
                        break;

                    case EntryType.Credit:
                        balance += credit;
                        balance -= debit;
                        break;
                }
            }

            return balance;
        }
Beispiel #5
0
        public override void Perform(Documents.Document document)
        {
            if (_firstRun)
            {
                var origin = GetPasteOrigin(document);
                var objects = new List<MapObject>();

                if (_objectsToPaste.Count() == 1)
                {
                    // Only one object - no need to group.
                    _grouping = PasteSpecialGrouping.None;
                }

                Group allGroup = null;
                if (_grouping == PasteSpecialGrouping.All)
                {
                    // Use one group for all copies
                    allGroup = new Group(document.Map.IDGenerator.GetNextObjectID());
                    // Add the group to the tree
                    objects.Add(allGroup);
                }

                // Get a list of all entity names if needed
                var names = new List<string>();
                if (_makeEntitesUnique)
                {
                    names = document.Map.WorldSpawn.Find(x => x is Entity)
                        .Select(x => x.GetEntityData())
                        .Where(x => x != null)
                        .Select(x => x.Properties.FirstOrDefault(y => y.Key == "targetname"))
                        .Where(x => x != null)
                        .Select(x => x.Value)
                        .ToList();
                }

                // Start at i = 1 so the original isn't duped with no offets
                for (var i = 1; i <= _numCopies; i++)
                {
                    var copyOrigin = origin + (_offset * i);
                    var copyRotation = _rotation * i;
                    var copy = CreateCopy(document.Map.IDGenerator, copyOrigin, copyRotation, names, document.Map.GetTransformFlags()).ToList();
                    var grouped = GroupCopy(document.Map.IDGenerator, allGroup, copy);
                    objects.AddRange(grouped);
                }

                // Mark the objects to be created
                Create(objects);

                // We don't need to calculate this again.
                _firstRun = false;
                _objectsToPaste = null;
            }
            base.Perform(document);
        }
Beispiel #6
0
 public Document(Documents docs)
 {
     m_docs = docs;
     try
     {
         New();
     }
     catch
     {
     }
 }
Beispiel #7
0
 public static Document GetStencil(Documents documents)
 {
     //try
     {
         return documents[Constants.StencilName];
     }
     //catch
     //{
     //    // The stencil is not in the collection; open it as a docked stencil.
     //    return documents.OpenEx(Constants.StencilName, (short)VisOpenSaveArgs.visOpenDocked);
     //}
 }
        //Create
        public IHttpActionResult PostLogEntry(Documents.PerformanceLogEntry logEntry)
        {
            MongoCollection<Documents.PerformanceLogEntry> logCollection =
                _panzaDb.GetCollection<Documents.PerformanceLogEntry>("perf_log");

            WriteConcernResult wcr = logCollection.Insert<Documents.PerformanceLogEntry>(logEntry);

            if (wcr.ErrorMessage == null)
            {
                return Ok(logEntry);
            }

            return BadRequest();
        }
        public ObjectPropertiesDialog(Documents.Document document)
        {
            Document = document;
            InitializeComponent();
            Objects = new List<MapObject>();
            _smartEditControls = new Dictionary<VariableType, SmartEditControl>();

            _dumbEditControl = new DumbEditControl {Document = Document};
            _dumbEditControl.ValueChanged += PropertyValueChanged;
            _dumbEditControl.NameChanged += PropertyNameChanged;

            RegisterSmartEditControls();

            FollowSelection = true;
        }
        public void Run(Documents.Net.LogPacketCollection packets, IEnumerable<int> selectedIndices)
        {
            List<LogPacket> selectedPackets = new List<LogPacket>();

            lock (packets)
            {
                foreach (int i in selectedIndices)
                {
                    if (packets.Count > i)
                    {
                        selectedPackets.Add(packets[i]);
                    }
                }
            }

            Run(selectedPackets);
        }
Beispiel #11
0
        private void AddNotaFiscalEntrada(Documents purchaseOrder)
        {
            string code;
            _con.Comany.GetNewObjectCode(out code); // pega o codigo do ultimo objeto criado

            Documents nota = _con.Comany.GetBusinessObject(BoObjectTypes.oPurchaseInvoices);

            nota.CardCode = "F99999";
            nota.DocDueDate = DateTime.Now;

            nota.Lines.BaseType = (int)BoObjectTypes.oPurchaseOrders;
            nota.Lines.BaseEntry = Convert.ToInt32(code);
            nota.Lines.BaseLine = 0;
            nota.Lines.TaxCode = "5403-001";
            nota.Lines.Add();

            nota.Lines.BaseType = (int)BoObjectTypes.oPurchaseOrders;
            nota.Lines.BaseEntry = Convert.ToInt32(code);
            nota.Lines.TaxCode = "5403-001";
            nota.Lines.BaseLine = 1;

            nota.Add();
            MessageBox.Show(_con.Message);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            bool isSandbox = false;

            EnvironmentConfiguration.ChangeEnvironment(isSandbox);

            // Instantiate a new checkout
            BoletoCheckout checkout = new BoletoCheckout();

            // Sets the payment mode
            checkout.PaymentMode = PaymentMode.DEFAULT;

            // Sets the receiver e-mail should will get paid
            checkout.ReceiverEmail = "*****@*****.**";

            // Sets the currency
            checkout.Currency = Currency.Brl;

            // Add items
            checkout.Items.Add(new Item("0001", "Notebook Prata", 2, 2000.00m));
            checkout.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m));

            // Sets a reference code for this checkout, it is useful to identify this payment in future notifications.
            checkout.Reference = "REF1234";

            // Sets shipping information
            checkout.Shipping = new Shipping();
            checkout.Shipping.ShippingType = ShippingType.Sedex;
            checkout.Shipping.Cost         = 0.00m;
            checkout.Shipping.Address      = new Address(
                "BRA",
                "SP",
                "Sao Paulo",
                "Jardim Paulistano",
                "01452002",
                "Av. Brig. Faria Lima",
                "1384",
                "5o andar"
                );

            // Sets your customer information.
            // If you using SANDBOX you must use an email @sandbox.pagseguro.com.br
            checkout.Sender = new Sender(
                "Joao Comprador",
                "*****@*****.**",
                new Phone("11", "56273440")
                );

            checkout.Sender.Hash = "b2806d600653cbb2b195f317ca9a1a58738187a02c05bf7f2280e2076262e73b";

            SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909");

            checkout.Sender.Documents.Add(senderCPF);

            // Sets the notification url
            checkout.NotificationUrl = "http://www.lojamodelo.com.br";

            try
            {
                AccountCredentials credentials = PagSeguroConfiguration.GetAccountCredentials(isSandbox);
                Transaction        result      = TransactionService.CreateCheckout(credentials, checkout);
            }
            catch (PagSeguroServiceException exception)
            {
                foreach (ServiceError element in exception.Errors)
                {
                }
            }
        }
Beispiel #13
0
        private static void ProcessUploadThread(object args)
        {
            string guid = ((ProcessThreadArguments)args).Guid;

            Documents documents = Documents.RecentFromDescription(guid);

            if (documents.Count != 1)
            {
                return; // abort
            }

            Document uploadedDoc = documents[0];

            FinancialAccount account = ((ProcessThreadArguments)args).Account;

            ExternalBankData externalData = new ExternalBankData();

            externalData.Profile = ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId);
            // TODO: HACK HACK HACK HACK LOAD

            using (
                StreamReader reader = new StreamReader(StorageRoot + uploadedDoc.ServerFileName,
                                                       Encoding.GetEncoding(1252)))
            {
                externalData.LoadData(reader, ((ProcessThreadArguments)args).Organization, account.ForeignCurrency);
            }

            _staticDataLookup[guid + "FirstTx"] = externalData.Records[0].DateTime.ToLongDateString();
            _staticDataLookup[guid + "LastTx"]  =
                externalData.Records[externalData.Records.Length - 1].DateTime.ToLongDateString();
            _staticDataLookup[guid + "TxCount"] = externalData.Records.Length.ToString("N0");

            _staticDataLookup[guid + "Profile"] = externalData.Profile;

            _staticDataLookup[guid + "PercentRead"] = 1;

            DateTime timeWalker         = externalData.Records[0].DateTime;
            int      currentRecordIndex = 0;

            // Walk past the first identical time records, and verify that we have at least one balance record that matches
            // our own for this timestamp. There may be several transactions in the master file, but at least one should have
            // a post-transaction balance that matches our records, or something is much more broken.

            long swarmopsCentsStart = account.GetDeltaCents(Constants.DateTimeLow, timeWalker.AddSeconds(1));

            // At least one of the transactions for this timestamp should match.

            bool foundMatch = false;

            while (externalData.Records[currentRecordIndex].DateTime == timeWalker)
            {
                if (externalData.Records[currentRecordIndex].AccountBalanceCents == swarmopsCentsStart)
                {
                    foundMatch = true;

                    // continue loop until on first record past initial conditions
                }
                currentRecordIndex++; // no test for array overrun in while
            }

            if (!foundMatch)
            {
                throw new InvalidOperationException("Unable to locate stable initial conditions for resynchronization");
            }

            // From here on out, every new timestamp should have the exact same delta in Swarmops as it has in the master file.

            List <ExternalBankMismatchingDateTime> mismatchList = new List <ExternalBankMismatchingDateTime>();

            while (currentRecordIndex < externalData.Records.Length)
            {
                DateTime lastTimestamp = timeWalker;

                timeWalker = externalData.Records[currentRecordIndex].DateTime;

                long swarmopsDeltaCents = account.GetDeltaCents(lastTimestamp.AddSeconds(1), timeWalker.AddSeconds(1));
                // "AddSeconds" because DeltaCents operates on ">= lowbound, < highbound"
                int  timestampStartIndex    = currentRecordIndex;
                long masterDeltaCents       = externalData.Records[currentRecordIndex++].TransactionNetCents;
                int  masterTransactionCount = 1;

                while (currentRecordIndex < externalData.Records.Length &&
                       externalData.Records[currentRecordIndex].DateTime == timeWalker)
                {
                    masterDeltaCents += externalData.Records[currentRecordIndex++].TransactionNetCents;
                    masterTransactionCount++;
                }

                if (masterDeltaCents != swarmopsDeltaCents)
                {
                    // We have a mismatch. Add it to the list.

                    ExternalBankMismatchingDateTime newMismatch = new ExternalBankMismatchingDateTime();
                    newMismatch.DateTime                 = timeWalker;
                    newMismatch.MasterDeltaCents         = masterDeltaCents;
                    newMismatch.MasterTransactionCount   = masterTransactionCount;
                    newMismatch.SwarmopsDeltaCents       = swarmopsDeltaCents;
                    newMismatch.SwarmopsTransactionCount = 0; // TODO

                    // Load transactions from both sources. First, create the interim construction object.

                    ExternalBankMismatchConstruction mismatchConstruction = new ExternalBankMismatchConstruction();

                    // Load from Master

                    for (int innerRecordIndex = timestampStartIndex;
                         innerRecordIndex < currentRecordIndex;
                         innerRecordIndex++)
                    {
                        string description = externalData.Records[innerRecordIndex].Description.Replace("  ", " ");

                        if (!mismatchConstruction.Master.ContainsKey(description))
                        {
                            mismatchConstruction.Master[description] =
                                new ExternalBankMismatchingRecordConstruction();
                        }

                        mismatchConstruction.Master[description].Cents.Add(
                            externalData.Records[innerRecordIndex].TransactionNetCents);
                        mismatchConstruction.Master[description].Transactions.Add(null);
                        // no dependencies on the master side, only on swarmops side
                    }

                    // Load from Swarmops

                    FinancialAccountRows swarmopsTransactionRows =
                        account.GetRowsFar(lastTimestamp, timeWalker);
                    // the "select far" is a boundary < x <= boundary selector. Default is boundary <= x < boundary.

                    Dictionary <int, FinancialTransaction> lookupTransactions =
                        new Dictionary <int, FinancialTransaction>();

                    // note all transaction IDs, then sum up per transaction

                    foreach (FinancialAccountRow swarmopsTransactionRow in swarmopsTransactionRows)
                    {
                        lookupTransactions[swarmopsTransactionRow.FinancialTransactionId] =
                            swarmopsTransactionRow.Transaction;
                    }


                    foreach (FinancialTransaction transaction in lookupTransactions.Values)
                    {
                        string description = transaction.Description.Replace("  ", " ");
                        // for legacy compatibility with new importer

                        if (!mismatchConstruction.Swarmops.ContainsKey(description))
                        {
                            mismatchConstruction.Swarmops[description] =
                                new ExternalBankMismatchingRecordConstruction();
                        }

                        long cents = transaction[account];

                        if (cents != 0) // only add nonzero records
                        {
                            mismatchConstruction.Swarmops[description].Cents.Add(transaction[account]);
                            mismatchConstruction.Swarmops[description].Transactions.Add(transaction);
                        }
                    }

                    // Then, parse the intermediate construction object to the presentation-and-action object.

                    Dictionary <string, ExternalBankMismatchingRecordDescription> mismatchingRecordList =
                        new Dictionary <string, ExternalBankMismatchingRecordDescription>();

                    foreach (string masterKey in mismatchConstruction.Master.Keys)
                    {
                        Dictionary <int, bool> checkMasterIndex   = new Dictionary <int, bool>();
                        Dictionary <int, bool> checkSwarmopsIndex = new Dictionary <int, bool>();

                        // For each key and entry for each key;

                        // 1) locate an exact corresponding amount in swarmops records and log; failing that,
                        // 2) if exactly one record left in master and swarmops records, log; failing that,
                        // 3) log the rest of the master OR rest of swarmops records with no corresponding
                        //    equivalent with counterpart. (May produce bad results if 2 consistent mismatches
                        //    for every description.)

                        ExternalBankMismatchingRecordDescription newRecord =
                            new ExternalBankMismatchingRecordDescription();
                        newRecord.Description = masterKey;

                        List <long>   masterCentsList   = new List <long>();
                        List <long>   swarmopsCentsList = new List <long>();
                        List <object> dependenciesList  = new List <object>();
                        List <FinancialTransaction>             transactionsList = new List <FinancialTransaction>();
                        List <ExternalBankMismatchResyncAction> actionsList      =
                            new List <ExternalBankMismatchResyncAction>();

                        // STEP 1 - locate all identical matches

                        if (mismatchConstruction.Swarmops.ContainsKey(masterKey))
                        {
                            for (int masterIndex = 0;
                                 masterIndex < mismatchConstruction.Master[masterKey].Cents.Count;
                                 masterIndex++)
                            {
                                // no "continue" necessary on first run-through; nothing has been checked off yet

                                long findMasterCents = mismatchConstruction.Master[masterKey].Cents[masterIndex];

                                for (int swarmopsIndex = 0;
                                     swarmopsIndex < mismatchConstruction.Swarmops[masterKey].Cents.Count;
                                     swarmopsIndex++)
                                {
                                    if (checkSwarmopsIndex.ContainsKey(swarmopsIndex))
                                    {
                                        continue;
                                        // may have been checked off already in the rare case of twin identical amounts
                                    }

                                    if (findMasterCents == mismatchConstruction.Swarmops[masterKey].Cents[swarmopsIndex])
                                    {
                                        // There is a match as per case 1. Record both, mark both as used, continue.

                                        masterCentsList.Add(findMasterCents);
                                        swarmopsCentsList.Add(
                                            mismatchConstruction.Swarmops[masterKey].Cents[swarmopsIndex]);
                                        // should be equal, we're defensive here
                                        transactionsList.Add(
                                            mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex]);
                                        dependenciesList.Add(
                                            mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex]
                                            .Dependency);
                                        actionsList.Add(ExternalBankMismatchResyncAction.NoAction);

                                        checkMasterIndex[masterIndex]     = true;
                                        checkSwarmopsIndex[swarmopsIndex] = true;

                                        break;
                                    }
                                }
                            }
                        }

                        // STEP 2 - if exactly one record left on both sides, connect and log as mismatching record

                        // TODO: improve logic to handle same number of records left on both sides

                        if (mismatchConstruction.Swarmops.ContainsKey(masterKey) &&
                            mismatchConstruction.Master[masterKey].Cents.Count - checkMasterIndex.Keys.Count == 1 &&
                            mismatchConstruction.Swarmops[masterKey].Cents.Count - checkSwarmopsIndex.Keys.Count == 1)
                        {
                            for (int masterIndex = 0;
                                 masterIndex < mismatchConstruction.Master[masterKey].Cents.Count;
                                 masterIndex++)
                            {
                                if (checkMasterIndex.ContainsKey(masterIndex))
                                {
                                    continue; // This will fire for all but one indexes
                                }

                                long findMasterCents = mismatchConstruction.Master[masterKey].Cents[masterIndex];

                                for (int swarmopsIndex = 0;
                                     swarmopsIndex < mismatchConstruction.Swarmops[masterKey].Cents.Count;
                                     swarmopsIndex++)
                                {
                                    if (checkSwarmopsIndex.ContainsKey(swarmopsIndex))
                                    {
                                        continue;
                                    }

                                    masterCentsList.Add(findMasterCents);
                                    swarmopsCentsList.Add(mismatchConstruction.Swarmops[masterKey].Cents[swarmopsIndex]);
                                    dependenciesList.Add(
                                        mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex].Dependency);
                                    transactionsList.Add(
                                        mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex]);
                                    actionsList.Add(ExternalBankMismatchResyncAction.RewriteSwarmops);

                                    checkMasterIndex[masterIndex]     = true;
                                    checkSwarmopsIndex[swarmopsIndex] = true;
                                }
                            }
                        }

                        // STEP 3 - log remaining records on both sides as missing counterparts. Only one of these should fire.

                        // STEP 3a - log remaining on Master side

                        if (mismatchConstruction.Master[masterKey].Cents.Count > checkMasterIndex.Keys.Count)
                        {
                            for (int masterIndex = 0;
                                 masterIndex < mismatchConstruction.Master[masterKey].Cents.Count;
                                 masterIndex++)
                            {
                                if (checkMasterIndex.ContainsKey(masterIndex))
                                {
                                    continue;
                                }

                                masterCentsList.Add(mismatchConstruction.Master[masterKey].Cents[masterIndex]);
                                swarmopsCentsList.Add(0);  // null equivalent; invalid value
                                dependenciesList.Add(null);
                                transactionsList.Add(null);
                                actionsList.Add(ExternalBankMismatchResyncAction.CreateSwarmops);

                                checkMasterIndex[masterIndex] = true;
                            }
                        }

                        // STEP 3b - log remaining on Swarmops side

                        if (mismatchConstruction.Swarmops.ContainsKey(masterKey) &&
                            mismatchConstruction.Swarmops[masterKey].Cents.Count > checkSwarmopsIndex.Keys.Count)
                        {
                            for (int swarmopsIndex = 0;
                                 swarmopsIndex < mismatchConstruction.Swarmops[masterKey].Cents.Count;
                                 swarmopsIndex++)
                            {
                                if (checkSwarmopsIndex.ContainsKey(swarmopsIndex))
                                {
                                    continue;
                                }

                                masterCentsList.Add(0);  // null equivalent; invalid value
                                swarmopsCentsList.Add(mismatchConstruction.Swarmops[masterKey].Cents[swarmopsIndex]);
                                transactionsList.Add(
                                    mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex]);

                                if (mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex].Dependency !=
                                    null)
                                {
                                    dependenciesList.Add(
                                        mismatchConstruction.Swarmops[masterKey].Transactions[swarmopsIndex].Dependency);
                                    actionsList.Add(ExternalBankMismatchResyncAction.ManualAction);  // can't auto
                                }
                                else
                                {
                                    dependenciesList.Add(null);
                                    actionsList.Add(ExternalBankMismatchResyncAction.DeleteSwarmops);
                                }

                                checkMasterIndex[swarmopsIndex] = true;
                            }
                        }

                        newRecord.MasterCents   = masterCentsList.ToArray();
                        newRecord.SwarmopsCents = swarmopsCentsList.ToArray();
                        newRecord.ResyncActions = actionsList.ToArray();
                        // newRecord.TransactionDependencies = dependenciesList.ToArray();
                        newRecord.Transactions = transactionsList.ToArray();

                        mismatchingRecordList[masterKey] = newRecord;
                    }

                    // Finally, add the transactions that were (described) in Swarmops but not in Master

                    foreach (string swarmopsKey in mismatchConstruction.Swarmops.Keys)
                    {
                        if (!mismatchingRecordList.ContainsKey(swarmopsKey))
                        {
                            mismatchingRecordList[swarmopsKey]             = new ExternalBankMismatchingRecordDescription();
                            mismatchingRecordList[swarmopsKey].Description = swarmopsKey;

                            mismatchingRecordList[swarmopsKey].SwarmopsCents =
                                mismatchConstruction.Swarmops[swarmopsKey].Cents.ToArray();
                            mismatchingRecordList[swarmopsKey].Transactions =
                                mismatchConstruction.Swarmops[swarmopsKey].Transactions.ToArray();
                            mismatchingRecordList[swarmopsKey].MasterCents =
                                new long[mismatchConstruction.Swarmops[swarmopsKey].Cents.Count]; // inits to zero

                            mismatchingRecordList[swarmopsKey].ResyncActions =
                                new ExternalBankMismatchResyncAction[
                                    mismatchConstruction.Swarmops[swarmopsKey].Cents.Count];
                            for (int index = 0;
                                 index < mismatchingRecordList[swarmopsKey].ResyncActions.Length;
                                 index++)
                            {
                                mismatchingRecordList[swarmopsKey].ResyncActions[index] =
                                    ExternalBankMismatchResyncAction.DeleteSwarmops;
                            }
                        }
                    }

                    newMismatch.MismatchingRecords = mismatchingRecordList.Values.ToArray();

                    mismatchList.Add(newMismatch);
                }

                int percentProcessed = (int)(currentRecordIndex * 100L / externalData.Records.Length);

                lock (_staticDataLookup)
                {
                    if (percentProcessed > 1)
                    {
                        _staticDataLookup[guid + "PercentRead"] = percentProcessed;
                        // for the progress bar to update async
                    }

                    if (percentProcessed > 99)
                    {
                        // Placed inside loop to have a contiguous lock block, even though it decreases performance.
                        // Should normally be placed just outside.
                        _staticDataLookup[guid + "MismatchArray"] = mismatchList.ToArray();
                        _staticDataLookup[guid + "Account"]       = account;
                    }
                }
            }
        }
Beispiel #14
0
 public void Retire(Document doc)
 {
     Documents.Remove(doc);
 }
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean          running  = (Boolean)options["noquit"];
            Application      word     = null;
            object           oMissing = System.Reflection.Missing.Value;
            Template         tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.HasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Options   wdOptions      = null;
                Documents documents      = null;
                Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        ReleaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // If we are opening a document with a write password and no read password, and
                // we are not in read only mode, we should follow the document properties and
                // enforce a read only open. If we do not, Word pops up a dialog
                if (!nowrite && String.IsNullOrEmpty(writePassword) && IsReadOnlyEnforced(inputFile))
                {
                    nowrite = true;
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        ReleaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Window docWin     = null;
                    View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        word.PrintPreview                     = false;
                        docWinView.RevisionsView              = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments   = false;
                        docWinView.ShowComments               = false;
                        docWinView.ShowFormatChanges          = false;
                        docWinView.ShowInkAnnotations         = false;
                        docWinView.ShowInsertionsAndDeletions = false;
                    }
                    catch (SystemException e) {
                        Console.WriteLine("Failed to set revision settings {0}", e.Message);
                    }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;

                        if ((Boolean)options["word_fix_table_columns"])
                        {
                            FixWordTableColumnWidths(doc);
                        }
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        ReleaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        UpdateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    ReleaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    ReleaseCOMObject(docWinView);
                    ReleaseCOMObject(docWin);
                }

                // Set up a delegate function if we're using a printer
                PrintDocument printFunc = delegate(string destination, string printerName)
                {
                    word.ActivePrinter = printerName;
                    doc.PrintOut(Background: false, OutputFileName: destination);
                };

                if (String.IsNullOrEmpty((string)options["printer"]))
                {
                    // No printer given, so export
                    try
                    {
                        doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                                quality, WdExportRange.wdExportAllDocument,
                                                1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);
                    } catch (Exception)
                    {
                        // Couldn't export, so see if there is a fallback printer
                        if (!String.IsNullOrEmpty((string)options["fallback_printer"]))
                        {
                            PrintToGhostscript((string)options["fallback_printer"], outputFile, printFunc);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    PrintToGhostscript((string)options["printer"], outputFile, printFunc);
                }

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.ResetValue(ref wdOptions);
                }

                ReleaseCOMObject(wdOptions);
                ReleaseCOMObject(documents);
                ReleaseCOMObject(doc);
                ReleaseCOMObject(tmpl);
                ReleaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    CloseWordApplication(word);
                }
                ReleaseCOMObject(word);
            }
        }
Beispiel #16
0
        public IHttpActionResult Upload()
        {
            int      ProjectId = 0, AssignedToId = 0, UploadeById = 0, DocumentTypeId = 0;
            string   DocumentTitle = string.Empty, DocumentDescription = string.Empty;
            DateTime EffectiveDate = DateTime.Now;

            byte[] fileData    = null;
            var    result      = new HttpResponseMessage();
            var    httpContext = HttpContext.Current;
            var    httpRequest = httpContext.Request;

            try
            {
                if (!string.IsNullOrEmpty(httpRequest.Form["ProjectId"]))
                {
                    ProjectId = Convert.ToInt32(httpRequest.Form["ProjectId"]);
                }
                if (!string.IsNullOrEmpty(httpRequest.Form["AssignedToId"]))
                {
                    AssignedToId = Convert.ToInt32(httpRequest.Form["AssignedToId"]);
                }
                if (!string.IsNullOrEmpty(httpRequest.Form["DocumentType"]))
                {
                    DocumentTypeId = Convert.ToInt32(httpRequest.Form["DocumentTypeId"]);
                }
                if (!string.IsNullOrEmpty(httpRequest.Form["DocumentTitle"]))
                {
                    DocumentTitle = httpRequest.Form["DocumentTitle"];
                }
                if (!string.IsNullOrEmpty(httpRequest.Form["UploadeById"]))
                {
                    UploadeById = Convert.ToInt32(httpRequest.Form["UploadeById"]);
                }
                if (!string.IsNullOrEmpty(httpRequest.Form["DocumentDescription"]))
                {
                    DocumentDescription = httpRequest.Form["DocumentDescription"];
                }
                var    postedFile  = httpRequest.Files[0];
                string FileName    = postedFile.FileName;
                string contentType = postedFile.ContentType;
                using (var binaryReader = new BinaryReader(postedFile.InputStream))
                {
                    fileData = binaryReader.ReadBytes(postedFile.ContentLength);
                    var document = new Documents()
                    {
                        ProjectId           = ProjectId,
                        DocumentTitle       = DocumentTitle,
                        DocumentTypeId      = DocumentTypeId,
                        AssignedToId        = AssignedToId,
                        UploadedBy          = UploadeById,
                        FileNameUrl         = FileName,
                        CreatedOn           = DateTime.Now,
                        DocumentBytes       = fileData,
                        DocumentDescription = DocumentDescription
                    };
                    var docId = _documentService.Add(document);
                    if (docId > 0)
                    {
                        return(Ok("Uploaded successfully"));
                    }
                    else
                    {
                        return(Ok("Uploading failed"));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #17
0
        public string Enviar(BE.EntradaAlmacen beEntradaAlmacen, out int errCode, out string errMessage)
        {
            string docEntry = "";

            int    errCod = 0;
            string errMsg = "";

            try
            {
                Documents oEntradaAlmacen = oCompany.GetBusinessObject(BoObjectTypes.oInventoryGenEntry);

                oEntradaAlmacen.Series = beEntradaAlmacen.Serie;

                oEntradaAlmacen.DocDate    = beEntradaAlmacen.FechaContable;
                oEntradaAlmacen.TaxDate    = beEntradaAlmacen.FechaContable;
                oEntradaAlmacen.DocDueDate = beEntradaAlmacen.FechaCreacion;

                oEntradaAlmacen.Comments = beEntradaAlmacen.Comentario;

                oEntradaAlmacen.PaymentGroupCode = -1;

                oEntradaAlmacen.UserFields.Fields.Item("U_EXX_NOMBENEFE").Value = beEntradaAlmacen.Usuario;

                int linea = 0;
                foreach (var beEntradaAlmacenDetalle in beEntradaAlmacen.Detalle)
                {
                    if (linea > 0)
                    {
                        oEntradaAlmacen.Add();
                    }

                    oEntradaAlmacen.Lines.ItemCode        = beEntradaAlmacenDetalle.Codigo;
                    oEntradaAlmacen.Lines.ItemDescription = beEntradaAlmacenDetalle.Descripcion;
                    oEntradaAlmacen.Lines.Quantity        = beEntradaAlmacenDetalle.Cantidad;

                    //oEntradaAlmacen.Lines.Price = beEntradaAlmacenDetalle.Precio;
                    //oEntradaAlmacen.Lines.UnitPrice = beEntradaAlmacenDetalle.Precio;

                    //oEntradaAlmacen.Lines.TaxCode = beEntradaAlmacenDetalle.CodImpuesto;
                    //oEntradaAlmacen.Lines.Currency = beEntradaAlmacenDetalle.CodMoneda;

                    oEntradaAlmacen.Lines.WarehouseCode = beEntradaAlmacenDetalle.CodAlmacen;

                    //oEntradaAlmacen.Lines.AccountCode = beEntradaAlmacenDetalle.CodCuentaContable;

                    oEntradaAlmacen.Lines.CostingCode = beEntradaAlmacenDetalle.CodCentroCosto;
                    //oEntradaAlmacen.Lines.ProjectCode = beEntradaAlmacenDetalle.CodProyecto;

                    linea++;
                }


                int retCode = oEntradaAlmacen.Add();
                if (retCode == 0)
                {
                    docEntry = oCompany.GetNewObjectKey();
                }
                else
                {
                    oCompany.GetLastError(out errCod, out errMsg);
                }

                errCode    = errCod;
                errMessage = errMsg;

                return(docEntry);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #18
0
 public void RemoveDocument(Document obj)
 {
     Documents.Remove(obj);
 }
Beispiel #19
0
 ///<summary>
 /// Constructor
 ///</summary>
 ///<param name="context"></param>
 ///<param name="documentsApi">Docs api</param>
 public ProjectApi(ApiContext context, Documents.DocumentsApi documentsApi)
 {
     _documentsApi = documentsApi;
     _context = context;
 }
        internal override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free managed
                if (_documents != null)
                {
                    _documents.Dispose();
                    _documents = null;
                }

                if (_selection != null)
                {
                    _selection.Dispose();
                    _selection = null;
                }
            }

            base.Dispose(true);
        }
        public DocumentCollectionNode(DocumentClient client, Documents.DocumentCollection coll)
        {
            this.Text = coll.Id;
            this.Tag = coll;
            this.client = client;
            this.ImageKey = "SystemFeed";
            this.SelectedImageKey = "SystemFeed";

            this.Nodes.Add(new StoredProceduresNode(this.client));
            this.Nodes.Add(new UDFsNode(this.client));
            this.Nodes.Add(new TriggersNode(this.client));
            this.Nodes.Add(new ConflictsNode(this.client));

            MenuItem myMenuItem5 = new MenuItem("Read DocumentCollection");
            myMenuItem5.Click += new EventHandler(myMenuItemReadDocumentCollection_Click);
            this.contextMenu.MenuItems.Add(myMenuItem5);

            MenuItem myMenuItem3 = new MenuItem("Replace DocumentCollection");
            myMenuItem3.Click += new EventHandler(myMenuItemUpdateDocumentCollection_Click);
            this.contextMenu.MenuItems.Add(myMenuItem3);

            MenuItem myMenuItem6 = new MenuItem("Delete DocumentCollection");
            myMenuItem6.Click += new EventHandler(myMenuItemDeleteDocumentCollection_Click);
            this.contextMenu.MenuItems.Add(myMenuItem6);

            this.contextMenu.MenuItems.Add("-");

            MenuItem myMenuItem = new MenuItem("Create Document");
            myMenuItem.Click += new EventHandler(myMenuItemAddDocument_Click);
            this.contextMenu.MenuItems.Add(myMenuItem);
            MenuItem myMenuItem9 = new MenuItem("Create Document From File");
            myMenuItem9.Click += new EventHandler(myMenuItemAddDocumentFromFile_Click);
            this.contextMenu.MenuItems.Add(myMenuItem9);
            MenuItem myMenuItem4 = new MenuItem("Create Multiple Documents From Folder");
            myMenuItem4.Click += new EventHandler(myMenuItemAddDocumentsFromFolder_Click);
            this.contextMenu.MenuItems.Add(myMenuItem4);
            MenuItem myMenuItem1 = new MenuItem("Refresh Documents feed");
            myMenuItem1.Click += new EventHandler((sender, e) => Refresh(true));
            this.contextMenu.MenuItems.Add(myMenuItem1);
            MenuItem myMenuItem2 = new MenuItem("Query Documents");
            myMenuItem2.Click += new EventHandler(myMenuItemQueryDocument_Click);
            this.contextMenu.MenuItems.Add(myMenuItem2);
        }
        public DatabaseNode(DocumentClient localclient, Documents.Database db)
        {
            this.Text = db.Id;
            this.Tag = db;
            this.client = localclient;
            this.ImageKey = "SystemFeed";
            this.SelectedImageKey = "SystemFeed";

            this.Nodes.Add(new UsersNode(this.client));

            MenuItem myMenuItem3 = new MenuItem("Read Database");
            myMenuItem3.Click += new EventHandler(myMenuItemReadDatabase_Click);
            this.contextMenu.MenuItems.Add(myMenuItem3);

            MenuItem myMenuItem = new MenuItem("Delete Database");
            myMenuItem.Click += new EventHandler(myMenuItemDeleteDatabase_Click);
            this.contextMenu.MenuItems.Add(myMenuItem);

            this.contextMenu.MenuItems.Add("-");

            MenuItem myMenuItem2 = new MenuItem("Create DocumentCollection");
            myMenuItem2.Click += new EventHandler(myMenuItemAddDocumentCollection_Click);
            this.contextMenu.MenuItems.Add(myMenuItem2);
            MenuItem myMenuItem4 = new MenuItem("Refresh DocumentCollections Feed");
            myMenuItem4.Click += new EventHandler((sender, e) => Refresh(true));
            this.contextMenu.MenuItems.Add(myMenuItem4);

        }
        private void DoAssert(Documents.Document doc, bool fromIndex)
        {
            IndexableField[] keywordFieldValues = doc.GetFields("keyword");
            IndexableField[] textFieldValues = doc.GetFields("text");
            IndexableField[] unindexedFieldValues = doc.GetFields("unindexed");
            IndexableField[] unstoredFieldValues = doc.GetFields("unstored");

            Assert.IsTrue(keywordFieldValues.Length == 2);
            Assert.IsTrue(textFieldValues.Length == 2);
            Assert.IsTrue(unindexedFieldValues.Length == 2);
            // this test cannot work for documents retrieved from the index
            // since unstored fields will obviously not be returned
            if (!fromIndex)
            {
                Assert.IsTrue(unstoredFieldValues.Length == 2);
            }

            Assert.IsTrue(keywordFieldValues[0].StringValue.Equals("test1"));
            Assert.IsTrue(keywordFieldValues[1].StringValue.Equals("test2"));
            Assert.IsTrue(textFieldValues[0].StringValue.Equals("test1"));
            Assert.IsTrue(textFieldValues[1].StringValue.Equals("test2"));
            Assert.IsTrue(unindexedFieldValues[0].StringValue.Equals("test1"));
            Assert.IsTrue(unindexedFieldValues[1].StringValue.Equals("test2"));
            // this test cannot work for documents retrieved from the index
            // since unstored fields will obviously not be returned
            if (!fromIndex)
            {
                Assert.IsTrue(unstoredFieldValues[0].StringValue.Equals("test1"));
                Assert.IsTrue(unstoredFieldValues[1].StringValue.Equals("test2"));
            }
        }
        private void PushIntoDB(string[][] result, String type)
        {
            iCampusViewModel VM = App.ViewModel;
            Cours coursToUpdate;

            switch (type)
            {
                #region CASE COURS
                case "Cours":
                    foreach (string[] array in result)
                    {
                        Cours toPushC = new Cours { sysCode = array[0], title = array[1], titular = array[3], notified = (array[4] == "hot") };
                        VM.AddCours(toPushC);
                    }
                    VM.ClearCoursList();

                    if (RefreshAll)
                    {
                        RefreshAll = false;
                        Connect cx = new Connect();
                        foreach (Cours item in VM.AllCours)
                        {
                            //cx.Sync(item.url);
                        }
                    }
                    break;
                #endregion
                #region CASE SECTION
                case "Section":
                    coursToUpdate = (from Cours _cours in VM.AllCours where _cours.sysCode == result[0][4] select _cours).First();

                    foreach (string[] array in result)
                    {
                        switch (array[0])
                        {
                            case "Documents et liens":

                                Connect cx = new Connect();
                                coursToUpdate.isDnL = true;
                                coursToUpdate.dnlNotif = (array[4] == "hot");
                                cx.Sync(array[1].Replace("&amp;","&"));
                                break;

                            case "Annonces":
                                coursToUpdate.isAnn = true;
                                coursToUpdate.annNotif = (array[4] == "hot");
                                (new Connect()).Sync(array[1].Replace("&amp;", "&"));
                                break;

                            default:
                                break;
                        }
                    }
                    //VM.AddCours(coursToUpdate);
                    break;
                #endregion
                #region CASE DOC
                case "Docs":
                    coursToUpdate = (from Cours _cours in VM.AllCours where _cours.sysCode == result[0][7] select _cours).First();

                    foreach (string[] array in result)
                    {
                        string[] name = array[0].Split('.');

                        Documents toPush = new Documents()
                        {
                            url = array[1],
                            Description = array[5],
                            notified = (array[6] == "hot"),
                            Cours = coursToUpdate
                        };

                        switch (array[2])
                        {
                            case "document": //Dossier
                                toPush.path = array[0].Trim();
                                toPush.IsFolder = true;
                                toPush.date = DateTime.Today;
                                (new Connect()).Sync(array[1].Replace("&amp;", "&"));
                                break;

                            case "backends": //Fichier
                                string[] date = array[4].Split('.');
                                string[] partialSize = array[3].Replace("&nbsp;", " ").Replace('.', ',').Split(' ');
                                switch (partialSize[1])
                                {
                                    case "Ko":
                                        partialSize[1] = "E+3";
                                        break;
                                    case "Mo":
                                        partialSize[1] = "E+6";
                                        break;
                                    case "Go":
                                        partialSize[1] = "E+9";
                                        break;
                                    default:
                                        partialSize[1] = "";
                                        break;
                                }
                                if (name.Length > 2)
                                {
                                    for (int i = 1; i < name.Length - 1; i++)
                                    {
                                        name[0] += " "+name[i];
                                    }
                                }
                                toPush.path = name[0].Trim();
                                toPush.IsFolder = false;
                                toPush.Extension = name.Last().Trim();
                                toPush.size = Double.Parse(partialSize[0] + partialSize[1]);
                                toPush.date = new DateTime(int.Parse(date[2]), int.Parse(date[1]), int.Parse(date[0]));
                                break;

                            default:
                                break;
                        }
                        if (array[8] != null)
                        {
                            toPush.RootFolder = (from Documents _root in VM.AllFolders where _root.path == result[0][8] select _root).First();
                            toPush.IsRoot = false;
                        }
                        else
                        {
                            toPush.IsRoot = true;
                        }
                        //Debug.WriteLine("Adding Document" + toPush.Name + "\r" + toPush.IsRoot);
                        VM.AddDocument(toPush);
                    }
                    //VM.AddCours(coursToUpdate);
                    break;
                #endregion

                #region CASE ANNONCE
                case "Annonces":
                    coursToUpdate = (from Cours _cours in VM.AllCours where _cours.sysCode == result[0][4] select _cours).First();
                    foreach (string[] array in result)
                    {
                        Annonce AnnToPush = new Annonce()
                        {
                            title = array[0],
                            content = array[1],
                            notified = (array[3] == "hot"),
                            Cours = coursToUpdate,
                            date = DateTime.Parse(array[2])
                        };
                        //Debug.WriteLine("Adding "+ AnnToPush.title +" to DB (depend of " +  AnnToPush.Cours.sysCode);
                        VM.AddAnnonce(AnnToPush);
                    }
                    VM.ClearAnnsOfCours(coursToUpdate);
                    break;
                #endregion

                default:
                    break;
            }
        }
        public ActionResult SaveDocuments(ContainerViewModel model)
        {
            // Use your file here f

            foreach (var f in model.File)
            {
                var arrayBytes = ReadFully(f.InputStream);
                File(arrayBytes, f.ContentType);

                Documents entity = new Documents { document = arrayBytes, name = f.FileName, type = f.ContentType };
                context.Documents.Add(entity);
                context.SaveChanges();
            }

            //File.WriteAllBytes(model.File.InputStream, arrayBytes);

            return RedirectToAction("Information", new { id = model.GKey });
        }
Beispiel #26
0
        public CoverageResult GetCoverageResult()
        {
            CalculateCoverage();

            Modules modules = new Modules();

            foreach (var result in _results)
            {
                Documents documents = new Documents();
                foreach (var doc in result.Documents.Values)
                {
                    // Construct Line Results
                    foreach (var line in doc.Lines.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(line.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(line.Method, out Method method))
                                {
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                                else
                                {
                                    documents[doc.Path][line.Class].Add(line.Method, new Method());
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(line.Class, new Methods());
                                documents[doc.Path][line.Class].Add(line.Method, new Method());
                                documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(line.Class, new Methods());
                            documents[doc.Path][line.Class].Add(line.Method, new Method());
                            documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                        }
                    }

                    // Construct Branch Results
                    foreach (var branch in doc.Branches.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(branch.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(branch.Method, out Method method))
                                {
                                    method.Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                        );
                                }
                                else
                                {
                                    documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                    documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                                                                  );
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(branch.Class, new Methods());
                                documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                {
                                    Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                }
                                                                                              );
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(branch.Class, new Methods());
                            documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                            documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                            {
                                Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                            }
                                                                                          );
                        }
                    }
                }

                modules.Add(Path.GetFileName(result.ModulePath), documents);
                _instrumentationHelper.RestoreOriginalModule(result.ModulePath, _identifier);
            }

            var coverageResult = new CoverageResult {
                Identifier = _identifier, Modules = modules, InstrumentedResults = _results
            };

            if (!string.IsNullOrEmpty(_mergeWith) && !string.IsNullOrWhiteSpace(_mergeWith) && _fileSystem.Exists(_mergeWith))
            {
                string json = _fileSystem.ReadAllText(_mergeWith);
                coverageResult.Merge(JsonConvert.DeserializeObject <Modules>(json));
            }

            return(coverageResult);
        }
Beispiel #27
0
        /// <summary>
        /// Fetch documents from enumerator and add to buffer. If cache recycle, stop read to execute in another read
        /// </summary>
        public void Fetch(TransactionService trans, DataService data, BsonReader bsonReader)
        {
            // empty document buffer
            Documents.Clear();

            // while until must cache not recycle
            while (trans.CheckPoint() == false)
            {
                // read next node
                HasMore = _nodes.MoveNext();

                // if finish, exit loop
                if (HasMore == false)
                {
                    return;
                }

                // if run ONLY under index, skip/limit before deserialize
                if (_query.UseIndex && _query.UseFilter == false)
                {
                    if (--_skip >= 0)
                    {
                        continue;
                    }

                    if (--_limit <= -1)
                    {
                        HasMore = false;
                        return;
                    }
                }

                // get current node
                var node = _nodes.Current;

                // read document from data block
                var buffer = data.Read(node.DataBlock);
                var doc    = bsonReader.Deserialize(buffer).AsDocument;

                // if need run in full scan, execute full scan and test return
                if (_query.UseFilter)
                {
                    // execute query condition here - if false, do not add on final results
                    if (_query.FilterDocument(doc) == false)
                    {
                        continue;
                    }

                    // implement skip/limit after deserialize in full scan
                    if (--_skip >= 0)
                    {
                        continue;
                    }

                    if (--_limit <= -1)
                    {
                        HasMore = false;
                        return;
                    }
                }

                // increment position cursor
                _position++;

                // avoid lock again just to check limit
                if (_limit == 0)
                {
                    HasMore = false;
                }

                Documents.Add(doc);
            }
        }
Beispiel #28
0
 internal App(MdiForm mdiform)
 {
     m_mdiform = mdiform;
     m_docs = new Documents(this);
 }
Beispiel #29
0
        public CFE ObtenerDatosNotaDebito(int numNotaDebito, CAE.ESTipoCFECFC tipoCFE, string formaPago, string adenda, string razonRef)
        {
            Documents notaDebito = null;
            CFE cfe = new CFE();
            CFEInfoReferencia cfeReferencia;
            CFEItems item;
            Emisor emisor;
            Rango rango = null;
            CFEMediosPago mediosPago;
            CAE cae;
            descuentoGeneral = 0;
            descuentoGeneralExtranjero = 0;
            porcentajeDescuento = 0;

            try
            {

                notaDebito = ProcConexion.Comp.GetBusinessObject(BoObjectTypes.oInvoices);
                notaDebito.GetByKey(numNotaDebito);

                //Actualiza la forma de pagos
                notaDebito.UserFields.Fields.Item("U_U_FrmPagOIN").Value = formaPago;
                notaDebito.Update();

                #region EMISOR

                emisor = this.ObtenerDatosEmisor() as Emisor;
                cfe.RucEmisor = emisor.Ruc;
                cfe.NombreEmisor = emisor.Nombre;
                cfe.NombreComercialEmisor = emisor.NombreComercial;
                cfe.NumeroResolucion = emisor.NumeroResolucion;
                cfe.CodigoCasaPrincipalEmisor = this.ObtenerSucursal(notaDebito.DocEntry.ToString(), TABLA_NOTA_DEBITO);
                cfe.CajaEmisor = this.ObtenerCaja(notaDebito.DocEntry.ToString(), TABLA_NOTA_DEBITO);
                cfe.DomicilioFiscalEmisor = this.ObtenerDireccionEmisor();
                cfe.CiuidadEmisor = this.ObtenerCiudadEmisor();
                cfe.DocumentoSAP = notaDebito.DocEntry.ToString();
                cfe.EstadoDGI = CFE.ESEstadoCFE.PendienteDGI;
                cfe.EstadoReceptor = CFE.ESEstadoCFE.PendienteReceptor;

                #endregion EMISOR

                #region RECEPTOR

                cfe.TipoDocumentoReceptor = CFE.ObtenerTipoDocumentoReceptor(notaDebito.UserFields.Fields.Item("U_TipDocND").Value);
                cfe.CodigoPaisReceptor = this.ObtenerCodPaisReceptor(notaDebito.CardCode, cfe.TipoDocumentoReceptor);
                cfe.NombreReceptor = notaDebito.CardName;

                if (cfe.PaisReceptor.Equals("UY"))
                {
                    cfe.NumDocReceptorUruguayo = notaDebito.UserFields.Fields.Item("U_ValDocND").Value;
                }
                else
                {
                    cfe.NumDocReceptorExtrangero = notaDebito.UserFields.Fields.Item("U_ValDocND").Value;

                    ManteUdoAdobe manteUdoAdobe = new ManteUdoAdobe();
                    string ciGenereico = manteUdoAdobe.ObtenerCiGenerico();

                    if (cfe.NumDocReceptorExtrangero.Equals(ciGenereico))
                    {
                        cfe.NumDocReceptorExtrangero = "00000000";
                    }
                }

                //cfe.CiuidadReceptor = notaDebito.Address.Replace("\r", "");
                cfe.CiuidadReceptor = this.ObtenerCiudad(notaDebito.DocEntry, "INV12");
                cfe.PaisReceptor = this.ObtenerNombPaisReceptor(notaDebito.CardCode);
                cfe.CorreoReceptor = this.ObtenerCorreoReceptor(notaDebito.CardCode);
                //cfe.DireccionReceptor = cfe.CiuidadReceptor;// +" " + cfe.PaisReceptor;
                cfe.DireccionReceptor = this.ObtenerCiudad(notaDebito.DocEntry, "INV12");
                cfe.NumeroCompraReceptor = this.ObtenerNroPedidoReceptor(notaDebito.DocEntry, TABLA_NOTA_DEBITO);

                #endregion RECEPTOR

                #region TOTALES ENCABEZADO

                cfe.TipoModena = this.ObtenerCodigoISOModena(notaDebito.DocCurrency);

                ManteUdoTipoCambio manteUdoTipoCambio = new ManteUdoTipoCambio();
                string temp = "", confTC = manteUdoTipoCambio.ObtenerConfiguracion(out temp);

                if (confTC.Equals("N"))
                {
                     double docRate = this.ObtenerDocRate();
                    
                    if (cfe.TipoModena == "UYU" || cfe.TipoModena == "UY")
                    {
                                               
                            cfe.TipoCambio = 1;
                     }
                        else
                        {
                             if (docRate > 0)
                                {
                                    cfe.TipoCambio = 1 / docRate;
                                    cfe.TipoCambio = Math.Round(cfe.TipoCambio, 2);
                                }  
                        }                        
                    }
                                    
                else
                {
                    cfe.TipoCambio = notaDebito.DocRate;
                }

                //Si el cliente es extrangero entonces el monto de exportacion y asimilados es la suma de las lineas si importar el codigo de impuesto que tenga
                //y el monto total a pagar va ser ese mismo monto. En el xslt en ambos casos se asigna el mismo valor
                if (this.ValidarClienteExtranjero(notaDebito.CardCode))
                {
                    cfe.TotalMontoExportacionAsimilados = this.ObtenerTotalesExportacion(notaDebito);
                }
                else
                {
                    cfe.TotalMontoNoGravado = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("1"));// / cfe.TipoCambio;
                    cfe.TotalMontoNoGravadoExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("1"));
                    cfe.TotalMontoImpuestoPercibido = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("11"));// / cfe.TipoCambio;
                    cfe.TotalMontoImpuestoPercibidoExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("11"));
                    cfe.TotalMontoIVASuspenso = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("12"));// / cfe.TipoCambio;
                    cfe.TotalMontoIVASuspensoExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("12"));
                    cfe.TotalMontoNetoIVATasaMinima = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("2"));// / cfe.TipoCambio;
                    cfe.TotalMontoNetoIVATasaMinimaExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("2"));
                    cfe.TotalMontoNetoIVATasaBasica = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("3"));// / cfe.TipoCambio;
                    cfe.TotalMontoNetoIVATasaBasicaExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("3"));
                    cfe.TotalMontoNetoIVAOtraTasa = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("4"));// / cfe.TipoCambio;
                    cfe.TotalMontoNetoIVAOtraTasaExtranjero = this.ObtenerTotalesPorImpuesto(notaDebito, ObtenerCodigoImpuesto("4"));
                    cfe.TasaMinimaIVA = this.ObtenerIvaTasaMinima();
                    cfe.TasaBasicaIVA = this.ObtenerIvaTasaBasica();

                    cfe.TotalIVAOtraTasa = this.ObtenerTotalesIVAPorTasa(notaDebito.DocEntry.ToString(), "IVAB", "INV1");
                }

                cfe.Lineas = notaDebito.Lines.Count;

                #endregion TOTALES ENCABEZADO

                #region ITEMS

                for (int i = 0; i < notaDebito.Lines.Count; i++)
                {
                    notaDebito.Lines.SetCurrentLine(i);


                        //Si el Tipo de lista de Materiales de Ventas no lo agrego al XML 
                    if (!notaDebito.Lines.TreeType.ToString().Equals("iIngredient"))
                    {


                        //Nueva instancia del objeto item de cfe
                        item = cfe.NuevoItem();

                        item.NumeroLinea = i + 1;

                        string indFacturacionNumero = "";// notaDebito.Lines.UserFields.Fields.Item("U_IndND").Value + "";

                        if (indFacturacionNumero.Equals("6"))
                        {
                            item.IndicadorFacturacion = 6;
                        }
                        else if (indFacturacionNumero.Equals("7"))
                        {
                            item.IndicadorFacturacion = 7;
                        }
                        #region FE_EXPORTACION
                        else if (this.ValidarClienteExtranjero(notaDebito.CardCode))
                        {
                            item.IndicadorFacturacion = 10;
                        }
                        #endregion FE_EXPORTACION
                        else
                        {
                            string resultadoIndicadorFacturacion = this.ObtenerIndicadorFacturacion(notaDebito.Lines.TaxCode.ToString());

                            if (resultadoIndicadorFacturacion.Equals(""))
                            {
                                item.IndicadorFacturacion = 0;
                            }
                            else
                            {
                                item.IndicadorFacturacion = Convert.ToInt16(resultadoIndicadorFacturacion);
                            }


                          
                        }
                        item.NombreItem = notaDebito.Lines.ItemCode;
                        item.DescripcionItem = notaDebito.Lines.ItemDescription;
                        item.CantidadItem = notaDebito.Lines.Quantity;
                        item.PrecioUnitarioItem = notaDebito.Lines.Price - (notaDebito.Lines.Price * (notaDebito.DiscountPercent / 100));

                        if (item.PrecioUnitarioItem.ToString().Equals("0"))
                        {
                            item.IndicadorFacturacion = 5;
                        }


                        item.PrecioUnitarioItemPDF = notaDebito.Lines.Price;
                        item.LineNum = notaDebito.Lines.LineNum;
                        item.ArticulosXUnidad = notaDebito.Lines.UnitsOfMeasurment;
                        item.UnidadMedida = this.ObtenerUnidadMedidaItem(notaDebito.Lines.ItemCode, notaDebito.DocEntry + "", notaDebito.Lines.LineNum + "", "INV1");
                        item.UnidadMedidaPDF = item.UnidadMedida;
                        item.TipoImpuesto = notaDebito.Lines.TaxCode;

                        cfe.AgregarItem(item);

                    }
                }

                #endregion ITEMS

                #region MEDIOS DE PAGO

                mediosPago = cfe.NuevoMediosPago();
                mediosPago.Glosa = this.ObtenerMedioPago(notaDebito.DocEntry.ToString(), TABLA_NOTA_DEBITO);
                if (formaPago.Equals("Contado"))
                {
                    cfe.FormaPago = CFE.ESFormaPago.Contado;
                }
                else
                {
                    cfe.FormaPago = CFE.ESFormaPago.Credito;
                }
                cfe.AgregarMediosPago(mediosPago);

                #endregion MEDIOS DE PAGO

                descuentoGeneral = notaDebito.TotalDiscount;
                descuentoGeneralExtranjero = notaDebito.TotalDiscountFC;
                porcentajeDescuento = notaDebito.DiscountPercent;

                #region IDENTIFICACION DEL COMPROBANTE

                //Valida que el documento sea de contingencia
                if (FrmEstadoContingencia.estadoContingencia.Equals("Y"))
                {
                    //Valida que el cliente sea de contado
                    if (this.ValidarClienteContado(notaDebito.CardCode))
                    {
                        cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDETicketContingencia));
                    }
                    else
                    {
                        //Valida si es un ciente extranjero
                        if (this.ValidarClienteExtranjero(notaDebito.CardCode))
                        {
                            cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFacturaExportacionContingencia));
                        }
                        else
                        {
                            cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFacturaContingencia));
                        }
                    }
                }//Si no es contingencia
                else
                {
                    //Valida que el cliente sea de contado
                    if (this.ValidarClienteContado(notaDebito.CardCode))
                    {
                        cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDETicket));
                        rango = this.ObtenerDatosRangoCFE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDETicket), cfe.CodigoCasaPrincipalEmisor.ToString(), cfe.CajaEmisor) as Rango;
                    }
                    else
                    {
                        //Valida si es un cliente extranjero
                        if (this.ValidarClienteExtranjero(notaDebito.CardCode))
                        {
                            cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFacturaExportacion));
                            rango = this.ObtenerDatosRangoCFE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFacturaExportacion), cfe.CodigoCasaPrincipalEmisor.ToString(), cfe.CajaEmisor) as Rango;
                        }
                        else
                        {
                            cfe.TipoCFE = CFE.ObtenerTipoCFECFC(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFactura));
                            rango = this.ObtenerDatosRangoCFE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFactura), cfe.CodigoCasaPrincipalEmisor.ToString(), cfe.CajaEmisor) as Rango;
                        }
                    }
                }

                //Estado de contigencia serie y numero se ingresan manualmente
                if (FrmEstadoContingencia.estadoContingencia.Equals("Y"))
                {
                    SAPbouiCOM.Item txtNumCFE = SAPbouiCOM.Framework.Application.SBO_Application.Forms.ActiveForm.Items.Item("txtNumCFE");
                    SAPbouiCOM.Item txtSeCFE = SAPbouiCOM.Framework.Application.SBO_Application.Forms.ActiveForm.Items.Item("txtSeCFE");

                    cfe.SerieComprobante = ((SAPbouiCOM.EditText)txtSeCFE.Specific).Value + "";
                    cfe.NumeroComprobante = int.Parse(((SAPbouiCOM.EditText)txtNumCFE.Specific).Value + "");
                }
                else
                {
                    if (rango != null)
                    {
                        cfe.SerieComprobante = rango.Serie;
                        cfe.NumeroComprobante = rango.NumeroActual;
                    }
                }

                cfe.FechaComprobante = notaDebito.DocDate.ToString("yyyy-MM-dd");
                cfe.FechaVencimiento = notaDebito.DocDueDate.ToString("yyyy-MM-dd");

                if (notaDebito.DocType == BoDocumentTypes.dDocument_Items)
                {
                    cfe.TipoDocumentoSAP = CFE.ESTIpoDocumentoSAP.Articulo;
                }
                else if (notaDebito.DocType == BoDocumentTypes.dDocument_Service)
                {
                    cfe.TipoDocumentoSAP = CFE.ESTIpoDocumentoSAP.Servicio;
                }

                //if (notaDebito.DocumentStatus == BoStatus.bost_Close)
                //{
                //    cfe.FormaPago = CFE.ESFormaPago.Contado;
                //}
                //else
                //{
                //    cfe.FormaPago = CFE.ESFormaPago.Credito;
                //}

                #endregion IDENTIFICACION DEL COMPROBANTE

                #region EXPORTACION

                int modalidad, viaTransporte;

                bool convertido = int.TryParse(notaDebito.UserFields.Fields.Item("U_ModVenND").Value, out modalidad);

                if (convertido)
                {
                    cfe.ModalidadVentaInt = modalidad;
                }

                #region FE_EXPORTACION
                //cfe.ViaTransporteInt = notaDebito.TransportationCode;
                convertido = false;
                convertido = int.TryParse(notaDebito.UserFields.Fields.Item(Globales.Constantes.UDFViaTransporteND).Value, out viaTransporte);
                if (convertido)
                {
                    cfe.ViaTransporteInt = viaTransporte;
                }
                #endregion FE_EXPORTACION

                cfe.ClausulaVenta = notaDebito.UserFields.Fields.Item("U_ClaVenND").Value;

                #endregion EXPORTACION

                #region ADENDA

                //ManteUdoAdenda manteUdoAdenda = new ManteUdoAdenda();
                //Adenda adenda = manteUdoAdenda.ObtenerAdenda(ProcConexion.Comp, Adenda.ESTipoObjetoAsignado.TipoCFE113, notaDebito.DocNum.ToString());

                //cfe.TextoLibreAdenda = adenda.CadenaAdenda;
                cfe.TextoLibreAdenda = adenda;// notaDebito.UserFields.Fields.Item("U_AdendaND").Value;

                #endregion ADENDA

                #region DOCUMENTO DE REFERENCIA                

                //cfeReferencia = (CFEInfoReferencia)this.ObtenerDocumentoReferencia(TABLA_DETALLES_NOTA_DEBITO, notaDebito.DocEntry.ToString());

                //if (cfeReferencia != null)
                //{
                //    cfeReferencia.NumeroLinea = 1;
                //}
                //else
                //{
                //    cfeReferencia = new CFEInfoReferencia();
                //    cfeReferencia.IndicadorReferenciaGlobal = CFEInfoReferencia.ESIndicadorReferenciaGlobal.ReferenciaGlobal;
                //    cfeReferencia.NumeroLinea = 1;
                //    cfeReferencia.NumeroComprobanteReferencia = "";
                //    cfeReferencia.SerieComprobanteReferencia = "";

                //    if (FrmEstadoContingencia.estadoContingencia.Equals("Y"))
                //    {
                //        cfeReferencia.TipoCFEReferencia = 111;
                //        cfeReferencia.SerieComprobanteReferencia = "A";//Serie del documento de referencia
                //        cfeReferencia.NumeroComprobanteReferencia = "1";//Numero de CFE del documento de referencia
                //    }

                //    if (razonRef.Equals(""))
                //    {

                //        cfeReferencia.RazonReferencia = "Descuento General";
                //    }
                //    else
                //    {
                //        cfeReferencia.RazonReferencia = razonRef;
                //    }
                //}

                cfeReferencia = new CFEInfoReferencia();
                cfeReferencia.NumeroLinea = 1;
                cfeReferencia.SerieComprobanteReferencia = notaDebito.UserFields.Fields.Item("U_SerieRefND").Value;

                if (FrmEstadoContingencia.estadoContingencia.Equals("Y"))
                {
                    cfeReferencia.TipoCFEReferencia = 111;
                    cfeReferencia.SerieComprobanteReferencia = "A"; //Serie del documento de referencia
                    cfeReferencia.NumeroComprobanteReferencia = "1"; //Numero de CFE del documento de referencia
                }
                else
                {
                    if (cfeReferencia.SerieComprobanteReferencia == "" || cfeReferencia.SerieComprobanteReferencia == "1")
                    {
                        cfeReferencia.IndicadorReferenciaGlobal = CFEInfoReferencia.ESIndicadorReferenciaGlobal.ReferenciaGlobal;
                        cfeReferencia.SerieComprobanteReferencia = "";
                        cfeReferencia.NumeroComprobanteReferencia = "";
                        cfeReferencia.RazonReferencia = "Descuento General";
                    }
                    else
                    {
                        cfeReferencia.TipoCFEReferencia = 111;
                        cfeReferencia.NumeroComprobanteReferencia = notaDebito.UserFields.Fields.Item("U_NumRefND").Value;
                        cfeReferencia.RazonReferencia = razonRef;
                    }
                }

                if (cfeReferencia != null)
                {
                    cfe.AgregarInfoReferencia(cfeReferencia);
                }

                #endregion  DOCUMENTO DE REFERENCIA

                #region CAE

                //Valida que el documento sea de contingencia
                if (FrmEstadoContingencia.estadoContingencia.Equals("Y"))
                {
                    //Valida que el cliente sea de contado
                    if (this.ValidarClienteContado(notaDebito.CardCode))
                    {
                        cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.Contingencia)) as CAE;
                    }
                    else
                    {
                        cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.Contingencia)) as CAE;
                    }
                }//Si no es contingencia
                else
                {
                    //Valida que el cliente sea de contado
                    if (this.ValidarClienteContado(notaDebito.CardCode))
                    {
                        cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDETicket)) as CAE;
                    }
                    else
                    {
                        #region FE_EXPORTACION
                        //cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFactura)) as CAE;                        
                        if (ValidarClienteExtranjero(notaDebito.CardCode))
                        {
                            cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFacturaExportacion)) as CAE;
                        }
                        else
                        {
                            cae = this.ObtenerDatosCAE(CAE.ObtenerStringTipoCFECFC(CAE.ESTipoCFECFC.NDEFactura)) as CAE;
                        }
                        #endregion FE_EXPORTACION
                    }
                }

                if (cae.NumeroAutorizacion != null)
                {
                    cfe.NumeroCAE = long.Parse(cae.NumeroAutorizacion);
                    cfe.NumeroInicialCAE = cae.NumeroDesde;
                    cfe.NumeroFinalCAE = cae.NumeroHasta;
                    cfe.FechaVencimientoCAE = cae.FechaVencimiento;

                    ManteDocumentos manteDocumentos = new ManteDocumentos();
                    FinCae finCae = manteDocumentos.ObtenerAlertaCAE();

                      if (finCae.Cantidad > 0 && rango != null)
                    {
                    if ((cae.NumeroHasta - rango.NumeroActual) <= finCae.Cantidad)
                    {
                        SAPbouiCOM.Framework.Application.SBO_Application.MessageBox
                            ("!!!Atención!!!  Rango utilizado: " + rango.NumeroActual + " de: " + cae.NumeroHasta +
                            ". Solicitar Nuevos CAEs a DGI.");
                    }
                    }

                    DateTime fechaVencimiento = DateTime.Parse(cae.FechaVencimiento);
                    TimeSpan diferenciaDias = DateTime.Now.Subtract(fechaVencimiento);
                    int diasFecha = int.Parse(diferenciaDias.Days.ToString());

                    if (diasFecha > 0 && finCae.Dias != 0)
                    {
                        SAPbouiCOM.Framework.Application.SBO_Application.MessageBox
                            ("!!!Atención!!! El rango se venció, fecha de vencimiento: " + cae.FechaVencimiento);
                    }
                    else
                    {
                        diasFecha = diasFecha * -1;

                        if (diasFecha <= finCae.Dias && finCae.Dias != 0)
                        {
                            SAPbouiCOM.Framework.Application.SBO_Application.MessageBox
                                ("!!!Atención!!! El rango se va vencer, fecha de vencimiento: " + cae.FechaVencimiento);
                        }
                    }
                }
                else
                {
                    cfe = null;
                }

                #endregion CAE

                #region Web Service
                cfe.OrigenFE = notaDebito.UserFields.Fields.Item("U_Origen").Value;
                #endregion Web Service
            }
            catch (Exception ex)
            {
                SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("NotaDebitoB1/Error: " + ex.ToString());
            }
            finally
            {
                if (notaDebito != null)
                {
                    //Libera de memoria el obtejo notaDebito
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(notaDebito);
                    GC.Collect();
                }
            }

            return cfe;
        }
Beispiel #30
0
 public void LoadnewSupplDoc(Documents.SupplierDocuments sopenSupplDoc, string sCurrDocType)
 {
     sopenSupplDoc.Close();
     LoadSupplDoc(sCurrDocType);
 }
Beispiel #31
0
 public static PostBody ToViewModel(this Post post, Documents.Blog blog)
 {
     return new PostBody(post, blog);
 }
Beispiel #32
0
 public void LoadnewSalesOrder(Documents.SalesOrder sopenSalesOrder)
 {
     sopenSalesOrder.Close();
     salesOrderToolStripMenuItem_Click(null, null);
 }
        protected void ButtonRequest_Click(object sender, EventArgs e)
        {
            // The data has been validated client-side already. We'll throw unfriendly exceptions if invalid data is passed here.
            // People who choose to disable JavaScript and then submit bad input almost deserve to be hurt.

            Int64 amountCents = (Int64)(this.CurrencyAmount.Value * 100.0);

            string description = this.TextPurpose.Text;

            FinancialAccount budget = FinancialAccount.FromIdentity(Int32.Parse(Request.Form["DropBudgets"]));

            // sanity check

            if (budget.Organization.Identity != CurrentOrganization.Identity)
            {
                throw new InvalidOperationException("Budget-organization mismatch; won't file expense claim");
            }

            // Store bank details for current user

            CurrentUser.BankName     = this.TextBank.Text;
            CurrentUser.BankClearing = this.TextClearing.Text;
            CurrentUser.BankAccount  = this.TextAccount.Text;

            // Get documents; check that documents have been uploaded

            Documents documents = Documents.RecentFromDescription(this.FileUpload.GuidString);

            if (documents.Count == 0)
            {
                throw new InvalidOperationException("No documents uploaded");
            }

            ExpenseClaim claim = ExpenseClaim.Create(CurrentUser, CurrentOrganization, budget, DateTime.UtcNow,
                                                     description, amountCents);

            foreach (int tagSetId in this._tagSetIds)
            {
                string selectedTagString =
                    Request.Form["DropTags" + tagSetId.ToString(CultureInfo.InvariantCulture)];

                if (!String.IsNullOrEmpty(selectedTagString))
                {
                    int selectedTagType = Int32.Parse(selectedTagString);
                    if (selectedTagType != 0)
                    {
                        claim.FinancialTransaction.CreateTag(
                            FinancialTransactionTagType.FromIdentity(selectedTagType),
                            CurrentUser);
                    }
                }
            }

            documents.SetForeignObjectForAll(claim);

            string successMessage = string.Format(Resources.Pages.Financial.FileExpenseClaim_SuccessMessagePartOne,
                                                  CurrentOrganization.Currency.Code,
                                                  amountCents / 100.0,
                                                  budget.Name);

            if (budget.OwnerPersonId != CurrentUser.Identity)
            {
                successMessage += "<br/><br/>" + Resources.Pages.Financial.FileExpenseClaim_SuccessMessagePartTwo +
                                  "<br/>";
            }
            else
            {
                successMessage += "<br/><br/>" +
                                  Resources.Pages.Financial.FileExpenseClaim_SuccessMessagePartTwoOwnBudget +
                                  "<br/>";
                claim.Attest(CurrentUser);
            }

            Response.AppendCookie(new HttpCookie("DashboardMessage", HttpUtility.UrlEncode(successMessage)));

            // Redirect to dashboard

            Response.Redirect("/", true);
        }
    /// <summary>
    /// Save Client
    /// </summary>
    private void SaveClient()
    {
        var client = new Client
        {
            ClientId = Convert.ToInt32(lblClientId.Text),
            ClientName = txtClientName.Text,
            Email = txtEmail.Text,
            Telephone = txtTelephone.Text, 
            Website = txtWebsite.Text,   
        };
      

 
        // save the client id
        var clientId = new Clients().AddUpdateClient(client);

        //save client logo 
        if (!string.IsNullOrEmpty(txtUploadUrl.Text))
        {
            var logoDoc = new Document
            {
                RefId = clientId,
                DocumentTypeValue = 7,
                UploadUrl = txtUploadUrl.Text
            };
            var isSuccess = new Documents().SaveDocuments(new List<Document> { logoDoc });
        }
        txtUploadUrl.Text = "";
        lblClientId.Text = clientId.ToString();
        LoadClient();
    }
Beispiel #35
0
 public void Ajoute(Document doc)
 {
     Documents.Add(doc);
 }
 /// <summary> Return the offsetGap from the analyzer assigned to field </summary>
 public override int GetOffsetGap(Documents.IFieldable field)
 {
     Analyzer analyzer = analyzerMap[field.Name] ?? defaultAnalyzer;
     return analyzer.GetOffsetGap(field);
 }
 public override void Collect(int doc)
 {
     Documents.Add(doc + _docBase);
 }
Beispiel #38
0
 public void SetDocument(Documents.Document document)
 {
     Document = document;
     DocumentChanged();
 }
Beispiel #39
0
 public int CalculateCyclomaticComplexity(Documents documents)
 {
     return(documents.Values.SelectMany(c => c.Values.Select(CalculateCyclomaticComplexity)).Sum());
 }
 /*
  * Test function to reset db data
  */
 public void Reset()
 {
     Words.RemoveRange(Words);
     Documents.RemoveRange(Documents);
     SaveChanges();
 }
Beispiel #41
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get auth data

            this._authenticationData = GetAuthenticationDataAndCulture();

            string reportIdParameter  = Request.QueryString["ReportId"];
            string reportKeyParameter = Request.QueryString["ReportKey"];

            if (!string.IsNullOrEmpty(reportIdParameter))
            {
                this._reportId = Int32.Parse(reportIdParameter);  // will throw if non-numeric - don't matter for app
            }
            else if (!string.IsNullOrEmpty(reportKeyParameter))
            {
                this._reportId =
                    SwarmDb.GetDatabaseForReading().GetVatReportIdFromGuid(reportKeyParameter.ToLowerInvariant().Trim());
            }
            else
            {
                throw new ArgumentException("No Report Requested");
            }

            VatReport report = VatReport.FromIdentity(_reportId);

            // TODO: AUTH CHECK

            Response.ContentType = "application/json";

            Int64 turnoverCentsTotal = 0;
            Int64 inboundCentsTotal  = 0;
            Int64 outboundCentsTotal = 0;

            StringBuilder response = new StringBuilder(16384);

            VatReportItems items = report.Items;

            items.Sort(VatItemSorterByDate);
            List <string> lines = new List <string>();

            string hasDoxString =
                "<img data-txid='{0}' class='LocalViewDox action-icon' />" +
                "<img data-docid='{1}' data-docname=\\\"{2}\\\" class='LocalDownloadDox action-icon' />";

            foreach (VatReportItem item in items)
            {
                FinancialTransaction transaction = item.Transaction;
                bool include = false;

                string element = string.Format("\"id\":\"{0}\",\"txid\":\"{1}\",\"datetime\":\"{2:MMM dd}\",\"description\":\"{3}\"",
                                               transaction.Identity,
                                               transaction.OrganizationSequenceId,
                                               transaction.DateTime,
                                               JsonSanitize(transaction.Description));

                if (item.TurnoverCents != 0)
                {
                    element            += String.Format(",\"turnover\":\"{0:N2}\"", item.TurnoverCents / 100.0);
                    turnoverCentsTotal += item.TurnoverCents;
                    include             = true;
                }

                if (item.VatInboundCents != 0)
                {
                    element           += String.Format(",\"inbound\":\"{0:N2}\"", item.VatInboundCents / 100.0);
                    inboundCentsTotal += item.VatInboundCents;
                    include            = true;
                }

                if (item.VatOutboundCents != 0)
                {
                    element            += String.Format(",\"outbound\":\"{0:N2}\"", item.VatOutboundCents / 100.0);
                    outboundCentsTotal += item.VatOutboundCents;
                    include             = true;
                }

                Documents documents = Documents.ForObject(transaction.Dependency ?? transaction);

                if (documents.Count > 0)
                {
                    element += String.Format(",\"dox\":\"" + hasDoxString + "\"", transaction.Identity, documents[0].Identity, CurrentOrganization.Name + " - " + report.Description + " - " + Resources.Global.Financial_TransactionIdShort + transaction.OrganizationSequenceId.ToString("N0"));
                }

                if (include)
                {
                    lines.Add("{" + element + "}");
                }
            }

            if (lines.Count == 0) // add empty report line
            {
                lines.Add("{" + String.Format("\"id\":\"0\",\"description\":\"{0}\"",
                                              JsonSanitize(Resources.Pages.Ledgers.ViewVatReports_EmptyReport)) + "}");
            }

            Response.Write("{\"rows\":[" + String.Join(",", lines.ToArray()) + "]");

            Response.Write(",\"footer\":[{"); // needs to be on separate line to not trigger a String.Format warning

            Response.Write(String.Format("\"id\":\"0\",\"description\":\"{0}\",\"turnover\":\"{1:N2}\",\"inbound\":\"{2:N2}\",\"outbound\":\"{3:N2}\"",
                                         JsonSanitize(Resources.Pages.Ledgers.ViewVatReports_Footer_Total.ToUpperInvariant()), turnoverCentsTotal / 100.0, inboundCentsTotal / 100.0, outboundCentsTotal / 100.0));

            Response.Write("}]}"); // needs to be separate to not trigger String.Format warning

            Response.End();
        }
Beispiel #42
0
        /// <summary>
        /// Mass Invoicing
        /// </summary>
        /// <param name="invoice"></param>
        /// <returns></returns>
        public static ResultDTO CreateDraft(DocumentDTO invoice, UserValues user, FloorService floorServiceItem, string type)
        {
            var result           = new ResultDTO();
            var massInvoicingDAO = new MassInvoicingDAO();
            var distributionDAO  = new DistributionDAO();
            var objectCode       = "13";
            var containMainUsage = true;

            try {
                Documents lObjDocInvDrf = (Documents)DIApplication.Company.GetBusinessObject(BoObjectTypes.oDrafts); //ODRF

                var task = Task.Run(() => {
                    lObjDocInvDrf.CardCode      = invoice.Document.Code;
                    lObjDocInvDrf.CardName      = invoice.Document.Name;
                    lObjDocInvDrf.PaymentMethod = "99";

                    BusinessPartners BPartner = (BusinessPartners)DIApplication.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners);
                    BPartner.GetByKey(lObjDocInvDrf.CardCode);

                    if (BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value.ToString() == "")
                    {
                        BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "P01";
                        containMainUsage = false;
                    }
                    lObjDocInvDrf.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value;


                    //lObjDocInvDrf.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "Por Definir";
                    lObjDocInvDrf.UserFields.Fields.Item("U_PE_Origin").Value = type;
                    lObjDocInvDrf.DocObjectCode      = BoObjectTypes.oInvoices;
                    lObjDocInvDrf.PaymentGroupCode   = massInvoicingDAO.GetPayCondition(invoice.Document.Code);
                    lObjDocInvDrf.Series             = distributionDAO.GetSeries(user.WhsCode, objectCode);
                    lObjDocInvDrf.EDocGenerationType = EDocGenerationTypeEnum.edocGenerate;
                });

                var task2 = Task.Factory.StartNew(() => {
                    foreach (var line in invoice.FloorServiceLines)
                    {
                        lObjDocInvDrf.Lines.ItemCode      = floorServiceItem.ItemCode;
                        lObjDocInvDrf.Lines.WarehouseCode = line.Corral;
                        lObjDocInvDrf.Lines.Quantity      = (line.Existence * line.TotalDays);
                        lObjDocInvDrf.Lines.Price         = floorServiceItem.Price;
                        lObjDocInvDrf.Lines.CostingCode   = user.Area;
                        lObjDocInvDrf.Lines.UserFields.Fields.Item("U_SU_BatchAuc").Value = line.Batch;
                        lObjDocInvDrf.Lines.Add();
                    }

                    foreach (var line in invoice.DeliveryLines)
                    {
                        lObjDocInvDrf.Lines.ItemCode    = line.ItemCode;
                        lObjDocInvDrf.Lines.Quantity    = line.Quantity;
                        lObjDocInvDrf.Lines.Price       = line.Price;
                        lObjDocInvDrf.Lines.CostingCode = user.Area;
                        lObjDocInvDrf.Lines.BaseEntry   = line.DocEntry;
                        lObjDocInvDrf.Lines.BaseLine    = line.LineNum;
                        lObjDocInvDrf.Lines.BaseType    = 15; //ODLN
                        lObjDocInvDrf.Lines.Add();
                    }
                });

                //lObjDocInvDrf.EDocGenerationType = SAPbobsCOM.EDocGenerationTypeEnum.edocGenerate;
                //lObjDocInvDrf.EDocExportFormat = 9;
                Task.WaitAll(task, task2);



                if (lObjDocInvDrf.Add() != 0)
                {
                    LogService.WriteError("InvoiceDI (Draft) " + DIApplication.Company.GetLastErrorDescription());
                    result.Success = false;
                    result.Message = "Error: " + DIApplication.Company.GetLastErrorDescription();
                }
                else
                {
                    string lStrDocEntry = DIApplication.Company.GetNewObjectKey();

                    result.Success = true;
                    result.Message = DIApplication.Company.GetNewObjectKey();
                    if (containMainUsage == false)
                    {
                        result.Success = true;
                        result.Message = DIApplication.Company.GetNewObjectKey();
                        SAPbouiCOM.Framework.Application.SBO_Application.StatusBar.SetText("El socio de negocios no contenia Uso de CFDI, se asigno le asigno por default 'Por Definir'"
                                                                                           , SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
                    }
                }
            }
            catch (AggregateException ae) {
                LogService.WriteInfo(String.Format("Error: {0}", ae.Message));
                LogService.WriteError(ae);

                ae.Handle(e => {
                    HandleException(e, "InvoiceDI(Draft)");
                    result.Message = "Error: " + e.Message;
                    result.Success = false;
                    return(true);
                });
            }
            catch (Exception ex) {
                HandleException(ex, "InvoiceDI(Draft)");
                result.Message = "Error: " + ex.Message;
                result.Success = false;
            }
            return(result);
        }
Beispiel #43
0
        public ActionResult Upload(string baseData)
        {
            using (var db = new ExchangedbEntities())
            {
                if (HttpContext.Request.Files.AllKeys.Any())
                {
                    for (var i = 0; i < HttpContext.Request.Files.Count; i++)
                    {
                        var file = HttpContext.Request.Files["files" + i];
                        if (file != null)
                        {
                            var fileName = Path.GetFileName(file.FileName);

                            if (System.IO.File.Exists(Server.MapPath("~/Files/" + Session["Login"] + "/" + fileName)))
                            {
                                ModelState.AddModelError("", "File with " + fileName + " name exists \n");
                                //return PartialView("Upload");
                            }
                            else
                            {
                                file.SaveAs(Server.MapPath("~/Files/" + Session["Login"] + "/" + fileName));

                                var filesize =
                                    new FileInfo(Server.MapPath("~/Files/" + Session["Login"] + "/" + fileName)).Length;

                                var mimetype = MimeMapping.GetMimeMapping(fileName);

                                var dbFileType = db.FileType.FirstOrDefault(a => a.MIMEType.Equals(mimetype));

                                if (dbFileType == null && mimetype != null)
                                {
                                    var filetypeid = db.FileType.OrderByDescending(a => a.Id).FirstOrDefault().Id;

                                    dbFileType = new FileType
                                    {
                                        Id       = filetypeid + 1,
                                        MIMEType = mimetype,
                                        Type     = mimetype.Split('/')[0]
                                    };

                                    db.FileType.Add(dbFileType);
                                }

                                var document = new Documents
                                {
                                    Id           = Guid.NewGuid(),
                                    AccessId     = 1,
                                    CreatedBy    = Session["Login"].ToString(),
                                    CreationDate = DateTime.Now,
                                    LastEditDate = DateTime.Now,
                                    FileName     = fileName,
                                    Size         = Convert.ToInt32(filesize),
                                    FileTypeId   = dbFileType.Id
                                };


                                var id     = Session["Id"].ToString();
                                var dbUser = db.Users.FirstOrDefault(a => a.Id.ToString().Equals(id));

                                dbUser.Documents.Add(document);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            return(PartialView("Upload"));
        }
Beispiel #44
0
 public void PushDocument(Document document)
 {
     Documents.Enqueue(document);
 }
Beispiel #45
0
 public void AddDocument(Document obj)
 {
     Documents.Add(obj);
 }
Beispiel #46
0
        public void RefreshSamples(bool canGetDatas = true)
        {
            if (SysProcessManager == null)
            {
                return;
            }
            if (!mudoleHasInit)
            {
                return;
            }
            if (SysProcessManager.CurrentProcessTasks.Any(d => d.Publisher == this))
            {
                XLogSys.Print.WarnFormat("{0}已经有任务在执行,请在执行完毕后再刷新,或取消该任务", Name);
                return;
            }
            if (dataView == null && MainDescription.IsUIForm && IsUISupport)
            {
                var dock    = MainFrm as IDockableManager ?? ControlExtended.DockableManager;
                var control = dock?.ViewDictionary.FirstOrDefault(d => d.Model == this);
                if (control != null)
                {
                    if (control.View is IRemoteInvoke)
                    {
                        var invoke = control.View as IRemoteInvoke;
                        invoke.RemoteFunc = DropAction;
                    }
                    dynamic dy = control.View;

                    dataView     = dy.DataList;
                    scrollViewer = dy.ScrollViewer;

                    alltoolList            = dy.ETLToolList;
                    alltoolList.MouseMove += (s, e) =>
                    {
                        if (e.LeftButton == MouseButtonState.Pressed)
                        {
                            var attr = alltoolList.SelectedItem as XFrmWorkAttribute;
                            if (attr == null)
                            {
                                return;
                            }

                            var data = new DataObject(typeof(XFrmWorkAttribute), attr);
                            try
                            {
                                DragDrop.DoDragDrop(control.View as UserControl, data, DragDropEffects.Move);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    };
                }
            }
            Documents.Clear();

            var alltools = CurrentETLTools.Take(ETLMount).ToList();
            var hasInit  = false;
            var func     = Aggregate(d => d, alltools, false);

            if (!canGetDatas)
            {
                return;
            }
            var temptask = TemporaryTask.AddTempTask(Name + "_转换",
                                                     func(new List <IFreeDocument>()).Take(SampleMount),
                                                     data =>
            {
                ControlExtended.UIInvoke(() =>
                {
                    Documents.Add((data));
                    if (hasInit == false && Documents.Count > 2)
                    {
                        InitUI();
                        hasInit = true;
                    }
                });
            }, d =>
            {
                if (!hasInit)
                {
                    InitUI();
                    hasInit = true;
                }
            }
                                                     , SampleMount);

            temptask.Publisher = this;
            SysProcessManager.CurrentProcessTasks.Add(temptask);
        }
Beispiel #47
0
 public Loan(Session eSession)
 {
     _Session   = eSession;
     _Documents = new EncompassREST.Documents(this);
 }
        //Update
        public IHttpActionResult PutLogEntry(string id, Documents.PerformanceLogEntry logEntry)
        {
            if (id == logEntry._id.ToString())
            {
                MongoCollection<Documents.PerformanceLogEntry> logCollection =
                    _panzaDb.GetCollection<Documents.PerformanceLogEntry>("perf_log");

                WriteConcernResult wcr = logCollection.Save(logEntry);

                if (wcr.ErrorMessage == null)
                {
                    return Ok();
                }
            }

            return BadRequest();
        }
Beispiel #49
0
        private Documents GetLines(Documents pObjSaleOrder, string pStrRequestId, int pIntMobilizationTypeId)
        {
            SAPbobsCOM.Recordset lObjRecordSet = null;
            string lStrInsurenceItemCode       = "";
            string lStrQuery  = "";
            string lStrResult = mObjQueryManager.GetValue("U_ParentProductId", "U_RequestId", pStrRequestId, "[@UG_PE_WS_PRRE]");

            LogService.WriteInfo("[SaleOrder: TipoGanado" + lStrResult + "]");
            if (lStrResult == "105" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_EQUINO", "[@UG_CONFIG]");;
            }
            if (lStrResult == "1" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_BOVINO", "[@UG_CONFIG]");;
            }
            LogService.WriteInfo("[SaleOrder: ItemCode" + lStrInsurenceItemCode.ToString() + "]");
            double lDouInsurencePrice = GetInsurencePrice(lStrInsurenceItemCode.ToString());

            LogService.WriteInfo("[SaleOrder: Precio" + lDouInsurencePrice + "]");

            try
            {
                lObjRecordSet = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                Dictionary <string, string> lLstStrParameters = new Dictionary <string, string>();
                lLstStrParameters.Add("RequestId", pStrRequestId);
                lLstStrParameters.Add("MobilizationTypeId", pIntMobilizationTypeId.ToString());
                lStrQuery = this.GetSQL("GetItemAndPriceByProductRequests").Inject(lLstStrParameters);

                lObjRecordSet.DoQuery(lStrQuery);

                if (lObjRecordSet.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordSet.RecordCount; i++)
                    {
                        pObjSaleOrder.Lines.SetCurrentLine(i);
                        pObjSaleOrder.Lines.WarehouseCode = "OFGE";
                        pObjSaleOrder.Lines.ItemCode      = lObjRecordSet.Fields.Item("U_ItemCode").Value.ToString();
                        pObjSaleOrder.Lines.Quantity      = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                        pObjSaleOrder.Lines.Price         = Convert.ToDouble(lObjRecordSet.Fields.Item("Price").Value.ToString());
                        pObjSaleOrder.Lines.CostingCode   = "OG_PERMI";
                        //pObjSaleOrder.Update();
                        pObjSaleOrder.Lines.Add();

                        if (pIntMobilizationTypeId == 2)
                        {
                            pObjSaleOrder.Lines.WarehouseCode = "OFGE";
                            pObjSaleOrder.Lines.ItemCode      = lStrInsurenceItemCode;
                            pObjSaleOrder.Lines.Quantity      = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                            pObjSaleOrder.Lines.Price         = lDouInsurencePrice;
                            pObjSaleOrder.Lines.CostingCode   = "OG_PERMI";


                            pObjSaleOrder.Lines.Add();
                        }

                        lObjRecordSet.MoveNext();
                    }
                }
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordSet);
            }

            return(pObjSaleOrder);
        }
 public IEnumerable<Document> GetContactDocuments([FromUri] int contactId)
 {
     var candDocTypes = new Documents().GetDocumentTypesForPrimaryTypes("contact").Select(t => t.DocTypeValue).ToArray();
     return Documents.GetDocumentByDocType(candDocTypes, contactId);
 }
        private void RemoveDocument(JsonDocumentModel document)
        {
            Documents.Remove(document);

            document.UndoRedoManager.PropertyChanged -= UndoRedoManagerOnPropertyChanged;
        }
Beispiel #52
0
 public static PostList ToViewModel(this IEnumerable<Post> posts, Documents.Blog blog, int page, int pageSize, int totalRecords)
 {
     return new PostList(page, pageSize, totalRecords, posts.Select((post, idx) => new PostSummary(post, blog, idx, pageSize)));
 }
        private Entity UnMarshalJObject(JObject jObj)
        {
            Entity result = null;

            if (jObj["entity-type"] != null)
            {
                string entityType = jObj["entity-type"].ToObject <string>();
                if (entityType == "documents")
                {
                    if (jObj["isPaginable"] != null &&
                        jObj["isPaginable"].ToObject <bool>() == true)
                    {
                        Pageable page = JsonConvert.DeserializeObject <Pageable>(jObj.ToString());
                        foreach (Document document in page.Entries)
                        {
                            document.SetClient(client);
                        }
                        result = page;
                    }
                    else
                    {
                        Documents docs = JsonConvert.DeserializeObject <Documents>(jObj.ToString());
                        foreach (Document document in docs.Entries)
                        {
                            document.SetClient(client);
                        }
                        result = docs;
                    }
                }
                else if (entityType == "document")
                {
                    result = JsonConvert.DeserializeObject <Document>(jObj.ToString()).SetClient(client);
                }
                else if (entityType == "null")
                {
                    result = null;
                }
                else if (entityMap.ContainsKey(entityType))
                {
                    result = (Entity)JsonConvert.DeserializeObject(jObj.ToString(), entityMap[entityType]);
                }
                else if (businessObjects.ContainsKey(entityType))
                {
                    if (jObj["value"] != null && jObj["value"] is JObject)
                    {
                        JObject boJobj = new JObject();
                        boJobj.Add("entity-type", entityType);
                        foreach (KeyValuePair <string, JToken> pair in jObj["value"].ToObject <JObject>())
                        {
                            boJobj.Add(pair.Key, pair.Value);
                        }
                        result = (Entity)JsonConvert.DeserializeObject(boJobj.ToString(), businessObjects[entityType]);
                    }
                    else
                    {
                        throw new InvalidEntityException(jObj.ToString());
                    }
                }
                else
                {
                    result            = new UnknowEntity(jObj);
                    result.EntityType = entityType;
                }
            }
            else if (jObj["batchId"] != null)
            {
                result = JsonConvert.DeserializeObject <Batch>(jObj.ToString()).SetClient(client).SetClient(client);
            }
            else if (jObj["name"] != null &&
                     jObj["size"] != null &&
                     jObj["uploadType"] != null)
            {
                result = JsonConvert.DeserializeObject <BatchFile>(jObj.ToString());
            }
            else
            {
                result = new UnknowEntity(jObj);
            }
            return(result);
        }
Beispiel #54
0
 public PostBody(Post post, Documents.Blog blog)
 {
     this.post = post;
     this.blog = blog;
 }
Beispiel #55
0
        /// <summary>
        /// Mass Invoicing
        /// </summary>
        /// <param name="invoice"></param>
        /// <returns></returns>
        public static ResultDTO CreateInvoice(DocumentDTO invoice, UserValues user, FloorService floorServiceItem, string type)
        {
            var result = new ResultDTO();

            if (invoice.Document.Debt == 0)
            {
                result.Success = true;
                result.Message = "Ya Se Habia Facturado";
                return(result);
            }

            var       massInvoicingDAO = new MassInvoicingDAO();
            var       distributionDAO  = new DistributionDAO();
            var       objectCode       = BoObjectTypes.oInvoices.ToString();
            Documents lObjDocInvoice   = null;

            //var containMainUsage = true;

            try {
                //Documents lObjDocInvoice = (Documents)DIApplication.Company.GetBusinessObject(BoObjectTypes.oDrafts); //OINV
                lObjDocInvoice = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);

                lObjDocInvoice.DocDate         = DateTime.Now;
                lObjDocInvoice.CardCode        = invoice.Document.Code;
                lObjDocInvoice.CardName        = invoice.Document.Name;
                lObjDocInvoice.PaymentMethod   = "99";
                lObjDocInvoice.DocObjectCodeEx = "13";
                lObjDocInvoice.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "P01";
                lObjDocInvoice.Series           = distributionDAO.GetSeries(user.WhsCode, objectCode);
                lObjDocInvoice.PaymentGroupCode = massInvoicingDAO.GetPayCondition(invoice.Document.Code);
                lObjDocInvoice.UserFields.Fields.Item("U_PE_Origin").Value           = type;
                lObjDocInvoice.UserFields.Fields.Item("U_GLO_BusinessPartner").Value = invoice.Document.Code;
                //lObjDocInvoice.EDocExportFormat = 5;
                lObjDocInvoice.EDocGenerationType = EDocGenerationTypeEnum.edocGenerate;
                lObjDocInvoice.NumAtCard          = string.Format("CM_CR_{0}", DateTime.Today.ToString("ddMMyy"));

                #region Comments
                //BusinessPartners BPartner = (BusinessPartners)DIApplication.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners);
                //BPartner.GetByKey(lObjDocInvoice.CardCode);

                //if (BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value.ToString() == "")
                //{
                //    BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = "P01";
                //    containMainUsage = false;
                //}
                //lObjDocInvoice.UserFields.Fields.Item("U_B1SYS_MainUsage").Value = BPartner.UserFields.Fields.Item("U_B1SYS_MainUsage").Value;
                #endregion

                foreach (var line in invoice.FloorServiceLines)
                {
                    lObjDocInvoice.Lines.ItemCode      = floorServiceItem.ItemCode;
                    lObjDocInvoice.Lines.Quantity      = (line.Existence * line.TotalDays);
                    lObjDocInvoice.Lines.WarehouseCode = line.Corral;
                    lObjDocInvoice.Lines.Price         = floorServiceItem.Price;
                    lObjDocInvoice.Lines.CostingCode   = user.Area;
                    lObjDocInvoice.Lines.UserFields.Fields.Item("U_SU_BatchAuc").Value = (type.Equals("N")) ? line.Batch : line.DocEntry.ToString();

                    lObjDocInvoice.Lines.Add();
                }

                foreach (var line in invoice.DeliveryLines)
                {
                    lObjDocInvoice.Lines.ItemCode    = line.ItemCode;
                    lObjDocInvoice.Lines.Quantity    = line.Quantity;
                    lObjDocInvoice.Lines.Price       = line.Price;
                    lObjDocInvoice.Lines.CostingCode = user.Area;
                    lObjDocInvoice.Lines.BaseEntry   = line.DocEntry;
                    lObjDocInvoice.Lines.BaseLine    = line.LineNum;
                    lObjDocInvoice.Lines.BaseType    = 15; //ODLN
                    lObjDocInvoice.Lines.Add();
                }


                if (lObjDocInvoice.Add() != 0)
                {
                    var error = DIApplication.Company.GetLastErrorDescription();
                    LogService.WriteError("InvoiceDI (CreateDocument) " + error);
                    result.Success = false;
                    result.Message = "Error: " + error;
                    return(result);
                }
                else
                {
                    string lStrDocEntry = DIApplication.Company.GetNewObjectKey();

                    result.Success = true;
                    result.Message = string.Format("La Factura se realizó con éxito con el DocEntry: {0}", lStrDocEntry);

                    //Update StockTransfer When Auction Invoicing
                    if (type.Equals("S"))
                    {
                        var transferDocEntries = massInvoicingDAO.GetTransferDocEntries(invoice.Document.Code);

                        if (transferDocEntries != null)
                        {
                            if (transferDocEntries.Length > 0)
                            {
                                Task.Factory.StartNew(() => {
                                    Parallel.ForEach(transferDocEntries, docEntry => {
                                        StockTransfer lObjDocTransfer = (StockTransfer)DIApplication.Company.GetBusinessObject(BoObjectTypes.oStockTransfer); //OWTR
                                        lObjDocTransfer.GetByKey(docEntry);
                                        lObjDocTransfer.UserFields.Fields.Item("U_GLO_Status").Value = "C";
                                        var resultCode = lObjDocTransfer.Update();
                                        if (resultCode != 0)
                                        {
                                            var error = DIApplication.Company.GetLastErrorDescription();
                                            LogService.WriteError("InvoiceDI (Update Stock Transfers) " + error);
                                            result.Message += ", " + error;
                                        }
                                    });
                                });
                            }
                        }
                        else
                        {
                            result.Success  = false;
                            result.Message += string.Format(" - No se encontró la transferencia para el SN {0}", invoice.Document.Code);
                        }
                    }
                    return(result);
                }
            }
            catch (AggregateException ae) {
                ae.Handle(e => {
                    HandleException(e, "InvoiceDI(Document)");
                    return(true);
                });
            }
            catch (Exception ex) {
                HandleException(ex, "InvoiceDI(Document)" + ex.Message + " " + ex.InnerException.Message);
            }
            return(new ResultDTO()
            {
                Success = false, Message = "Error: No Se Pudo Crear La Factura Para el Cliente " + invoice.Document.Name
            });
        }
        private void SaveState(string fileName)
        {
            FileStream stream = null;

            try
            {
                stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);

                using (var writer = new BinaryWriter(stream))
                {
                    stream = null;

                    IEnumerable <ILayoutItem> itemStates = Documents.Concat(Tools.Cast <ILayoutItem>());

                    int itemCount = 0;
                    // reserve some space for items count, it'll be updated later
                    writer.Write(itemCount);

                    foreach (ILayoutItem item in itemStates)
                    {
                        if (!item.ShouldReopenOnStart)
                        {
                            continue;
                        }

                        ExportAttribute exportAttribute =
                            item.GetType()
                            .GetCustomAttributes(typeof(ExportAttribute), false)
                            .Cast <ExportAttribute>()
                            .FirstOrDefault();

                        string typeName = null;

                        if (exportAttribute != null && exportAttribute.ContractType != null)
                        {
                            typeName = exportAttribute.ContractType.AssemblyQualifiedName;
                        }

                        if (string.IsNullOrEmpty(typeName))
                        {
                            continue;
                        }

                        writer.Write(typeName);
                        writer.Write(item.ContentId);

                        // Here's the tricky part. Because some items might fail to save their state, or they might be removed (a plug-in assembly deleted and etc.)
                        // we need to save the item's state size to be able to skip the data during deserialization.
                        // Save surrent stream position. We'll need it later.
                        long stateSizePosition = writer.BaseStream.Position;

                        // Reserve some space for item state size
                        writer.Write(0L);

                        long stateSize;

                        try
                        {
                            long stateStartPosition = writer.BaseStream.Position;
                            item.SaveState(writer);
                            stateSize = writer.BaseStream.Position - stateStartPosition;
                        }
                        catch
                        {
                            stateSize = 0;
                        }

                        // Go back to the position before item's state and write the actual value.
                        writer.BaseStream.Seek(stateSizePosition, SeekOrigin.Begin);
                        writer.Write(stateSize);

                        if (stateSize > 0)
                        {
                            // Got to the end of the stream
                            writer.BaseStream.Seek(0, SeekOrigin.End);
                        }

                        itemCount++;
                    }

                    writer.BaseStream.Seek(0, SeekOrigin.Begin);
                    writer.Write(itemCount);
                    writer.BaseStream.Seek(0, SeekOrigin.End);

                    var shellView = Views.Values.Single() as IShellView;
                    if (shellView != null)
                    {
                        shellView.SaveLayout(writer.BaseStream);
                    }
                }
            }
            catch
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
Beispiel #57
0
        //
        /// <summary>
        /// SDW Upload document
        /// </summary>
        /// <param name="saveDoc"></param>
        /// <param name="caseId"></param>
        /// <returns></returns>
        internal string uploadDocument(Documents saveDoc, Int32 caseId)
        {
            String spName = "PKG_ICM_DOCUMENTS.ADD_DOCUMENT";
            var connectionString = dbConnSdw;

            string uFileName = "";
            var fname = saveDoc.fileName + Guid.NewGuid().ToString();

            try
            {
                using (var conn = new OracleConnection(connectionString))
                using (var command = new OracleCommand(spName, conn)
                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    //in
                    //  command.Parameters.Add("P_DOCFILENAME", OracleDbType.Varchar2, 256, saveDoc.fileName, ParameterDirection.Input);
                    command.Parameters.Add("P_CASE_ID", OracleDbType.Int32, caseId, ParameterDirection.Input);
                    command.Parameters.Add("P_USER_ID", OracleDbType.Int32, SpecDutyBase.gv.WW_USERLONG, ParameterDirection.Input);
                    command.Parameters.Add("P_TITLE", OracleDbType.Varchar2, 256, saveDoc.title, ParameterDirection.Input);
                    command.Parameters.Add("P_SIZE", OracleDbType.Int32, saveDoc.file_size, ParameterDirection.Input);
                    command.Parameters.Add("P_PATH", OracleDbType.Varchar2, 256, saveDoc.path + "/", ParameterDirection.Input);
                    command.Parameters.Add("P_EXTENSION", OracleDbType.Varchar2, 256, saveDoc.fileExtension, ParameterDirection.Input);
                    command.Parameters.Add("P_DOC_TYPE_ID", OracleDbType.Int32, 256, saveDoc.docTypeId, ParameterDirection.Input);
                    //out
                    command.Parameters.Add("P_FILE_NAME", OracleDbType.Varchar2, 256, saveDoc.fileName, ParameterDirection.InputOutput);
                    command.Parameters.Add("P_RESULT", OracleDbType.Varchar2, 256, "", ParameterDirection.Output);
                    //in
                    command.Parameters.Add("P_DOC_MIMETYPE", OracleDbType.Varchar2, 256, saveDoc.mimetype, ParameterDirection.Input);
                    command.Parameters.Add("P_LETTER_ID", OracleDbType.Int32, 256, 0, ParameterDirection.Input);
                    command.Parameters.Add("P_DT_CREATED", OracleDbType.Date, DateTime.Now, ParameterDirection.Input);
                    //  command.Parameters.Add("P_DT_CREATED", OracleDbType.Date, ParameterDirection.Input).Value = DateTime.Now;
                    command.Parameters.Add("P_IS_MEDMIDS", OracleDbType.Varchar2, ParameterDirection.Input).Value = "T";

                    // command.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
                    conn.Open();
                    command.ExecuteNonQuery();
                    uFileName = saveDoc.title; // command.Parameters["P_FILE_NAME"].Value.ToString();
                    string output2 = command.Parameters["P_RESULT"].Value.ToString();
                    conn.Close();
                }

            }
            catch (Exception ex)
            {
             //   logger.Fatal("SpecDutyBase.CaseAction 1 exception: " + ex.Message + ex.StackTrace);
                logger.Fatal("SpecDutyBase.CaseAction 1 exception: " ,ex);
                throw;
            }

            return uFileName;
        }
Beispiel #58
0
        static void Main(string[] args)
        {
            bool isSandbox = true;

            EnvironmentConfiguration.ChangeEnvironment(isSandbox);

            // Instantiate a new preApproval request
            PreApprovalRequest preApproval = new PreApprovalRequest();

            // Sets the currency
            preApproval.Currency = Currency.Brl;

            // Sets a reference code for this preApproval request, it is useful to identify this payment in future notifications.
            preApproval.Reference = "REF1234";

            // Sets your customer information.
            preApproval.Sender = new Sender(
                "Joao Comprador",
                "*****@*****.**",
                new Phone("11", "56273440")
                );

            // Sets the preApproval informations
            var now = DateTime.Now;

            preApproval.PreApproval                      = new PreApproval();
            preApproval.PreApproval.Charge               = Charge.Manual;
            preApproval.PreApproval.Name                 = "Seguro contra roubo do Notebook";
            preApproval.PreApproval.AmountPerPayment     = 100.00m;
            preApproval.PreApproval.MaxAmountPerPeriod   = 100.00m;
            preApproval.PreApproval.MaxPaymentsPerPeriod = 5;
            preApproval.PreApproval.Details              = string.Format("Todo dia {0} será cobrado o valor de {1} referente ao seguro contra roubo do Notebook.", now.Day, preApproval.PreApproval.AmountPerPayment.ToString("C2"));
            preApproval.PreApproval.Period               = Period.Monthly;
            preApproval.PreApproval.DayOfMonth           = now.Day <= 28 ? now.Day : 28;
            preApproval.PreApproval.InitialDate          = now;
            preApproval.PreApproval.FinalDate            = now.AddMonths(6);
            preApproval.PreApproval.MaxTotalAmount       = 600.00m;

            // Sets the url used by PagSeguro for redirect user after ends checkout process
            preApproval.RedirectUri = new Uri("http://www.lojamodelo.com.br/retorno");

            // Sets the url used for user review the signature or read the rules
            preApproval.ReviewUri = new Uri("http://www.lojamodelo.com.br/revisao");

            SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909");

            preApproval.Sender.Documents.Add(senderCPF);

            // Sets sender Address
            Address senderAddress = new Address("BR", "RJ", "Rio de Janeiro", "Copacabana", "03351-800", "Avenida Copacabana", "1000", "2o Andar");

            preApproval.Sender.Address = senderAddress;

            try
            {
                AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox);

                Uri preApprovalRedirectUri = preApproval.Register(credentials);

                Console.WriteLine("URL do pagamento : " + preApprovalRedirectUri);
                Console.ReadKey();
            }
            catch (PagSeguroServiceException exception)
            {
                Console.WriteLine(exception.Message + "\n");

                foreach (ServiceError element in exception.Errors)
                {
                    Console.WriteLine(element + "\n");
                }
                Console.ReadKey();
            }
        }
Beispiel #59
0
        private void InitUI()

        {
            var alltools = CurrentETLTools.Take(ETLMount).ToList();


            if (generateFloatGrid)
            {
                var gridview = PluginProvider.GetObjectInstance <IDataViewer>("可编辑列表");

                var r = gridview.SetCurrentView(Documents);

                if (ControlExtended.DockableManager == null)
                {
                    return;
                }

                ControlExtended.DockableManager.AddDockAbleContent(
                    FrmState.Custom, r, "样例数据");
                generateFloatGrid = false;
            }
            else
            {
                var view = new GridView();


                Dict.Clear();
                var keys = new List <string> {
                    ""
                };
                var docKeys = Documents.GetKeys(null, SampleMount);

                keys.AddRange(docKeys);
                var tool = CurrentTool;


                foreach (var key in keys)
                {
                    var col = new GridViewColumn
                    {
                        Header = key,
                        DisplayMemberBinding = new Binding($"[{key}]"),
                        Width = 155
                    };
                    view.Columns.Add(col);

                    var group = new SmartGroup
                    {
                        Name  = key,
                        Value = alltools.Where(d => d.Column == key).ToList()
                    };

                    group.PropertyChanged += (s, e) =>
                    {
                        if (e.PropertyName == "Name")
                        {
                            var last = alltools.LastOrDefault() as IColumnDataTransformer;
                            if (last != null && last.TypeName == "列名修改器" && last.NewColumn == key)
                            {
                                last.NewColumn = group.Name;
                            }
                            else
                            {
                                last           = PluginProvider.GetObjectInstance("列名修改器") as IColumnDataTransformer;
                                last.NewColumn = group.Name;
                                last.Column    = key;
                                InsertModule(last);
                                ETLMount++;
                                OnPropertyChanged("ETLMount");
                                RefreshSamples();
                            }
                        }
                    };
                    Dict.Add(group
                             );
                }
                if (tool != null)
                {
                    Dict.Where(d => d.Name == tool.Column).Execute(d => d.GroupType = GroupType.Input);
                    var transformer = tool as IColumnDataTransformer;
                    if (transformer != null)
                    {
                        var newcol = transformer.NewColumn.Split(' ');
                        if (transformer.IsMultiYield)
                        {
                            Dict.Execute(d => d.GroupType = newcol.Contains(d.Name)? GroupType.Input:GroupType.Output);
                        }
                        else
                        {
                            Dict.Where(d => d.Name == transformer.NewColumn).Execute(d => d.GroupType = GroupType.Output);;
                        }
                    }
                }
                var nullgroup = Dict.FirstOrDefault(d => string.IsNullOrEmpty(d.Name));
                nullgroup?.Value.AddRange(
                    alltools.Where(
                        d =>
                        Documents.GetKeys().Contains(d.Column) == false &&
                        string.IsNullOrEmpty(d.Column) == false));
                if (MainDescription.IsUIForm && IsUISupport)
                {
                    if (dataView != null)
                    {
                        dataView.View = view;
                    }
                }
            }
        }
Beispiel #60
0
        WblockCloneObjects()
        {
            try {
                m_db = Utils.Db.GetCurDwg();
                if (m_db == null)
                {
                    return;
                }

                using (TransactionHelper trHlpr = new TransactionHelper()) {
                    trHlpr.Start();

                    /// get the object to clone
                    Objects objs = new Objects(trHlpr);
                    if (objs.ShowDialog() != DialogResult.OK)
                    {
                        trHlpr.Abort();
                        return;
                    }

                    DBObject objToClone = trHlpr.Transaction.GetObject(objs.ObjectId, OpenMode.ForRead);

                    if (objToClone is DBDictionary)
                    {
                        throw new System.Exception("Please select a record in a dictionary");
                    }

                    AcadApp.Document activeDoc = AcadApp.Application.DocumentManager.MdiActiveDocument;

                    /// get cloning options...
                    ///

                    //String message = "\nDuplicate Record Cloning Options:";
                    //Array enums = Enum.GetValues(typeof(DuplicateRecordCloning));
                    //foreach (int option in enums) {
                    //    message += string.Format("\n{0} = {1}",
                    //                            option,
                    //                            Enum.GetName(typeof(DuplicateRecordCloning), option));
                    //}

                    //PromptIntegerOptions prOpts = new PromptIntegerOptions(message);
                    //prOpts.LowerLimit = 0;
                    //prOpts.UpperLimit = enums.Length;


                    //Editor ed = activeDoc.Editor;
                    //PromptIntegerResult prRes = ed.GetInteger(prOpts);
                    //if (prRes.Status != PromptStatus.OK)
                    //    return;

                    //DuplicateRecordCloning drc = (DuplicateRecordCloning)prRes.Value;
                    //if (drc == DuplicateRecordCloning.NotApplicable ||
                    //    drc == DuplicateRecordCloning.RefMangleName) {
                    //    ed.WriteMessage("Invalid Input");
                    //    return;
                    //}

                    /// .... or not
                    DuplicateRecordCloning drc = DuplicateRecordCloning.Ignore;

                    if (objToClone.OwnerId == ObjectId.Null) /// object to clone is a root object, can't clone
                    {
                        return;
                    }

                    /// get the destination db
                    Documents docs = new Documents();
                    docs.Text = "Destination database";

                    if (docs.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    Database dbSrc  = activeDoc.Database;
                    Database dbDest = docs.Document.Database;

                    if (dbDest == dbSrc)
                    {
                        throw new System.Exception("Please pick a destination database other than the source");
                    }

                    /// find out parent dictionary
                    ObjectId     owningDictId  = objToClone.OwnerId;
                    DBDictionary owningDictSrc = trHlpr.Transaction.GetObject(owningDictId, OpenMode.ForRead) as DBDictionary;

                    /// might be nested
                    Stack owningDictNames = new Stack();

                    while (owningDictSrc.OwnerId != ObjectId.Null)
                    {
                        owningDictSrc = trHlpr.Transaction.GetObject(owningDictSrc.OwnerId, OpenMode.ForRead) as DBDictionary;
                        String owningDictName = owningDictSrc.NameAt(owningDictId);
                        owningDictNames.Push(owningDictName);

                        owningDictId = owningDictSrc.ObjectId;
                    }

                    /// check if parent dictionary exists in dest.
                    DBDictionary owningDictDest = null;

                    using (Transaction trDest = dbDest.TransactionManager.StartTransaction()) {
                        AcadApp.Application.DocumentManager.GetDocument(dbDest).LockDocument();
                        DBDictionary parentDictDest = trDest.GetObject(dbDest.NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary;

                        String owningDictName = owningDictNames.Peek().ToString();

                        if (parentDictDest.Contains(owningDictName))
                        {
                            while (owningDictNames.Count != 0)
                            {
                                owningDictName = owningDictNames.Pop().ToString();
                                owningDictDest = trDest.GetObject(parentDictDest.GetAt(owningDictName), OpenMode.ForRead) as DBDictionary;
                                parentDictDest = owningDictDest;
                            }
                        }
                        else
                        {
                            /// dest doesnt have same structure , create it
                            while (owningDictNames.Count != 0)
                            {
                                owningDictName = owningDictNames.Pop().ToString();
                                parentDictDest.UpgradeOpen();
                                owningDictDest = new DBDictionary();
                                parentDictDest.SetAt(owningDictName, owningDictDest);
                                trDest.AddNewlyCreatedDBObject(owningDictDest, true);
                                parentDictDest = owningDictDest;
                            }
                        }

                        trDest.Commit();
                    }

                    /// clone the objects over
                    ObjectIdCollection objIds = new ObjectIdCollection();
                    objIds.Add(objToClone.ObjectId);

                    IdMapping idMap = new IdMapping();
                    idMap.DestinationDatabase = dbDest;

                    m_db.WblockCloneObjects(objIds, owningDictDest.ObjectId, idMap, drc, false);

                    trHlpr.Commit();
                }
            }

            catch (AcRx.Exception ex)
            {
                if (ex.ErrorStatus == AcRx.ErrorStatus.FileNotFound)
                {
                    MessageBox.Show("No documents found in current session");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }

            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }