Ejemplo n.º 1
0
        /// <summary>
        /// Extracts the payment package from another package.
        /// </summary>
        /// <param name="communicationXml">The communication XML.</param>
        /// <param name="communicationPackage">The communication package.</param>
        /// <returns>Extracted payment <c>CommunicationPackage</c> object if <b>communicationXml</b> has payment data; otherwise, <c>null</c>.</returns>
        public static CommunicationPackage ExtractPaymentPackage(DBXml communicationXml, ICommunicationPackage communicationPackage)
        {
            if (communicationXml.Table("payment") == null || communicationXml.Table("payment").HasRows == false)
            {
                return(null);
            }

            XDocument commXml = XDocument.Parse("<root/>");

            commXml.Root.Add(communicationXml.Table("payment").Xml);

            var settlements = communicationXml.Table("paymentSettlement");

            if (settlements != null && settlements.HasRows == true)
            {
                commXml.Root.Add(settlements.Xml);
            }

            XmlTransferObject commPkgData = new XmlTransferObject
            {
                DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId,
                Id = Guid.NewGuid(),
                LocalTransactionId = communicationPackage.XmlData.LocalTransactionId,
                XmlType            = CommunicationPackageType.Payment.ToString(),
                Content            = commXml.ToString(SaveOptions.DisableFormatting)
            };

            return(new CommunicationPackage(commPkgData)
            {
                DatabaseId = communicationPackage.DatabaseId
            });;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the number indicating previous version of bussiness object within database xml.
        /// </summary>
        /// <param name="dbXml">The database xml.</param>
        /// <returns>Previous version of bussiness object.</returns>
        public virtual Dictionary <string, string> GetPreviousVersion(DBXml dbXml)
        {
            var result = new Dictionary <string, string>(1);

            if (dbXml.Table(MainObjectTag).FirstRow().Action == DBRowState.Delete)
            {
                var ver = dbXml.Table(MainObjectTag).FirstRow().Element("version");
                if (ver != null)
                {
                    result.Add(String.Empty, dbXml.Table(MainObjectTag).FirstRow().Element("version").Value);
                }
                else
                {
                    return(null);
                }
            }
            else if (dbXml.PreviousVersion != null)
            {
                result.Add(String.Empty, dbXml.PreviousVersion);
            }
            else
            {
                return(null);
            }
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the number indicating previous version of bussiness object within database xml.
        /// </summary>
        /// <param name="dbXml">The database xml.</param>
        /// <returns>Previous version of bussiness object.</returns>
        public override Dictionary <string, string> GetPreviousVersion(DBXml dbXml)
        {
            if (dbXml.Table(MainObjectTag).Rows.Count() == 0)
            {
                return(null);
            }

            var result      = new Dictionary <string, string>(dbXml.Table(MainObjectTag).Rows.Count());
            var deletedRows = dbXml.Table(MainObjectTag).Rows.Where(r => r.Action == DBRowState.Delete);

            if (deletedRows.Count() > 0)
            {
                foreach (var row in deletedRows)
                {
                    var ver = row.Element("previousVersion");
                    if (ver != null)
                    {
                        result.Add(row.Element("id").Value, ver.Value);
                    }
                }
            }
            else if (dbXml.PreviousVersion != null)
            {
                result.Add(String.Empty, dbXml.PreviousVersion);
            }
            else
            {
                return(null);
            }

            return(result);
        }
Ejemplo n.º 4
0
 public virtual void SetPreviousVersion(DBXml dbXml, Dictionary <string, string> previousVersions)
 {
     // TODO zamienic na jakis inny wyjatek
     if (previousVersions.ContainsKey(String.Empty) == false)
     {
         throw new Exception("Previous version is not present in collection uder null key");
     }
     if (dbXml.Table(MainObjectTag).FirstRow().Element("version") == null)
     {
         dbXml.Table(MainObjectTag).FirstRow().AddElement("version", previousVersions[String.Empty]);
     }
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Executes the changeset. Operation is persisting changes to database.
 /// </summary>
 /// <param name="changeset">The changeset that is persisted.</param>
 public override void ExecuteChangeset(DBXml changeset)
 {
     repository.ExecuteOperations(changeset);
     //because
     if (changeset.Table(this.MainObjectTag) != null)
     {
         bool      isNew = (changeset.Table(this.MainObjectTag).FirstRow().Action.Value == DBRowState.Insert) ? true : false;
         XDocument xml   = XDocument.Parse("<root businessObjectId=\"\" mode=\"\" />");
         xml.Root.Attribute("businessObjectId").Value = this.CurrentPackage.Table(this.MainObjectTag).FirstRow().Element("id").Value;
         xml.Root.Attribute("mode").Value             = changeset.Table(this.MainObjectTag).FirstRow().Xml.Attribute("action").Value;
         this.repository.IndexDocument(xml, isNew);
     }
 }
Ejemplo n.º 6
0
        ///// <summary>
        ///// Check whether database xml from communication has correct version.
        ///// </summary>
        ///// <param name="commSnapshot">The snapshot from other branch.</param>
        ///// <param name="dbXml">The snapshot created from database.</param>
        ///// <returns><c>true</c> if database xml from communication has correct version; otherwise, <c>false</c>.</returns>
        //public virtual bool ValidateVersion(DBXml commSnapshot, DBXml dbXml)
        //{
        //    return GetPreviousVersion(commSnapshot)[null].Equals(dbXml.Table(MainObjectTag).FirstRow().Element("version").Value,
        //                                                   StringComparison.OrdinalIgnoreCase);
        //}

        /// <summary>
        /// Gets the number indicating previous version of bussiness object within database xml.
        /// </summary>
        /// <param name="dbXml">The database xml.</param>
        /// <returns>Previous version of bussiness object.</returns>
        public static Dictionary <string, string> GetPreviousVersion(DBXml dbXml, string mainObjectTag)
        {
            var result = new Dictionary <string, string>();

            foreach (DBRow row in dbXml.Table(mainObjectTag).Rows)
            {
                if (row.Action == DBRowState.Delete)
                {
                    var ver = row.Element("version");
                    if (ver != null)
                    {
                        result.Add(row.Element("id").Value, ver.Value);
                    }
                }
                else if (row.PreviousVersion != null)
                {
                    result.Add(row.Element("id").Value, row.PreviousVersion);
                }
            }
            if (result.Count == 0)
            {
                return(null);
            }
            else
            {
                return(result);
            }
        }
Ejemplo n.º 7
0
        private static bool IsSourceBranch(DBXml shiftDocument)
        {
            Guid branchId = Guid.Empty;

            if (IsOutcomeshift(shiftDocument) == true)
            {
                branchId = new Guid(shiftDocument.Table("warehouseDocumentHeader").FirstRow().Element("branchId").Value);
            }
            else
            {
                string targetWarehouseId        = null;
                string oppositeWarehouseFieldId = DictionaryMapper.Instance.GetDocumentField(Makolab.Fractus.Kernel.Enums.DocumentFieldName.ShiftDocumentAttribute_OppositeWarehouseId).Id.Value.ToString().ToUpperInvariant();
                targetWarehouseId = shiftDocument.Xml.Root.Element("documentAttrValue").Elements()
                                    .Where(row => row.Element("documentFieldId").Value.Equals(oppositeWarehouseFieldId))
                                    .Select(row => row.Element("textValue").Value)
                                    .SingleOrDefault();
                if (targetWarehouseId == null)
                {
                    throw new InvalidDataException("Missing target warehouse id.");
                }
                Warehouse targetWarehouse = DictionaryMapper.Instance.GetWarehouse(new Guid(targetWarehouseId));
                branchId = targetWarehouse.BranchId;
            }

            return(Makolab.Fractus.Kernel.Mappers.ConfigurationMapper.Instance.DatabaseId == DictionaryMapper.Instance.GetBranch(branchId).DatabaseId);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Executes the changeset. Operation is persisting changes to database.
        /// </summary>
        /// <param name="changeset">The changeset that is persisted.</param>
        public override void ExecuteChangeset(DBXml changeset)
        {
            this.repository.ExecuteOperations(changeset);

            List <string> indexedContractors = new List <string>();
            XDocument     xml      = XDocument.Parse("<root businessObjectId=\"\" mode=\"\" />");
            var           mainItem = this.CurrentPackage.Xml.Root.Descendants("contractorId").FirstOrDefault();

            if (mainItem != null)
            {
                xml.Root.Attribute("businessObjectId").Value = mainItem.Value;
                xml.Root.Attribute("mode").Value             = DBRowState.Update.ToStateName();
                this.repository.IndexContractor(xml);
                indexedContractors.Add(xml.Root.Attribute("businessObjectId").Value);
            }

            foreach (DBRow row in changeset.Table(MainObjectTag).Rows)
            {
                if (row.Action == DBRowState.Delete)
                {
                    continue;
                }

                string id = row.Element("relatedContractorId").Value;
                if (indexedContractors.Contains(id) == true)
                {
                    continue;
                }

                xml.Root.Attribute("businessObjectId").Value = id;
                xml.Root.Attribute("mode").Value             = DBRowState.Update.ToStateName();
                indexedContractors.Add(xml.Root.Attribute("businessObjectId").Value);
                this.repository.IndexContractor(xml);
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Executes the changeset. Operation is persisting changes to database.
 /// </summary>
 /// <param name="changeset">The changeset that is persisted.</param>
 public override void ExecuteChangeset(DBXml changeset)
 {
     if (this.executionMode == 1)
     {
         repository.ExecuteOperations(changeset);
     }
     else
     {
         DBXml   xml = new DBXml();
         DBTable tab = xml.AddTable(this.MainObjectTag);
         foreach (var valuation in changeset.Table(this.MainObjectTag).Rows)
         {
             Guid?savepointName = null;
             var  row           = tab.AddRow(valuation);
             try
             {
                 savepointName = Guid.NewGuid();
                 this.repository.CreateSavepoint(savepointName.ToString());
                 repository.ExecuteOperations(xml);
             }
             catch (SqlException)
             {
                 if (savepointName.HasValue)
                 {
                     this.repository.RollbackToSavepoint(savepointName.ToString());
                 }
             }
             row.Remove();
         }
     }
 }
Ejemplo n.º 10
0
        public override void SetPreviousVersion(DBXml dbXml, Dictionary <string, string> previousVersions)
        {
            if (dbXml.Table(MainObjectTag).Rows.Count() == 0)
            {
                return;
            }

            if (dbXml.Table(MainObjectTag).Rows.Any(r => r.Action == DBRowState.Delete))
            {
                PackageExecutionHelper.SetPreviousVersion(dbXml, previousVersions, this.MainObjectTag);
            }
            else
            {
                base.SetPreviousVersion(dbXml, previousVersions);
            }
        }
Ejemplo n.º 11
0
        private static bool IsIncomeshift(DBXml shiftDocument)
        {
            DocumentType docType = DictionaryMapper.Instance.GetDocumentType(new Guid(
                                                                                 shiftDocument.Table("warehouseDocumentHeader")
                                                                                 .FirstRow().Element("documentTypeId").Value));

            return(docType.WarehouseDocumentOptions.WarehouseDirection == Makolab.Fractus.Kernel.Enums.WarehouseDirection.IncomeShift);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Executes the changeset. Operation is persisting changes to database.
        /// </summary>
        /// <param name="changeset">The changeset that is persisted.</param>
        public override void ExecuteChangeset(DBXml changeset)
        {
            this.repository.ExecuteOperations(changeset);

            XDocument xml = XDocument.Parse("<root businessObjectId=\"\" mode=\"\" />");

            xml.Root.Attribute("businessObjectId").Value = this.CurrentPackage.Table(this.MainObjectTag).FirstRow().Element("id").Value;
            xml.Root.Attribute("mode").Value             = changeset.Table(this.MainObjectTag).FirstRow().Xml.Attribute("action").Value;
            this.repository.IndexContractor(xml);
        }
Ejemplo n.º 13
0
 public static void SetPreviousVersion(DBXml dbXml, Dictionary <string, string> previousVersions, string mainObjectTag)
 {
     foreach (var element in previousVersions)
     {
         var row = dbXml.Table(mainObjectTag).FindRow(element.Key);
         if (row != null && row.Element("version") == null)
         {
             row.AddElement("version", element.Value);
         }
     }
 }
Ejemplo n.º 14
0
 public static void RemoveDeletedRows(DBXml currentXml, DBXml dbXml, string mainObjectTag, ICommunicationLog log)
 {
     currentXml.Table(mainObjectTag).Rows
     .Where(r => r.Action == DBRowState.Delete)
     .Except(dbXml == null ? new List <DBRow>(0) : dbXml.Table(mainObjectTag).Rows, new DBRowIdComparer())
     .ToList()
     .ForEach(row =>
     {
         log.Info(mainObjectTag + " id=" + row.Element("id").Value + " is already deleted, skipping row");
         row.Remove();
     });
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Check whether database xml from communication has correct version.
        /// </summary>
        /// <param name="commSnapshot">The snapshot from other branch.</param>
        /// <param name="dbSnapshot">The snapshot created from database.</param>
        /// <returns><c>true</c> if database xml from communication has correct version; otherwise, <c>false</c>.</returns>
        public bool ValidateVersion(DBRow commSnapshot, DBXml dbSnapshot)
        {
            if (dbSnapshot != null &&
                commSnapshot.HasAction == false && //only delete action is valid
                commSnapshot.PreviousVersion.Equals(dbSnapshot.Table(MainObjectTag).FirstRow().Element("version").Value,
                                                    StringComparison.OrdinalIgnoreCase) == false)
            {
                return(false);
            }
            else if (dbSnapshot != null &&
                     commSnapshot.HasAction == true && //only delete action is valid
                     commSnapshot.Element("version").Value.Equals(dbSnapshot.Table(MainObjectTag).FirstRow().Element("version").Value,
                                                                  StringComparison.OrdinalIgnoreCase) == false)
            {
                return(false);
            }

            else
            {
                return(true);
            }
        }
Ejemplo n.º 16
0
        public override DBXml RemovePreviousVersion(DBXml dbXml)
        {
            if (dbXml.Table(MainObjectTag).Rows.Count() == 0)
            {
                return(dbXml);
            }

            var deletedRows = dbXml.Table(MainObjectTag).Rows.Where(r => r.Action == DBRowState.Delete);

            if (deletedRows.Count() > 0)
            {
                foreach (var row in deletedRows)
                {
                    row.RemovePreviousVersion();
                }
            }
            else
            {
                dbXml.RemovePreviousVersion();
            }

            return(dbXml);
        }
Ejemplo n.º 17
0
        private bool MustForwardPackage()
        {
            string oppositeDocumentId = PackageExecutionHelper.GetDocumentAttrValue(this.CurrentPackage.Table("documentAttrValue").Xml,
                                                                                    Makolab.Fractus.Kernel.Enums.DocumentFieldName.Attribute_OppositeDocumentId,
                                                                                    "textValue");

            if (oppositeDocumentId == null)
            {
                return(true);
            }

            DBXml oppositeSnapshot = this.repository.FindCommercialDocumentSnapshot(new Guid(oppositeDocumentId));

            if (oppositeSnapshot == null)
            {
                return(true);
            }

            string orderStatus = PackageExecutionHelper.GetDocumentAttrValue(this.CurrentPackage.Table("documentAttrValue").Xml,
                                                                             Makolab.Fractus.Kernel.Enums.DocumentFieldName.Attribute_OrderStatus,
                                                                             "textValue");
            string oppositeOrderStatus = (oppositeSnapshot.Table("documentAttrValue") == null) ? null :
                                         PackageExecutionHelper.GetDocumentAttrValue(oppositeSnapshot.Table("documentAttrValue").Xml,
                                                                                     Makolab.Fractus.Kernel.Enums.DocumentFieldName.Attribute_OrderStatus,
                                                                                     "textValue");

            //should work like this (orderStatus is a number) if ((orderStatus == null && oppositeOrderStatus != null) || (orderStatus != null && orderStatus.Equals(oppositeOrderStatus, StringComparison.OrdinalIgnoreCase) == false)) return true;
            if (orderStatus != oppositeOrderStatus)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Executes the changeset. Operation is persisting changes to database.
        /// </summary>
        /// <param name="changeset">The changeset that is persisted.</param>
        public override void ExecuteChangeset(DBXml changeset)
        {
            repository.ExecuteOperations(changeset);

            List <string> indexedItems = new List <string>();
            XDocument     xml          = XDocument.Parse("<root businessObjectId=\"\" mode=\"\" />");
            var           mainItem     = this.CurrentPackage.Xml.Root.Descendants("itemId").FirstOrDefault();

            if (mainItem != null)
            {
                xml.Root.Attribute("businessObjectId").Value = mainItem.Value;
                xml.Root.Attribute("mode").Value             = DBRowState.Update.ToStateName();
                this.repository.IndexItem(xml);
                indexedItems.Add(xml.Root.Attribute("businessObjectId").Value);
            }

            foreach (DBRow row in changeset.Table(MainObjectTag).Rows)
            {
                if (row.Action == DBRowState.Delete)
                {
                    continue;
                }

                string id = row.Element("relatedObjectId").Value;
                if (indexedItems.Contains(id) == true)
                {
                    continue;
                }

                xml.Root.Attribute("businessObjectId").Value = id;
                xml.Root.Attribute("mode").Value             = DBRowState.Update.ToStateName();
                ItemRelationType relationType      = DictionaryMapper.Instance.GetItemRelationType(new Guid(row.Element("itemRelationTypeId").Value));
                string           relatedObjectType = relationType.Metadata.Element("relatedObjectType").Value;
                switch (relatedObjectType)
                {
                case "Item":
                    this.repository.IndexItem(xml);
                    break;

                case "Contractor":
                    this.contractorRepository.IndexContractor(xml);
                    break;
                }
                indexedItems.Add(xml.Root.Attribute("businessObjectId").Value);
            }
        }
        public Dictionary <string, string> GetBranchList()
        {
            if (this.database.State != ConnectionState.Open)
            {
                this.database.Open();
            }

            using (SqlCommand cmd = this.helper.CreateCommand(StoredProcedure.dictionary_p_getBranches.ToProcedureName()))
            {
                XDocument branchXml = this.helper.GetXmlDocument(cmd.ExecuteXmlReader());
                DBXml     branches  = new DBXml(branchXml);
                Dictionary <string, string> branchList = new Dictionary <string, string>();
                foreach (var branch in branches.Table("branch").Rows)
                {
                    branchList.Add(branch.Element("id").Value, branch.Element("xmlLabels").Element("labels").Element("label").Value);
                }

                return(branchList);
            }
        }
Ejemplo n.º 20
0
        public override Dictionary <string, string> GetPreviousVersion(DBXml dbXml)
        {
            var prevVers = base.GetPreviousVersion(dbXml);

            if (this.currentContractor == null)
            {
                return(prevVers);
            }

            foreach (var table in this.extensionTables)
            {
                var commTab = dbXml.Table(table);
                var dbTab   = this.currentContractor.Table(table);
                if (commTab != null && commTab.HasRows && dbTab != null && dbTab.HasRows)
                {
                    string rand = Guid.NewGuid().ToString();
                    commTab.FirstRow().AddElement("_commReq", rand);
                    prevVers.Add(rand, dbTab.FirstRow().Element("version").Value);
                }
            }

            return(prevVers);
        }
Ejemplo n.º 21
0
 private static bool IsNewOrChanged(DBXml currentDocument, DBXml previousDocument)
 {
     return(previousDocument == null ||
            currentDocument.Table("warehouseDocumentHeader").FirstRow().Element("status").Value.Equals(
                previousDocument.Table("warehouseDocumentHeader").FirstRow().Element("status").Value) == false);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Check whether database xml from communication has correct version.
 /// </summary>
 /// <param name="commSnapshot">The snapshot from other branch.</param>
 /// <param name="dbSnapshot">The snapshot created from database.</param>
 /// <returns><c>true</c> if database xml from communication has correct version; otherwise, <c>false</c>.</returns>
 public virtual bool ValidateVersion(DBXml commSnapshot, DBXml dbSnapshot)
 {
     return(GetPreviousVersion(commSnapshot)[String.Empty].Equals(dbSnapshot.Table(MainObjectTag).FirstRow().Element("version").Value,
                                                                  StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Process communication package persisting it's data to database.
        /// </summary>
        /// <param name="communicationPackage">The communication package to execute.</param>
        /// <returns>
        ///     <c>true</c> if execution succeeded; otherwise, <c>false</c>
        /// </returns>
        public override bool ExecutePackage(ICommunicationPackage communicationPackage)
        {
            try
            {
                SessionManager.VolatileElements.DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId;
                SessionManager.VolatileElements.LocalTransactionId    = this.LocalTransactionId;

                bool result = base.ExecutePackage(communicationPackage);
                if (result == false)
                {
                    return(false);
                }

                //skip local shift documents
                if (IsLocal(this.CurrentPackage) == true)
                {
                    return(true);
                }

                using (var wrapper = this.UnitOfWork.ConnectionManager.SynchronizeConnection())
                {
                    SqlConnectionManager.Instance.SetConnection(wrapper.Connection, this.UnitOfWork.Transaction as SqlTransaction);
                }

                bool isOutcomeshift = IsOutcomeshift(this.CurrentPackage);
                bool isIncomeShift  = IsIncomeshift(this.CurrentPackage);
                bool isTargetBranch = IsTargetBranch(this.CurrentPackage);
                bool isSourceBranch = IsSourceBranch(this.CurrentPackage);

                if (isOutcomeshift == true)
                {
                    if (isTargetBranch == true)
                    {
                        if (this.IsHeadquarter == false)
                        {
                            DBXml series = new DBXml();
                            series.AddTable(this.CurrentPackage.Table("series"));

                            SeriesScript seriesProcessor = new SeriesScript(this.UnitOfWork, this.ExecutionController);
                            seriesProcessor.Log = this.Log;
                            seriesProcessor.LocalTransactionId = this.LocalTransactionId;
                            CommunicationPackage seriesPackage = new CommunicationPackage(new XmlTransferObject()
                            {
                                Content = series.Xml.ToString(SaveOptions.DisableFormatting)
                            });
                            seriesPackage.DatabaseId = communicationPackage.DatabaseId;
                            seriesPackage.XmlData.LocalTransactionId    = communicationPackage.XmlData.LocalTransactionId;
                            seriesPackage.XmlData.DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId;
                            seriesProcessor.ExecutePackage(seriesPackage);
                        }

                        this.ExecutionController.ExecuteCommand(() => ExecuteOutcomeShift());
                        if (this.CurrentPackage.Xml.Root.Attribute("skipPackage") == null)
                        {
                            this.CurrentPackage.Xml.Root.Add(new XAttribute("skipPackage", true));
                        }
                    }

                    if (this.IsHeadquarter && isTargetBranch == false)
                    {
                        DBXml series = this.Repository.FindSeries(new Guid(this.CurrentPackage.Table("warehouseDocumentHeader").FirstRow().Element("seriesId").Value));
                        this.CurrentPackage.AddTable(series.Table("series"));
                    }
                    if (this.IsHeadquarter == false && isTargetBranch == false && isSourceBranch == false)
                    {
                        throw new InvalidOperationException("ShiftDocumentSnapshot is in invalid branch.");
                    }
                }
                else if (isIncomeShift == true && this.IsHeadquarter == true && (isTargetBranch || IsNewOrChanged(this.CurrentPackage, this.previousDocument)))
                {
                    this.ExecutionController.ExecuteCommand(() => ExecuteIncomeShift());
                }
                communicationPackage.XmlData.Content = this.CurrentPackage.Xml.ToString(SaveOptions.DisableFormatting);
                return(result);
            }
            catch (SqlException e)
            {
                if (e.Number == 50012) // Conflict detection
                {
                    throw new ConflictException("Conflict detected while changing " + this.MainObjectTag);
                }
                else
                {
                    this.Log.Error("ShiftDocumentSnapshot:ExecutePackage " + e.ToString());
                    return(false);
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Process communication package persisting it's data to database.
        /// </summary>
        /// <param name="communicationPackage">The communication package to execute.</param>
        /// <returns>
        ///     <c>true</c> if execution succeeded; otherwise, <c>false</c>
        /// </returns>
        public override bool ExecutePackage(ICommunicationPackage communicationPackage)
        {
            SessionManager.VolatileElements.DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId;
            SessionManager.VolatileElements.LocalTransactionId    = this.LocalTransactionId;

            this.CurrentPackage = new DBXml(XDocument.Parse(communicationPackage.XmlData.Content));

            //Guid mainObjectId = new Guid(this.CurrentPackage.Table(MainObjectTag).Row().Element("id").Value);
            //DBXml dbSnapshot = GetCurrentSnapshot(mainObjectId);

            DBXml dbSnapshot        = new DBXml();
            Guid  currentConGrMemId = Guid.Empty;
            var   dbTables          = new List <DBTable>();

            try
            {
                var groupsAlreadyRemoved = new List <DBRow>();
                foreach (var conGrMem in this.CurrentPackage.Table(MainObjectTag).Rows)
                {
                    currentConGrMemId = new Guid(conGrMem.Element("id").Value);
                    DBXml currentDBSnapshot = GetCurrentSnapshot(currentConGrMemId);

                    if (conGrMem.Action == DBRowState.Delete && currentDBSnapshot == null)
                    {
                        groupsAlreadyRemoved.Add(conGrMem);
                    }

                    // TODO conflict detection & resolution
                    //if (ValidateVersion(conGrMem, currentDBSnapshot) == false)
                    //{
                    //    throw new ConflictException("Conflict detected while changing " + this.MainObjectTag + " id: " + currentConGrMemId);
                    //}

                    if (conGrMem.Element("_object1from") != null)
                    {
                        DBXml contractor = repository.FindContractorSnapshot(new Guid(conGrMem.Element("contractorId").Value));
                        if (contractor != null && contractor.Table("contractor").FirstRow().Element("version").Value.Equals(conGrMem.Element("_object1from").Value) == false)
                        {
                            this.Log.Error("ItemGroupMembershipScript: Wystapil konflikt wersji towaru " + conGrMem.Element("contractorId").Value + " oczekiwano " +
                                           conGrMem.Element("_object1from").Value +
                                           " otrzymano " + contractor.Table("contractor").FirstRow().Element("version").Value);

                            conGrMem.Element("_object1from").Value = contractor.Table("contractor").FirstRow().Element("version").Value;
                        }
                    }

                    if (currentDBSnapshot != null)
                    {
                        dbTables.Add(currentDBSnapshot.Table(this.MainObjectTag));
                    }
                }
                dbSnapshot.AddTable(dbTables);

                DBXml changeset = GenerateChangeset(CurrentPackage, dbSnapshot);
                ExecuteChangeset(changeset);
            }
            catch (SqlException e)
            {
                if (e.Number == 50012) // Conflict detection
                {
                    throw new ConflictException("Conflict detected while changing " + this.MainObjectTag + " id: " + currentConGrMemId.ToString());
                }
                else
                {
                    this.Log.Error("SnapshotScript:ExecutePackage " + e.ToString());
                    return(false);
                }
            }

            return(true);
        }
        public Dictionary <string, DepartmentStatistics> GetBasicStatisticsList()
        {
            if (this.database.State != ConnectionState.Open)
            {
                this.database.Open();
            }

            DBXml branches = null;

            using (SqlCommand cmd = this.helper.CreateCommand(StoredProcedure.dictionary_p_getBranches.ToProcedureName()))
            {
                XDocument branchXml = this.helper.GetXmlDocument(cmd.ExecuteXmlReader());
                branches = new DBXml(branchXml);
            }


            using (SqlCommand cmd = this.helper.CreateCommand(StoredProcedure.communication_p_getStatisticsList.ToProcedureName()))
            {
                XDocument statisticsXml = this.helper.GetXmlDocument(cmd.ExecuteXmlReader());
                DBXml     statistics    = new DBXml(statisticsXml);

                Dictionary <string, DepartmentStatistics> branchStatisticsList = new Dictionary <string, DepartmentStatistics>();
                foreach (var branchStats in statistics.Table("statistics").Rows)
                {
                    string branchId = branches.Table("branch").Rows.Where(row => row.Element("databaseId").Value.Equals(branchStats.Element("databaseId").Value, StringComparison.OrdinalIgnoreCase))
                                      .First().Element("id").Value;
                    DepartmentStatistics branchStat = new DepartmentStatistics();
                    if (branchStats.Element("lastUpdate") == null)
                    {
                        continue;
                    }
                    else
                    {
                        branchStat.StatisticsUpdateTime = DateTime.Parse(branchStats.Element("lastUpdate").Value).Round(DateTimeAccuracy.Second);
                    }

                    branchStat.CurrentTime          = DateTime.Parse(branchStats.Element("currentTime").Value).Round(DateTimeAccuracy.Second);
                    branchStat.SystemTime           = DateTime.Now.Round(DateTimeAccuracy.Second);
                    branchStat.LastExecutionTime    = (branchStats.Element("lastExecutionTime") == null) ? (DateTime?)null : DateTime.Parse(branchStats.Element("lastExecutionTime").Value).Round(DateTimeAccuracy.Second);
                    branchStat.LastReceiveTime      = (branchStats.Element("lastReceiveDate") == null) ? (DateTime?)null : DateTime.Parse(branchStats.Element("lastReceiveDate").Value).Round(DateTimeAccuracy.Second);
                    branchStat.LastSendTime         = (branchStats.Element("lastSendDate") == null) ? (DateTime?)null : DateTime.Parse(branchStats.Element("lastSendDate").Value).Round(DateTimeAccuracy.Second);
                    branchStat.PackagesToExecute    = (branchStats.Element("unprocessedPackagesQuantity") == null) ? -1 : Int32.Parse(branchStats.Element("unprocessedPackagesQuantity").Value);
                    branchStat.PackagesToReceive    = (branchStats.Element("unsentPackage") == null) ? -1 : Int32.Parse(branchStats.Element("unsentPackage").Value);
                    branchStat.PackagesToSend       = (branchStats.Element("undeliveredPackagesQuantity") == null) ? -1 : Int32.Parse(branchStats.Element("undeliveredPackagesQuantity").Value);
                    branchStat.LastExecutionMessage = (branchStats.Element("executionMessageTime") == null) ? null : new MessageData()
                    {
                        Time = DateTime.Parse(branchStats.Element("executionMessageTime").Value).Round(DateTimeAccuracy.Second)
                    };
                    branchStat.LastReceiveMessage = (branchStats.Element("receiveMessageTime") == null) ? null : new MessageData()
                    {
                        Time = DateTime.Parse(branchStats.Element("receiveMessageTime").Value).Round(DateTimeAccuracy.Second)
                    };
                    branchStat.LastSendMessage = (branchStats.Element("sentMessageTime") == null) ? null : new MessageData()
                    {
                        Time = DateTime.Parse(branchStats.Element("sentMessageTime").Value).Round(DateTimeAccuracy.Second)
                    };

                    SynchronizeStatisticTime(branchStat);
                    branchStatisticsList.Add(branchId, branchStat);
                }
                return(branchStatisticsList);
            }
        }