Пример #1
0
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int recordCount;

            DataSets.Product product = new DataSets.Product();
            int priceID;

            priceID = Identity.GetId(identity);


            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter;
                tableAdapter            = new DataSets.ProductTableAdapters.ProductsTableAdapter();
                tableAdapter.Connection = connection;
                recordCount             = tableAdapter.FillBy(product.Products, priceID);
            }

            if (recordCount == 0)
            {
                return(GetDeletedDocument(identity));
            }

            return(GetDocument((DataSets.Product.ProductsRow)product.Products[0], lastToken, config));
        }
Пример #2
0
        /* ChangeLog */
        public override int FillChangeLog(out System.Data.DataTable table, NorthwindConfig config, Token lastToken)
        {
            Emails emails;
            int    lastId;
            int    recordCount;

            emails = new Emails();

            lastId = Token.GetId(lastToken);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                CustomerEmailsChangeLogsTableAdapter tableAdapter;
                tableAdapter            = new CustomerEmailsChangeLogsTableAdapter();
                tableAdapter.Connection = connection;
                // fill the Changelog dataset
                if (lastToken.InitRequest)
                {
                    recordCount = tableAdapter.Fill(emails.CustomerEmailsChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, "");
                }
                else
                {
                    recordCount = tableAdapter.Fill(emails.CustomerEmailsChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser);
                }
            }

            table = emails.CustomerEmailsChangeLogs;
            return(recordCount);
        }
Пример #3
0
        public Identity[] GetLastChanges(Token lastToken, NorthwindConfig config, out Token nextToken)
        {
            #region Declarations
            int             recordCount = 0;
            DataTable       dataTable;
            Identity        identity;
            DataRow         row;
            List <Identity> identites = new List <Identity>();
            #endregion

            recordCount = 11;
            nextToken   = lastToken;

            while (recordCount == 11)
            {
                lastToken   = nextToken;
                recordCount = FillChangeLog(out dataTable, config, lastToken);

                for (int i = 0; i < ((recordCount == 11) ? recordCount - 1 : recordCount); i++)
                {
                    //get the next changelog entry
                    row      = dataTable.Rows[i];
                    identity = new Identity(this.EntityName, (string)row[0]);
                    identites.Add(identity);
                    nextToken = new Token(identity, (int)row[1], lastToken.InitRequest);
                }
            }
            return(identites.ToArray());
        }
Пример #4
0
        /* Add */
        public override void Add(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            List<TransactionResult> transactionResult = new List<TransactionResult>();

            // cast the given document to an email document
            // return if fails
            EmailDocument emailDocument = doc as EmailDocument;
            if (emailDocument == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            CustomerEmailsTableAdapter tableAdapter;
            Emails emailsDataset = new Emails();
            Emails.CustomerEmailsRow emailRow = emailsDataset.CustomerEmails.NewCustomerEmailsRow();

            #region fill dataset from document

            try
            {
                if (emailDocument.emailaddress.IsNull)
                    emailRow.SetEmailNull();
                else
                    emailRow.Email = (string)emailDocument.emailaddress.Value;

                emailRow.CreateID = config.SequenceNumber;
                emailRow.CreateUser = config.CrmUser;

                emailRow.ModifyID = config.SequenceNumber;
                emailRow.ModifyUser = config.CrmUser;
            }
            catch (Exception e)
            {
                emailDocument.Id = "";
            #warning Check error message
                result.Add(emailDocument.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                return;
            }

            #endregion

            #region Get the ID of the new row and set it to the document

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                connection.Open();

                tableAdapter = new CustomerEmailsTableAdapter();
                tableAdapter.Connection = connection;

                emailsDataset.CustomerEmails.AddCustomerEmailsRow(emailRow);
                tableAdapter.Update(emailsDataset.CustomerEmails);
                OleDbCommand Cmd = new OleDbCommand("SELECT @@IDENTITY", connection);
                object lastid = Cmd.ExecuteScalar();
                emailDocument.Id = ((int)lastid).ToString();
            }

            #endregion
        }
Пример #5
0
        public void DoWork(IRequest request)
        {
            NorthwindConfig config = new NorthwindConfig();

            config.CurrencyCode = "EUR";
            config.CrmUser      = "******";
            config.Path         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Northwind");

            string   fileName = Path.Combine(config.Path, "Northwind.mdb");
            FileInfo fileInfo = new FileInfo(fileName);
            string   link     = _requestContext.ContractLink + "-";

            DatasetFeedEntry entry = new DatasetFeedEntry();

            entry.Id    = link;
            entry.Title = fileInfo.Name;

            entry.Published = fileInfo.CreationTime;
            entry.Updated   = fileInfo.LastAccessTime;
            entry.Link      = link;

            Feed <DatasetFeedEntry> feed = new Feed <DatasetFeedEntry>();

            feed.Id    = "Available Datasets";
            feed.Title = "Available Datasets";
            feed.Entries.Add(entry);
            request.Response.Feed = feed;
        }
Пример #6
0
        public override List <Identity> GetAll(NorthwindConfig config, string whereExpression, OleDbParameter[] oleDbParameters)
        {
            List <Identity> result      = new List <Identity>();
            int             recordCount = 0;

            DataSets.Order orderDataset = new DataSets.Order();

            // get the first 11 rows of the changelog
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                DataSets.OrderTableAdapters.OrdersTableAdapter tableAdapter;

                tableAdapter = new DataSets.OrderTableAdapters.OrdersTableAdapter();

                tableAdapter.Connection = connection;
#warning TODO: Filter support
                recordCount = tableAdapter.Fill(orderDataset.Orders);
            }

            foreach (DataSets.Order.OrdersRow row in orderDataset.Orders.Rows)
            {
                // use where expression !!
                result.Add(new Identity(this.EntityName, row.OrderID.ToString()));
            }

            return(result);
        }
        public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken)
        {
            #region declarations
            Category category;
            int      lastId;
            int      recordCount;
            #endregion

            category = new Category();

            lastId = Token.GetId(lastToken);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                ChangeLogTableAdapter tableAdapter;
                tableAdapter            = new ChangeLogTableAdapter();
                tableAdapter.Connection = connection;
                // fill the Changelog dataset
                if (lastToken.InitRequest)
                {
                    recordCount = tableAdapter.Fill(category.ChangeLog, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, "");
                }
                else
                {
                    recordCount = tableAdapter.Fill(category.ChangeLog, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser);
                }
            }

            table = category.ChangeLog;
            return(recordCount);
        }
        public override List <Identity> GetAll(NorthwindConfig config, string whereExpression, OleDbParameter[] oleDbParameters)
        {
            #region Declarations
            List <Identity> result      = new List <Identity>();
            int             recordCount = 0;
            Category        dataset     = new Category();
            #endregion

            // get the first 11 rows of the changelog
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                CategoriesTableAdapter tableAdapter;

                tableAdapter = new CategoriesTableAdapter();

                tableAdapter.Connection = connection;

                if (string.IsNullOrEmpty(whereExpression))
                {
                    recordCount = tableAdapter.Fill(dataset.Categories);
                }
                else
                {
                    recordCount = tableAdapter.FillByWhereClause(dataset.Categories, whereExpression, oleDbParameters);
                }
            }

            foreach (Category.CategoriesRow row in dataset.Categories.Rows)
            {
                // use where expression !!
                result.Add(new Identity(this.EntityName, row.CategoryID.ToString()));
            }

            return(result);
        }
Пример #9
0
        /// <summary>
        /// The Add verb inserts an account and all subentities  in the underlying data-store. On success, the
        /// identity of the newly inserted instances will added to the document and all subdocuments.
        /// </summary>
        /// <param name="doc">Document (without ID) containing the data to be stored</param>
        /// <param name="config">The configuration object</param>
        /// <returns>The transactionResult contais status information of the single transaction an also the nesed transactions of the subentities</returns>
        public override void Add(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            #region Declarations
            AccountDocument accDoc;
            AccountDataset.AccountsRow row;
            #endregion

            // cast the given document to an account document
            accDoc = doc as AccountDocument;
            if (accDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            // get the account row from the given document
            row = GetRow(accDoc, config, true);

            // store as customer if the account type is set to customer
            if (CRMSelections.acc_type_Customer == (string)accDoc.customerSupplierFlag.Value)
                StoreCustomer(accDoc, row, config, ref result);

            // store as supplier if the account type is set to supplier
            else if (CRMSelections.acc_type_Supplier == (string)accDoc.customerSupplierFlag.Value)
                StoreSupplier(accDoc, row, config, ref result);

               // for any other account type, set the transactionstatus to not supported
            else
            {
                result.Add(accDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountTypeNotSupported));
            }
        }
            public static string GetConnectionString(SdataContext context)
            {
                NorthwindConfig config = new NorthwindConfig(context.DataSet);

                config.CurrencyCode = "EUR";
                config.Path         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Northwind");
                return(config.ConnectionString);
            }
Пример #11
0
            static ConnStringFactory()
            {
                // TEMPORARY
                NorthwindConfig config = new NorthwindConfig();

                config.CurrencyCode   = "EUR";
                config.Path           = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Northwind");
                stat_connectionString = config.ConnectionString;
            }
Пример #12
0
 public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken)
 {
     table = new DataTable("PriceingList");
     table.Columns.Add("ID", typeof(string));
     table.Columns.Add("Sequence", typeof(int));
     table.Rows.Add(new object[] { Constants.DefaultValues.PriceList.ID, 0 });
     //table.Rows.Add(new object[] { Constants.DefaultValues.PriceListSpecial.ID, 0 });
     return 1;
 }
            public void DoWork(NorthwindConfig config, SyncFeedDigest syncDigestInfo)
            {
                ExecuteDelegate worker            = new ExecuteDelegate(Execute);
                AsyncCallback   completedCallback = new AsyncCallback(ExecuteCompletedCallback);

                AsyncOperation async = AsyncOperationManager.CreateOperation(null);

                // Begin asynchronous method call
                worker.BeginInvoke(config, syncDigestInfo, completedCallback, async);
            }
        public TransformationBase(RequestContext context, SupportedResourceKinds resourceKind)
        {
            _context      = context;
            _datasetLink  = _context.DatasetLink;
            _config       = _context.Config;
            _resourceKind = resourceKind;

            _resourceKindString = _resourceKind.ToString();
            _originApplication  = _datasetLink + _resourceKindString;

            _correlatedResSyncInfoStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_context.SdataContext);
        }
Пример #15
0
        /// <summary>
        /// dispatch the transaction between Add, Update,Delete
        /// </summary>
        /// <param name="doc">the data document</param>
        /// <param name="config">the configuratio Object</param>
        /// <returns>returns a transaction result for the transaction and all nested ones</returns>
        private void ExecuteTransaction(Document doc, NorthwindConfig config, ref List <TransactionResult> result)
        {
            if (doc.LogState == LogState.Created)
            {
                Add(doc, config, ref result);
            }

            else if (doc.LogState == LogState.Deleted)
            {
                Delete(doc, config, ref result);
            }

            else
            {
                Update(doc, config, ref result);
            }
        }
Пример #16
0
        public ProductPriceDocument[] GetProductPrices(string[] productIds, NorthwindConfig config)
        {
            List <ProductPriceDocument> items = new List <ProductPriceDocument>();
            DataSet          dataSet          = new DataSet();
            OleDbDataAdapter dataAdapter;

            string whereClause = "where";

            List <OleDbParameter> oleDbParameters = new List <OleDbParameter>();

            foreach (string productId in productIds)
            {
                whereClause += " ProductID=? OR";
                string         name       = "p" + oleDbParameters.Count.ToString();
                OleDbParameter oleDbParam = new OleDbParameter(name, Convert.ToInt32(productId));
                oleDbParameters.Add(oleDbParam);
            }

            whereClause = whereClause.Remove(whereClause.Length - 3, 3);

            string sqlQuery = "Select * from Products " + whereClause;

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                dataAdapter = new OleDbDataAdapter(sqlQuery, connection);
                dataAdapter.SelectCommand.Parameters.AddRange(oleDbParameters.ToArray());
                if (dataAdapter.Fill(dataSet, "Products") == 0)
                {
                    // no products found
                }
                else
                {
                    foreach (DataRow row in dataSet.Tables["Products"].Rows)
                    {
                        ProductPriceDocument productPrice = new ProductPriceDocument();
                        productPrice.ProductId = Convert.ToInt32(row["ProductID"]);
                        productPrice.UnitPrice = Convert.ToDecimal(row["UnitPrice"]);

                        items.Add(productPrice);
                    }
                }
            }

            return(items.ToArray());
        }
Пример #17
0
        private Document GetDocument(Emails.CustomerEmailsRow row, Token lastToken, NorthwindConfig config)
        {
            EmailDocument doc;
            string        id;

            id = row.ID.ToString();

            doc    = new EmailDocument();
            doc.Id = id;

            if (lastToken.InitRequest)
            {
                doc.LogState = LogState.Created;
            }

            else if (row.IsCreateIDNull() || row.IsModifyIDNull() ||
                     row.IsCreateUserNull() || row.IsModifyUserNull())
            {
                doc.LogState = LogState.Created;
            }

            else if ((row.CreateID > lastToken.SequenceNumber) &&
                     (row.CreateUser != config.CrmUser))
            {
                doc.LogState = LogState.Created;
            }

            else if ((row.CreateID == lastToken.SequenceNumber) &&
                     (row.CreateUser != config.CrmUser) &&
                     (id.CompareTo(lastToken.Id.Id) > 0))
            {
                doc.LogState = LogState.Created;
            }
            else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser))
            {
                doc.LogState = LogState.Updated;
            }

            doc.emailaddress.Value = row.IsEmailNull() ? null : row.Email;

            doc.type.Value = Constants.DefaultValues.Email.Type;

            return(doc);
        }
Пример #18
0
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int recordCount;

            DataSets.Order order = new DataSets.Order();
            CalculatedOrdersTableAdapter tableAdapter;

            tableAdapter = new CalculatedOrdersTableAdapter();
            CalculatedOrderDetailsTableAdapter detailTableAdapter;

            detailTableAdapter = new CalculatedOrderDetailsTableAdapter();
            DeletedOrderDetailsTableAdapter deletedDetailTableAdapter;

            deletedDetailTableAdapter = new DeletedOrderDetailsTableAdapter();


            int id;

            id = Identity.GetId(identity);



            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                tableAdapter.Connection = connection;
                recordCount             = tableAdapter.FillBy(order.CalculatedOrders, id, id);
                if (recordCount == 0)
                {
                    return(GetDeletedDocument(identity));
                }

                detailTableAdapter.Connection = connection;
                detailTableAdapter.FillBy(order.CalculatedOrderDetails, id);

                deletedDetailTableAdapter.Connection = connection;
                deletedDetailTableAdapter.Fill(order.DeletedOrderDetails, id.ToString(), lastToken.SequenceNumber, config.CrmUser);
            }


            return(GetDocument((DataSets.Order.CalculatedOrdersRow)order.CalculatedOrders[0],
                               order.CalculatedOrderDetails,
                               order.DeletedOrderDetails,
                               lastToken, config));
        }
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int      recordCount;
            Category category = new Category();

            int id = Identity.GetId(identity);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                CategoriesTableAdapter tableAdapter;
                tableAdapter            = new CategoriesTableAdapter();
                tableAdapter.Connection = connection;
                recordCount             = tableAdapter.FillBy(category.Categories, id);
            }

            if (recordCount == 0)
            {
                return(GetDeletedDocument(identity));
            }

            return(GetDocument((Category.CategoriesRow)category.Categories[0], lastToken, config));
        }
Пример #20
0
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            PricingListsDocument doc = new PricingListsDocument();
            if (identity.Id.Equals(Constants.DefaultValues.PriceList.ID))
            {
                doc.Id = Constants.DefaultValues.PriceList.ID;
                doc.description.Value = Constants.DefaultValues.PriceList.Name;
                doc.name.Value = Constants.DefaultValues.PriceList.Name;
            }
            else
            {
                doc.Id = Constants.DefaultValues.PriceListSpecial.ID;
                doc.description.Value = Constants.DefaultValues.PriceListSpecial.Name;
                doc.name.Value = Constants.DefaultValues.PriceListSpecial.Name;
            }
            doc.active.Value = "Y"; //Constants.DefaultValues.Active;
            #warning should be boolean, but as workaround this will filled with "Y"
            doc.erpdefaultvalue.Value = "Y";
            doc.defaultvalue.Value = false;

            return doc;
        }
Пример #21
0
        /* Get */
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int    recordCount;
            Emails emails = new Emails();

            int id = Identity.GetId(identity);

            //string strId = Convert.ToString(id);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                CustomerEmailsTableAdapter tableAdapter;
                tableAdapter            = new CustomerEmailsTableAdapter();
                tableAdapter.Connection = connection;
                recordCount             = tableAdapter.FillBy(emails.CustomerEmails, id);
            }

            if (recordCount == 0)
            {
                return(GetDeletedDocument(identity));
            }

            return(GetDocument((Emails.CustomerEmailsRow)emails.CustomerEmails[0], lastToken, config));
        }
Пример #22
0
 /// <summary>
 /// returns a filled document by the identity
 /// </summary>
 /// <param name="identity">the identity</param>
 /// <param name="lastToken">the last token to set the logstate</param>
 /// <param name="config">the configuration object</param>
 /// <returns>returns a filled document by the identity</returns>
 public abstract Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config);
Пример #23
0
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int recordCount;
            DataSets.Product product = new DataSets.Product();
            int uomFamilyId;

            uomFamilyId = Identity.GetId(identity);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                Sage.Integration.Northwind.Application.Entities.Product.DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter;
                tableAdapter = new Sage.Integration.Northwind.Application.Entities.Product.DataSets.ProductTableAdapters.ProductsTableAdapter();
                tableAdapter.Connection = connection;
                recordCount = tableAdapter.FillBy(product.Products, uomFamilyId);
            }

            if (recordCount == 0)
                return GetDeletedDocument(identity);

            return GetUOMFamilyDocument((DataSets.Product.ProductsRow)product.Products[0], lastToken, config);
        }
Пример #24
0
        /* Get */
        public override List<Identity> GetAll(NorthwindConfig config, string whereExpression, OleDbParameter[] oleDbParameters)
        {
            List<Identity> result = new List<Identity>();
            int recordCount = 0;
            DataSets.Product productsDataset = new DataSets.Product();

            // get the first 11 rows of the changelog
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter;

                tableAdapter = new DataSets.ProductTableAdapters.ProductsTableAdapter();

                tableAdapter.Connection = connection;

                if (string.IsNullOrEmpty(whereExpression))
                    recordCount = tableAdapter.Fill(productsDataset.Products);
                else
                    recordCount = tableAdapter.FillByWhereClause(productsDataset.Products, whereExpression, oleDbParameters);
            }

            foreach (DataSets.Product.ProductsRow row in productsDataset.Products.Rows)
            {
                // use where expression !!
                result.Add(new Identity(this.EntityName, row.ProductID.ToString()));
            }

            return result;
        }
Пример #25
0
        public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken)
        {
            #region declarations
            DataSets.Order order;
            int lastId;
            int recordCount;
            #endregion

            order = new DataSets.Order();

            lastId = Token.GetId(lastToken);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {

                ChangeLogsTableAdapter tableAdapter;
                tableAdapter = new ChangeLogsTableAdapter();
                tableAdapter.Connection = connection;// fill the Changelog dataset

                if (lastToken.InitRequest)
                    recordCount = tableAdapter.Fill(order.ChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, "");
                else
                    recordCount = tableAdapter.Fill(order.ChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser);
            }

            table = order.ChangeLogs;
            return recordCount;
        }
Пример #26
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="config"></param>
 /// <returns></returns>
 public virtual void Add(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
 {
     result.Add(doc.GetOperationNotImplementedTransactionResult());
 }
Пример #27
0
        private UnitOfMeasureFamilyDocument GetUOMFamilyDocument(Sage.Integration.Northwind.Application.Entities.Product.DataSets.Product.ProductsRow productRow, Token lastToken, NorthwindConfig config)
        {
            #region Declarations
            UnitOfMeasureFamilyDocument uomDoc;
            string identity;
            #endregion

            identity = productRow.ProductID.ToString();

            // create Account Doc
            uomDoc = new UnitOfMeasureFamilyDocument();
            uomDoc.Id = identity;

            if (lastToken.InitRequest)
                uomDoc.LogState = LogState.Created;

            else if (productRow.IsCreateIDNull() || productRow.IsModifyIDNull()
                || productRow.IsCreateUserNull() || productRow.IsModifyUserNull())
                uomDoc.LogState = LogState.Created;

            else if ((productRow.CreateID > lastToken.SequenceNumber)
                   && (productRow.CreateUser != config.CrmUser))
                uomDoc.LogState = LogState.Created;

            else if ((productRow.CreateID == lastToken.SequenceNumber)
               && (productRow.CreateUser != config.CrmUser)
                && (identity.CompareTo(lastToken.Id.Id) > 0))
                uomDoc.LogState = LogState.Created;
            else if ((productRow.ModifyID >= lastToken.SequenceNumber) && (productRow.ModifyUser != config.CrmUser))
                uomDoc.LogState = LogState.Updated;

            uomDoc.active.Value = Constants.DefaultValues.Active;
            uomDoc.defaultvalue.Value = true;

            uomDoc.name.Value = productRow.IsQuantityPerUnitNull() ? null : productRow.QuantityPerUnit.ToString(); ;
            uomDoc.description.Value = uomDoc.name.Value;
            return uomDoc;
        }
Пример #28
0
        /// <summary>
        /// get a northwind account row, which is a union of customers and suppliers,
        /// from the given account document and set the transaction status on the documents
        /// </summary>
        /// <param name="accDoc">the crm Account document</param>
        /// <param name="config"></param>
        /// <returns>a filled northwind account row</returns>
        private AccountDataset.AccountsRow GetRow(AccountDocument accDoc, NorthwindConfig config, bool newAccount)
        {
            #region Declarations
            AccountDataset accDataset;
            AccountDataset.AccountsRow result;
            Address address;
            Phone phone;
            ContactName personName;
            int subentities = 4;
            #endregion

            accDataset = new AccountDataset();
            result = accDataset.Accounts.NewAccountsRow();

            // get the account name from the document
            if (!accDoc.name.IsNull)
                result.CompanyName =  (string)accDoc.name.Value;

            if (newAccount)
            {
                // set create user and id
                result.CreateID = config.SequenceNumber;
                result.CreateUser = config.CrmUser;
            }

            // set modify user and id
            result.ModifyID = config.SequenceNumber;
            result.ModifyUser = config.CrmUser;

            #region Address

            // go throuh all addresses to find the business address,
            // the rest of the adresses will ignored
            foreach (AddressDocument adrDoc in accDoc.addresses)
            {
                // check if the Address is from the supported type
                if ((adrDoc.primaryaddress.IsNull) ||
                    (!adrDoc.primaryaddress.Value.ToString().Equals("True", StringComparison.InvariantCultureIgnoreCase)))
                {
                    // set the transactionsstatus to none to remove this status from the result
                    adrDoc.ClearTransactionStatus();
                    continue;
                }

                // the first correct address found

                // get a new Address Object to convert beween the systems
                address = new Address();

                // fill the address object with the crm data
                address.SetCrmAdresses(adrDoc.address1, adrDoc.address2, adrDoc.address3, adrDoc.address4);

                // set the Northwind address
                result.Address = address.NorthwindAddress;

                // get the city from the Address document
                if (!adrDoc.City.IsNull)
                    result.City = (string)adrDoc.City.Value;

                // get the state from the Address document
                if (!adrDoc.state.IsNull)
                    result.Region = (string)adrDoc.state.Value;

                // get the state from the Address document
                if (!adrDoc.postcode.IsNull)
                    result.PostalCode = (string)adrDoc.postcode.Value;

                // get the country from the Address document
                if (!adrDoc.country.IsNull)
                    result.Country = (string)adrDoc.country.Value;

                // stop searching
                subentities--;
                adrDoc.SetTransactionStatus(TransactionStatus.Success);
                break;

            }
            #endregion

            #region Contact
            // go throuh all people to find the billing person,
            // the rest of the people will ignored
            foreach (PersonDocument persDoc in accDoc.people)
            {
                // check if the person is from the supported type
                if ((persDoc.primaryperson.IsNull) || (!persDoc.primaryperson.Value.ToString().Equals("True",StringComparison.InvariantCultureIgnoreCase)))
                {
                    // set the transactionsstatus to none to remove this status from the result
                    persDoc.ClearTransactionStatus();
                    continue;
                }
                // the first correct people found

                // get the Title from the Person document
                if (!persDoc.title.IsNull)
                    result.ContactTitle = (string)persDoc.title.Value;

                // get a new ContactName Object to convert beween the systems
                personName = new ContactName();

                // fill the ContactName object with the crm data
                personName.SetCrmContact(persDoc.salutation,
                    persDoc.firstname,
                    persDoc.middlename,
                    persDoc.lastname,
                    persDoc.suffix);

                // set the Northwind ContactName
                result.ContactName = personName.NorthwindContacName;

                // stop searching
                subentities--;
                persDoc.SetTransactionStatus(TransactionStatus.Success);
                break;

            }
            #endregion

            #region Phones
            // go throuh all phones to find phone and fax,
            // the rest of the phones  will ignored

            foreach (PhoneDocument phoneDoc in accDoc.phones)
            {
                // check if the phone is from the supported type
                if (phoneDoc.type.Value != null)
                {
                    if ((phoneDoc.type.IsNull) ||
                        !((phoneDoc.type.Value.ToString() == CRMSelections.Link_PersPhon_Business)))
                    {
                        // set the transactionsstatus to none to remove this status from the result
                        if (!((phoneDoc.type.Value.ToString() == CRMSelections.Link_PersPhon_Fax)))
                            phoneDoc.ClearTransactionStatus();
                        continue;
                    }
                }

                // get a new phone Object to convert beween the systems
                phone = new Phone();

                // fill the ContactName object with the crm data
                phone.SetCrmPhone(phoneDoc.countrycode, phoneDoc.areacode, phoneDoc.number);

                // set the northwind phone
                result.Phone = phone.NorthwindPhone;

                // on new pone entries store the phonetype postfix in the id
                // to fill it up with the Account id later
                if ((phoneDoc.Id == null) || (phoneDoc.Id == ""))
                    phoneDoc.Id = Constants.PhoneIdPostfix;
                subentities--;
                phoneDoc.SetTransactionStatus(TransactionStatus.Success);
                break;
            }

            foreach (PhoneDocument phoneDoc in accDoc.phones)
            {
                // check if the phone is from the supported type
                if (phoneDoc.type.Value != null)
                {
                    if ((phoneDoc.type.IsNull) ||
                        !((phoneDoc.type.Value.ToString() == CRMSelections.Link_PersPhon_Fax)))
                    {
                        // set the transactionsstatus to none to remove this status from the result
                        if (!((phoneDoc.type.Value.ToString() == CRMSelections.Link_PersPhon_Business)))
                            phoneDoc.ClearTransactionStatus();
                        continue;
                    }
                }

                // get a new phone Object to convert beween the systems
                phone = new Phone();

                // fill the ContactName object with the crm data
                phone.SetCrmPhone(phoneDoc.countrycode, phoneDoc.areacode, phoneDoc.number);

                // set the northwind fax
                result.Fax = phone.NorthwindPhone;

                // on new pone entries store the phonetype postfix in the id
                // to fill it up with the Account id later
                if ((phoneDoc.Id == null) || (phoneDoc.Id == ""))
                    phoneDoc.Id = Constants.FaxIdPostfix;

                subentities--;
                phoneDoc.SetTransactionStatus(TransactionStatus.Success);
                break;
            }
            #endregion

            if (newAccount && (subentities > 0))
            {
                result.CreateUser = "******";
                result.ModifyUser = "******";
            }

            //return the row
            return result;
        }
        public override void Update(Document doc, NorthwindConfig config, ref List <TransactionResult> result)
        {
            List <TransactionResult> transactionResult = new List <TransactionResult>();
            ProductFamilyDocument    productFamilyDoc  = doc as ProductFamilyDocument;

            #region check input values
            if (productFamilyDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            // check id
            #endregion

            DataSets.CategoryTableAdapters.CategoriesTableAdapter tableAdapter;


            DataSets.Category category = new DataSets.Category();
            DataSets.Category.CategoriesRow row;
            tableAdapter = new DataSets.CategoryTableAdapters.CategoriesTableAdapter();
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                connection.Open();
                tableAdapter.Connection = connection;
                int recordCount = tableAdapter.FillBy(category.Categories, Convert.ToInt32(productFamilyDoc.Id));
                if (recordCount == 0)
                {
                    doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, "Category does not exists");
                    return;
                }
                row = (Category.CategoriesRow)category.Categories.Rows[0];

                try
                {
                    if (!productFamilyDoc.name.NotSet)
                    {
                        if (productFamilyDoc.name.IsNull)
                        {
                            row.SetCategoryNameNull();
                        }
                        else
                        {
                            row.CategoryName = (string)productFamilyDoc.name.Value;
                        }
                    }

                    if (!productFamilyDoc.description.NotSet)
                    {
                        if (productFamilyDoc.description.IsNull)
                        {
                            row.SetDescriptionNull();
                        }
                        else
                        {
                            row.Description = (string)productFamilyDoc.description.Value;
                        }
                    }

                    row.ModifyID   = config.SequenceNumber;
                    row.ModifyUser = config.CrmUser;
                }
                catch (Exception e)
                {
                    productFamilyDoc.Id = "";
#warning Check error message
                    result.Add(productFamilyDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                    return;
                }

                tableAdapter            = new DataSets.CategoryTableAdapters.CategoriesTableAdapter();
                tableAdapter.Connection = connection;

                tableAdapter.Update(category.Categories);

                result.Add(doc.SetTransactionStatus(TransactionStatus.Success));
            }
        }
        public override void Add(Document doc, NorthwindConfig config, ref List <TransactionResult> result)
        {
            List <TransactionResult> transactionResult = new List <TransactionResult>();
            ProductFamilyDocument    productFamilyDoc  = doc as ProductFamilyDocument;

            #region check input values
            if (productFamilyDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }
            #endregion

            DataSets.CategoryTableAdapters.CategoriesTableAdapter tableAdapter;


            DataSets.Category category          = new DataSets.Category();
            DataSets.Category.CategoriesRow row = category.Categories.NewCategoriesRow();


            #region fill dataset from document
            try
            {
                if (productFamilyDoc.name.IsNull)
                {
                    row.SetCategoryNameNull();
                }
                else
                {
                    row.CategoryName = (string)productFamilyDoc.name.Value;
                }

                if (productFamilyDoc.description.IsNull)
                {
                    row.SetDescriptionNull();
                }
                else
                {
                    row.Description = (string)productFamilyDoc.description.Value;
                }


                row.CreateID   = config.SequenceNumber;
                row.CreateUser = config.CrmUser;

                row.ModifyID   = config.SequenceNumber;
                row.ModifyUser = config.CrmUser;
            }
            catch (Exception e)
            {
                productFamilyDoc.Id = "";
#warning Check error message
                result.Add(productFamilyDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                return;
            }

            #endregion

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                connection.Open();


                tableAdapter            = new DataSets.CategoryTableAdapters.CategoriesTableAdapter();
                tableAdapter.Connection = connection;


                category.Categories.AddCategoriesRow(row);
                tableAdapter.Update(category.Categories);
                OleDbCommand Cmd    = new OleDbCommand("SELECT @@IDENTITY", connection);
                object       lastid = Cmd.ExecuteScalar();
                productFamilyDoc.Id = ((int)lastid).ToString();
            }
            result.Add(doc.SetTransactionStatus(TransactionStatus.Success));
        }
Пример #31
0
        public Identity[] GetLastChanges(Token lastToken, NorthwindConfig config, out Token nextToken)
        {
            #region Declarations
            int recordCount = 0;
            DataTable dataTable;
            Identity identity;
            DataRow row;
            List<Identity> identites = new List<Identity>();
            #endregion

            recordCount = 11;
            nextToken = lastToken;

            while (recordCount == 11)
            {
                lastToken = nextToken;
                recordCount = FillChangeLog(out dataTable, config, lastToken);

                for (int i = 0; i < ((recordCount == 11) ? recordCount - 1 : recordCount); i++)
                {
                    //get the next changelog entry
                    row = dataTable.Rows[i];
                    identity = new Identity(this.EntityName, (string)row[0]);
                    identites.Add(identity);
                    nextToken = new Token(identity, (int)row[1], lastToken.InitRequest);
                }
            }
            return identites.ToArray();
        }
Пример #32
0
        /// <summary>
        /// dispatch the transaction between Add, Update,Delete
        /// </summary>
        /// <param name="doc">the data document</param>
        /// <param name="config">the configuratio Object</param>
        /// <returns>returns a transaction result for the transaction and all nested ones</returns>
        private void ExecuteTransaction(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            if (doc.LogState == LogState.Created)
                Add(doc, config, ref result);

            else if (doc.LogState == LogState.Deleted)
                Delete(doc, config, ref result);

            else
                Update(doc, config, ref result);
        }
Пример #33
0
        public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config)
        {
            int recordCount;
            DataSets.Order order = new DataSets.Order();
            CalculatedOrdersTableAdapter tableAdapter;
            tableAdapter = new CalculatedOrdersTableAdapter();
            CalculatedOrderDetailsTableAdapter detailTableAdapter;
            detailTableAdapter = new CalculatedOrderDetailsTableAdapter();
            DeletedOrderDetailsTableAdapter deletedDetailTableAdapter;
            deletedDetailTableAdapter = new DeletedOrderDetailsTableAdapter();

            int id;

            id = Identity.GetId(identity);

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                tableAdapter.Connection = connection;
                recordCount = tableAdapter.FillBy(order.CalculatedOrders, id);
                if (recordCount == 0)
                    return GetDeletedDocument(identity);

                detailTableAdapter.Connection = connection;
                detailTableAdapter.FillBy(order.CalculatedOrderDetails, id);

                deletedDetailTableAdapter.Connection = connection;
                deletedDetailTableAdapter.Fill(order.DeletedOrderDetails, id.ToString(), lastToken.SequenceNumber, config.CrmUser);
            }

            return GetDocument((DataSets.Order.CalculatedOrdersRow)order.CalculatedOrders[0],
                order.CalculatedOrderDetails,
                order.DeletedOrderDetails,
                lastToken, config);
        }
Пример #34
0
        public override void Add(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            TransactionResult tmpTransactionResult;
            List<TransactionResult> transactionResult = new List<TransactionResult>();
            OrderDocument orderDoc = doc as OrderDocument;

            #region check input values
            if (orderDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            string customerID;
            if (orderDoc.accountid.IsNull)
            {

                result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountIDMadatory));
                return;
            }

            customerID = (string)orderDoc.accountid.Value;
            if (!customerID.StartsWith(Constants.CustomerIdPrefix))
            {
                result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AddOrdersForCustomersOnly));
                return;
            }
            #endregion

            DataSets.OrderTableAdapters.OrdersTableAdapter tableAdapter;
            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter;

            DataSets.Order order = new DataSets.Order();

            DataSets.Order.OrdersRow newOrder = order.Orders.NewOrdersRow();

            customerID = customerID.Substring(Constants.CustomerIdPrefix.Length);
            newOrder.CustomerID = customerID;

            #region get Company Name
            DataSet dataSet = new DataSet();
            OleDbDataAdapter dataAdapter;
            string sqlQuery = "Select CompanyName from Customers where CustomerID = '" + customerID + "'";

            try
            {
                using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
                {
                    dataAdapter = new OleDbDataAdapter(sqlQuery, connection);
                    if (dataAdapter.Fill(dataSet, "Customers") == 0)
                    {
                        result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountNotFound));
                        return;
                    }
                    newOrder.ShipName = dataSet.Tables[0].Rows[0][0].ToString();
                }
            }
            catch (Exception e)
            {
                orderDoc.Id = "";
                throw;
            }

            #endregion

            #region get Sels rep
            if (orderDoc.salesrepr.IsNull)
                newOrder.SetEmployeeIDNull();
            else
            {
                try
                {
                    newOrder.EmployeeID = int.Parse((string)orderDoc.salesrepr.Value);
                }
                catch (Exception)
                {
                    newOrder.SetEmployeeIDNull();
                }
                if (newOrder.IsEmployeeIDNull())
                {
                    try
                    {
                        dataSet = new DataSet();
                        sqlQuery = "SELECT Employees.EmployeeID FROM Employees where Employees.FirstName + ' ' + Employees.LastName = ? ";
                        using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
                        {
                            dataAdapter = new OleDbDataAdapter(sqlQuery, connection);
                            OleDbParameter parameter = new OleDbParameter("Name", (string)orderDoc.salesrepr.Value);
                            dataAdapter.SelectCommand.Parameters.Add(parameter);
                            if (dataAdapter.Fill(dataSet, "Employees") > 0)
                                newOrder.EmployeeID = Convert.ToInt32(dataSet.Tables[0].Rows[0][0]);
                            else
                                newOrder.EmployeeID = 1;
                        }
                    }
                    catch (Exception e)
                    {
                        orderDoc.Id = "";
                        throw;
                    }

                }
            }
            #endregion

            #region fill dataset from document
            try
            {

                if (orderDoc.opened.IsNull)
                    newOrder.SetOrderDateNull();
                else
                    newOrder.OrderDate = (DateTime)orderDoc.opened.Value;

                if (orderDoc.deliverydate.IsNull)
                    newOrder.SetRequiredDateNull();
                else
                    newOrder.RequiredDate = (DateTime)orderDoc.deliverydate.Value;

                if (orderDoc.shippedvia.IsNull)
                    newOrder.SetShipViaNull();
                else
                    newOrder.ShipVia = (int)orderDoc.shippedvia.Value;

                if (orderDoc.shipaddress.IsNull)
                {
                    newOrder.SetShipAddressNull();
                    newOrder.SetShipCityNull();
                    newOrder.SetShipCountryNull();
                    newOrder.SetShipPostalCodeNull();
                }
                else
                {
                    OrderAddress orderAddress = new OrderAddress();
                    orderAddress.CrmOrderAddress = (string)orderDoc.shipaddress.Value;
                    newOrder.ShipAddress = (string)orderAddress.NorthwindAddress;
                    newOrder.ShipCity = (string)orderAddress.NorthwindCity;
                    newOrder.ShipPostalCode = (string)orderAddress.NorthwindZipCode;
                    newOrder.ShipCountry = (string)orderAddress.NorthwindCountry;

                }

                if (orderDoc.freight.IsNull)
                    newOrder.Freight = (decimal)0;
                else
                    newOrder.Freight = (decimal)orderDoc.freight.Value;

                newOrder.CreateUser = config.CrmUser;
                newOrder.ModifyUser = config.CrmUser;
                newOrder.CreateID = config.SequenceNumber;
                newOrder.ModifyID = config.SequenceNumber;
            }
            catch (Exception e)
            {
                orderDoc.Id = "";
            #warning Check error message
                result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                return;
            }

            #endregion

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                OleDbTransaction transaction = null;
                try
                {
                    connection.Open();
                    transaction = connection.BeginTransaction();

                    tableAdapter = new DataSets.OrderTableAdapters.OrdersTableAdapter();
                    tableAdapter.Connection = connection;
                    detailsTableAdapter = new DataSets.OrderTableAdapters.Order_DetailsTableAdapter();
                    detailsTableAdapter.Connection = connection;

                    tableAdapter.SetTransaction(transaction);
                    detailsTableAdapter.SetTransaction(transaction);
                    order.Orders.AddOrdersRow(newOrder);
                    tableAdapter.Update(order.Orders);
                    OleDbCommand Cmd = new OleDbCommand("SELECT @@IDENTITY", connection);
                    Cmd.Transaction = transaction;
                    object lastid = Cmd.ExecuteScalar();
                    orderDoc.Id = ((int)lastid).ToString();
                    // add line Items

                    DataSets.Order.Order_DetailsRow detailRow;

                    Hashtable addedProductsProducts;
                    addedProductsProducts = new Hashtable();
                    int productID;

                    foreach (LineItemDocument lineItemDoc in orderDoc.orderitems)
                    {
                        try
                        {
                            try
                            {
                                productID = (int)lineItemDoc.productid.Value;
                            }
                            catch (Exception)
                            {
            #warning only to test unsupported products
                                productID = 0;
                            }
                            if (addedProductsProducts.Contains(productID))
                            {
                                transaction.Rollback();
                                orderDoc.Id = "";
                                result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_OrderContainsProductTwice));
                                return;
                            }
                            addedProductsProducts.Add(productID, productID);
                            detailRow = order.Order_Details.NewOrder_DetailsRow();
                            lineItemDoc.Id = orderDoc.Id + "-" + productID.ToString();
                            detailRow.OrderID = Convert.ToInt32(orderDoc.Id);
                            detailRow.ProductID = productID;
                            detailRow.Quantity = Convert.ToInt16(lineItemDoc.quantity.Value);
                            detailRow.UnitPrice = (Decimal)lineItemDoc.listprice.Value;

                            if ((lineItemDoc.discountsum.IsNull) || (detailRow.Quantity == 0) || (detailRow.UnitPrice == 0))
                            {
                                detailRow.Discount = (float)0;
                            }
                            else
                            {
                                // discountPC = discountsum / qunatity * listprice
                                //detailRow.Discount = Convert.ToSingle((decimal)lineItemDoc.discountsum.Value / ((decimal)detailRow.Quantity * detailRow.UnitPrice));
                                float discount = Convert.ToSingle((decimal)lineItemDoc.discountsum.Value / (detailRow.UnitPrice));
                                if (discount > 1)
                                    discount = 0;
                                detailRow.Discount = discount;
                            }

                            detailRow.CreateUser = config.CrmUser;
                            detailRow.ModifyUser = config.CrmUser;
                            detailRow.CreateID = config.SequenceNumber;
                            detailRow.ModifyID = config.SequenceNumber;
                        }
                            // this error occours in case of invalid data types
                        catch (Exception e)
                        {
                            transaction.Rollback();
                            orderDoc.Id = "";
                            result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.Message));
                            return;
                        }
                        order.Order_Details.AddOrder_DetailsRow(detailRow);
                        lineItemDoc.SetTransactionStatus(TransactionStatus.Success);
                    }

                    // here could an error ouucour in case on broken database connection
                    // or of same invalid constraints which are unhandled before
                    try
                    {
                        detailsTableAdapter.Update(order.Order_Details);
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        orderDoc.Id = "";
                        result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.Message));
                        return;
                    }
                    transaction.Commit();

                    orderDoc.GetTransactionResult(ref result);

                }
                catch (Exception transactionException)
                {
                    if (transaction != null)
                        transaction.Rollback();

                    orderDoc.Id = "";
                    throw;

                }

            }
        }
Пример #35
0
        private Document GetDocumentLineItem(DataSets.Order.CalculatedOrderDetailsRow row, Token lastToken, NorthwindConfig config)
        {
            #region Declarations
            LineItemDocument doc;
            string id;
            decimal discountPercentage;
            #endregion

            id = row.OrderID.ToString() + "-" + row.ProductID.ToString();

            doc = new LineItemDocument();
            doc.Id = id;

            if (lastToken.InitRequest)
                doc.LogState = LogState.Created;
            else if ((row.CreateID >= lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser))
                doc.LogState = LogState.Created;
            else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser))
                doc.LogState = LogState.Updated;

            doc.productid.Value = row.ProductID;
            //doc.orderquouteid.Value = row.OrderID;
            doc.uomid.Value = row.ProductID;
            doc.quantity.Value = row.IsQuantityNull() ? Convert.ToInt16(0) : row.Quantity;
            doc.listprice.Value = row.IsUnitPriceNull() ? new decimal(0) : row.UnitPrice;
            discountPercentage = row.IsDiscountNull() ? (decimal)0 : Convert.ToDecimal(row.Discount);

            //doc.discountsum.Value = (decimal)(short)doc.Quantity.Value * (decimal)doc.ListPrice.Value * discountPercentage;
            doc.discountsum.Value = (decimal)doc.listprice.Value * discountPercentage;
            doc.quotedprice.Value = (decimal)doc.listprice.Value * (1 - discountPercentage);

            //doc.quotedprice.Value = row.IsQuotePriceNull() ? new decimal(0) : Convert.ToDecimal(row.QuotePrice);

            doc.taxrate.Value = "0";
            doc.tax.Value = new decimal(0);
            doc.quotedpricetotal.Value = Convert.ToDecimal(doc.quantity.Value) * Convert.ToDecimal(doc.quotedprice.Value);
            return doc;
        }
Пример #36
0
        public override List<Identity> GetAll(NorthwindConfig config, string whereExpression, OleDbParameter[] oleDbParameters)
        {
            List<Identity> result = new List<Identity>();
            int recordCount = 0;
            DataSets.Order orderDataset = new DataSets.Order();

            // get the first 11 rows of the changelog
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                DataSets.OrderTableAdapters.OrdersTableAdapter tableAdapter;

                tableAdapter = new DataSets.OrderTableAdapters.OrdersTableAdapter();

                tableAdapter.Connection = connection;
            #warning TODO: Filter support
                recordCount = tableAdapter.Fill(orderDataset.Orders);

            }

            foreach (DataSets.Order.OrdersRow row in orderDataset.Orders.Rows)
            {
                // use where expression !!
                result.Add(new Identity(this.EntityName, row.OrderID.ToString()));
            }

            return result;
        }
Пример #37
0
        protected virtual int Fill(string sqlQuery, List<OleDbParameter> oleDbParameterList, NorthwindConfig config, out DataSet dataSet)
        {
            // declarations
            OleDbDataAdapter dataAdapter;
            int nOfRows;

            // initializations
            dataSet = null;
            nOfRows = 0;
            dataSet = new DataSet();

            // get the data base records using a table adapter.
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                dataAdapter = new OleDbDataAdapter(sqlQuery, connection);
                dataAdapter.SelectCommand.Parameters.AddRange(oleDbParameterList.ToArray());
                nOfRows = dataAdapter.Fill(dataSet, _reportName);
            }

            return nOfRows;
        }
Пример #38
0
        private Document GetDocument(DataSets.Order.CalculatedOrdersRow row,
            DataSets.Order.CalculatedOrderDetailsDataTable detailDataTable,
            DataSets.Order.DeletedOrderDetailsDataTable deletedOrderDetailsDataTable,
            Token lastToken, NorthwindConfig config)
        {
            #region Declarations
            OrderDocument doc;
            string id;
            LogState logState = LogState.Updated;
            Document lineItemDoc;
            CountryCodes countryCodes = new CountryCodes();
            #endregion

            id = row.OrderID.ToString();

            if (lastToken.InitRequest)
                logState = LogState.Created;

            else if (row.IsCreateIDNull() || row.IsModifyIDNull()
                || row.IsCreateUserNull() || row.IsModifyUserNull())
                logState = LogState.Created;

            else if ((row.CreateID > lastToken.SequenceNumber)
                   && (row.CreateUser != config.CrmUser))
                logState = LogState.Created;

            else if ((row.CreateID == lastToken.SequenceNumber)
                && (row.CreateUser != config.CrmUser)
                && (id.CompareTo(lastToken.Id.Id) > 0))
                logState = LogState.Created;

            else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser))
                logState = LogState.Updated;

            doc = new OrderDocument();
            doc.Id = id;
            doc.LogState = logState;

            doc.currency.Value = config.CurrencyCode;
            doc.pricinglistid.Value = Constants.DefaultValues.PriceList.ID;
            doc.reference.Value = id;

            if (row.IsCustomerIDNull())
                doc.accountid.Value = null;
            else
                doc.accountid.Value = Constants.CustomerIdPrefix + row.CustomerID;

            if (row.IsOrderDateNull())
                doc.opened.Value = null;
            else
                doc.opened.Value = row.OrderDate;

            if (row.IsShippedDateNull())
                doc.status.Value = Constants.OrderStatus.Active;
            else
                doc.status.Value = Constants.OrderStatus.Completed;

            //doc.DiscountPercentage.Value = new decimal(0);

            //doc.grossamt.Value = row.IsTotalQuotedPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalQuotedPrice);
            doc.discountamt.Value = new decimal(0);
            doc.lineitemdisc.Value = row.IsDiscountAmountNull() ? new decimal(0) : Convert.ToDecimal(row.DiscountAmount);
            doc.nettamt.Value = row.IsTotalNetPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalNetPrice);
            doc.freight.Value = row.IsFreightNull() ? new decimal(0) : row.Freight;

            doc.tax.Value = new decimal(0);
            doc.grossamt.Value = doc.nettamt.Value;

            if (row.IsRequiredDateNull())
                doc.deliverydate.Value = null;
            else
                doc.deliverydate.Value = row.RequiredDate;
            if (row.IsEmployeeIDNull())
                doc.salesrepr.Value = null;
            else
                doc.salesrepr.Value = Convert.ToString(row.EmployeeID);

            if (row.IsShipViaNull())
                doc.shippedvia.Value = null;
            else
                doc.shippedvia.Value = row.ShipVia;

            OrderAddress orderAddress = new OrderAddress();
            orderAddress.SetNorthwindAddress(row.IsShipAddressNull() ? "" : row.ShipAddress,
                row.IsShipCityNull() ? "" : row.ShipCity,
                row.IsShipPostalCodeNull() ? "" : row.ShipPostalCode,
                row.IsShipCountryNull() ? "" : row.ShipCountry);

            doc.shipaddress.Value = orderAddress.CrmOrderAddress;

            foreach (DataSets.Order.CalculatedOrderDetailsRow detailRow in detailDataTable.Rows)
            {
                lineItemDoc = GetDocumentLineItem(detailRow, lastToken, config);
                if ((doc.LogState != LogState.Created) && (lineItemDoc.HasNoLogStatus))
                    continue;

                doc.orderitems.Add(lineItemDoc);
            }

            foreach (DataSets.Order.DeletedOrderDetailsRow deletedRow in deletedOrderDetailsDataTable.Rows)
            {
                lineItemDoc = new LineItemDocument();
                lineItemDoc.Id = deletedRow[0].ToString();
                lineItemDoc.LogState = LogState.Deleted;
                doc.orderitems.Add(lineItemDoc);
            }

            return doc;
        }
Пример #39
0
 /// <summary>
 /// ExecuteTransaction is for the CRM system to send all create, update, and delete information from CRM to the ERP system. 
 /// </summary>
 /// <param name="TransactionData"></param>
 /// <param name="config">the configuration object</param>
 /// <returns>ExecuteTransactionsReponse is the response 
 /// from the ERP system providing results of the attempted changes.   
 /// The method returns an ArrayofTransactionResults, 
 /// which contains a list of TransactionResults.</returns>
 public TransactionResult[] ExecuteTransactions(Transaction[] TransactionData, NorthwindConfig config)
 {
     Document doc = GetDocumentTemplate();
     List<TransactionResult> result = new List<TransactionResult>();
     try
     {
         for (int index = 0; index < TransactionData.Length; index++)
         {
             doc = GetDocumentTemplate();
             doc.ReadFromXmlNode(TransactionData[index].Instance);
             ExecuteTransaction(doc, config, ref result);
         }
     }
     catch(Exception e)
     {
         result.Add(doc.SetTransactionStatus(TransactionStatus.FatalError, e.Message));
     }
     return result.ToArray();
 }
Пример #40
0
        public XmlNode ViewRealTimeData(string entityName, string[] selectFields, SearchField[] searchFields, string[] orderFields, int rowsPerPage, int pageNumber, NorthwindConfig config)
        {
            // declarations
            string sqlQuery;
            DataSet resultDataSet;
            XmlDocument resultXmlDoc;
            SearchField[] whereFieldList;
            SearchField[] havingFieldList;
            List<OleDbParameter> oleDbParameterList;

            // initializations
            resultDataSet = null;
            oleDbParameterList = null;

            // fill the where and having field lists
            whereFieldList = this.GetWhereFields(searchFields);
            havingFieldList = this.GetHavingFields(searchFields);

            // Create an OleDbCommand .
            sqlQuery = this.CreateSqlQuery(whereFieldList, havingFieldList, orderFields, out oleDbParameterList);

            // Get data from database
            this.Fill(sqlQuery, oleDbParameterList, config, out resultDataSet);

            // Convert result xml document to the CRM contract format
            resultXmlDoc = this.ConvertToXmlDocument(resultDataSet, selectFields, pageNumber, rowsPerPage);

            // return the root node xml document
            return (XmlNode)resultXmlDoc.DocumentElement;
        }
Пример #41
0
 /// <summary>
 /// get the next changes from an entity
 /// </summary>
 /// <param name="table">the datatable to fill</param>
 /// <param name="config">the configuration object</param>
 /// <param name="lastToken">the last token to get the next 10 changelog entries</param>
 /// <returns>retunrs a recordcount and a filled datatable</returns>
 public abstract int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken);
Пример #42
0
        /* ChangeLog */
        public override int FillChangeLog(out System.Data.DataTable table, NorthwindConfig config, Token lastToken)
        {
            #region Declarations
            int recordCount = 0;
            DataSets.Product changelog = new DataSets.Product();
            int lastUomID = 0;
            #endregion

            lastUomID = Token.GetId(lastToken);

            // get the first 11 rows of the changelog
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {
                ChangeLogsTableAdapter tableAdapter;

                tableAdapter = new ChangeLogsTableAdapter();

                tableAdapter.Connection = connection;

                // fill the Changelog dataset
                if (lastToken.InitRequest)
                    recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastUomID, lastToken.SequenceNumber, lastToken.SequenceNumber, "");
                else
                    recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastUomID, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser);

            }

            table = changelog.ChangeLogs;
            return recordCount;
        }
Пример #43
0
 public abstract List<Identity> GetAll(NorthwindConfig config, string whereExpression, OleDbParameter[] oleDbParameters);
Пример #44
0
 public override List<Identity> GetAll(NorthwindConfig config, string whereExpression, int startIndex, int count)
 {
     throw new NotImplementedException();
 }
Пример #45
0
 public abstract List<Identity> GetAll(NorthwindConfig config, string whereExpression, int startIndex, int count);
Пример #46
0
        /* Update */
        public override void Update(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            List<TransactionResult> transactionResult = new List<TransactionResult>();
            UnitOfMeasureFamilyDocument uomFamilyDoc = doc as UnitOfMeasureFamilyDocument;

            #region check input values
            if (uomFamilyDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            // check id
            #endregion

            DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter;

            DataSets.Product productDataset = new DataSets.Product();
            DataSets.Product.ProductsRow row;
            tableAdapter = new DataSets.ProductTableAdapters.ProductsTableAdapter();
            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {

                connection.Open();
                tableAdapter.Connection = connection;
                int recordCount = tableAdapter.FillBy(productDataset.Products, Convert.ToInt32(uomFamilyDoc.Id));
                if (recordCount == 0)
                {
                    doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, "Product does not exists");
                    return;
                }
                row = (DataSets.Product.ProductsRow)productDataset.Products.Rows[0];

                try
                {
                    // active ???

                    // defaultvalue ???

                    if(!uomFamilyDoc.name.NotSet)
                        if (uomFamilyDoc.name.IsNull)
                            row.SetQuantityPerUnitNull();
                        else
                            row.QuantityPerUnit = (string)uomFamilyDoc.name.Value;

                    if(!uomFamilyDoc.description.NotSet)
                        if (uomFamilyDoc.description.IsNull)
                            row.SetProductNameNull();
                        else
                            row.ProductName = (string)uomFamilyDoc.description.Value;

                    // ModifyID
                    row.ModifyID = config.SequenceNumber;
                    row.ModifyUser = config.CrmUser;
                }
                catch (Exception e)
                {
                    uomFamilyDoc.Id = "";
            #warning Check error message
                    result.Add(uomFamilyDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                    return;
                }

                tableAdapter = new DataSets.ProductTableAdapters.ProductsTableAdapter();
                tableAdapter.Connection = connection;

                tableAdapter.Update(productDataset.Products);

                result.Add(doc.SetTransactionStatus(TransactionStatus.Success));

            }
        }
Пример #47
0
        /// <summary>
        /// GetChangeLog is a request to the ERP system for changes to 
        /// a specific named entity instance for specified time durations.  
        /// A change can be either create, update, or delete.
        /// </summary>
        /// <param name="lastToken">the last passed token</param>
        /// <param name="config">the configuration object</param>
        /// <returns>
        /// The response to GetChangeLog is a GetChangeLogResponse, 
        /// which returns a list of changes (creates, deletes and updates), 
        /// in a complex type called ArrayofChangeLogEntries
        /// ArrayofChangeLogEntries contains a list of ChangeLogEntry’s 
        /// which contain details of the changes.
        /// </returns>
        public ChangeLog GetChangelog(Token lastToken, NorthwindConfig config)
        {
            #region Declarations
            int recordCount = 0;
            Token token;
            Identity identity;
            Document doc;
            ChangeLog result = new ChangeLog();
            DataTable dataTable;
            DataRow row;
            XmlDocument xmlDoc = new XmlDocument();
            #endregion

            // get the first 11 rows of the changelog
            recordCount = FillChangeLog(out dataTable, config, lastToken);

            // set the attend flag if the changlog contains less then 11 recorde
            result.AtEnd = (recordCount < 11);

            // if there are 11 instances, only 100 will retuned in this request
            result.ChangeLogInstances = new ChangeLogEntry[recordCount == 11 ? 10 : recordCount];

            token = lastToken;

            // go thru at least 10 records of the changelog
            for (int i = 0; i < result.ChangeLogInstances.Length; i++)
            {
                //get the next changelog entry
                row = dataTable.Rows[i];

                identity = new Identity(this.EntityName, (string)row[0]);

                // create a token from the changelog data
                token = new Token(identity, (int)row[1], lastToken.InitRequest);

                // get the Document by id
                doc = GetDocument(identity, lastToken, config);

                // create a changelog entry
                result.ChangeLogInstances[i] = new ChangeLogEntry();

                // set the token of this entry
                result.ChangeLogInstances[i].Token = Token.SerializeTokenToString(token);

                // add the xmldocument of the account document to the result
                result.ChangeLogInstances[i].Instance = doc.GetXmlNode(xmlDoc);

            }

            if (result.AtEnd)
                token.InitRequest = false;

            // update the nextpass token to the current one
            result.NextPassToken = Token.SerializeTokenToString(token);
            if (result.ChangeLogInstances.Length > 0)
                result.ChangeLogInstances[result.ChangeLogInstances.Length - 1].Token = result.NextPassToken;

            return result;
        }
Пример #48
0
        /* Add */
        public override void Add(Document doc, NorthwindConfig config, ref List<TransactionResult> result)
        {
            List<TransactionResult> transactionResult = new List<TransactionResult>();
            UnitOfMeasureFamilyDocument uomFamilyDoc = doc as UnitOfMeasureFamilyDocument;

            #region check input values

            if (uomFamilyDoc == null)
            {
                result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported));
                return;
            }

            #endregion

            DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter;

            DataSets.Product productDataset = new DataSets.Product();
            DataSets.Product.ProductsRow row = productDataset.Products.NewProductsRow();

            #region fill dataset from document

            try
            {
                // active ???

                // defaultvalue ???

                if (uomFamilyDoc.name.IsNull)
                    row.SetQuantityPerUnitNull();
                else
                    row.QuantityPerUnit = (string)uomFamilyDoc.name.Value;

                if (uomFamilyDoc.description.IsNull)
                    row.SetProductNameNull();
                else
                    row.ProductName = (string)uomFamilyDoc.description.Value;

                // CreateID and ModifyID
                row.CreateID = config.SequenceNumber;
                row.CreateUser = config.CrmUser;

                row.ModifyID = config.SequenceNumber;
                row.ModifyUser = config.CrmUser;
            }
            catch (Exception e)
            {
                uomFamilyDoc.Id = "";
            #warning Check error message
                result.Add(uomFamilyDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString()));
                return;
            }

            #endregion

            using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
            {

                connection.Open();

                tableAdapter = new DataSets.ProductTableAdapters.ProductsTableAdapter();
                tableAdapter.Connection = connection;

                productDataset.Products.AddProductsRow(row);
                tableAdapter.Update(productDataset.Products);
                OleDbCommand Cmd = new OleDbCommand("SELECT @@IDENTITY", connection);
                object lastid = Cmd.ExecuteScalar();
                uomFamilyDoc.Id = ((int)lastid).ToString();

            }
            result.Add(doc.SetTransactionStatus(TransactionStatus.Success));
        }
Пример #49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="accDoc"></param>
        /// <param name="accountRow"></param>
        /// <param name="config"></param>
        private void StoreCustomer(AccountDocument accDoc, AccountDataset.AccountsRow accountRow, NorthwindConfig config, ref List<TransactionResult> result)
        {
            #region declaration
            AccountDataset.CustomersRow customerRow;
            AccountDataset account;
            CustomersTableAdapter tableAdapter;
            string columnName;
            int recordCount;
            bool newCustomer;
            string customerId;
            #endregion

            newCustomer = ((accDoc.Id == null) || (accDoc.Id == ""));

            try
            {
                if (newCustomer)
                    customerId = GetNewCustomerID((string)accDoc.name.Value, config);
                else if (accDoc.Id.StartsWith(Constants.CustomerIdPrefix, StringComparison.InvariantCultureIgnoreCase))
                    customerId = accDoc.Id.Substring(Constants.CustomerIdPrefix.Length);
                else
                {
                    result.Add(accDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountNotFound));
                    return;
                }
            }
            catch (Exception)
            {
                result.Add(accDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountNotFound));
                return;
            }
            try
            {

                using (OleDbConnection connection = new OleDbConnection(config.ConnectionString))
                {
                    account = new AccountDataset();

                    tableAdapter = new CustomersTableAdapter();
                    tableAdapter.Connection = connection;
                    if (newCustomer)
                    {
                        customerRow = account.Customers.NewCustomersRow();
                        customerRow.CustomerID = customerId;
                    }
                    else
                    {
                        recordCount = tableAdapter.FillBy(account.Customers, customerId);
                        if (recordCount == 0)
                        {
                            accDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountNotFound);
                            return;
                        }
                        customerRow = (AccountDataset.CustomersRow)account.Customers.Rows[0];

                    }

                    for (int index = 0; index < accountRow.Table.Columns.Count; index++)
                    {

                        columnName = accountRow.Table.Columns[index].ColumnName;

                        if (!customerRow.Table.Columns.Contains(columnName))
                            continue;

                        if (columnName.StartsWith("Create", StringComparison.InvariantCultureIgnoreCase))
                            if ((accountRow[columnName].GetType().Equals(typeof(DBNull))))
                                continue;

                        customerRow[columnName] = accountRow[columnName];
                    }

                    if (newCustomer)
                        account.Customers.AddCustomersRow(customerRow);

                    tableAdapter.Update(account.Customers);
                    accDoc.SetTransactionStatus(TransactionStatus.Success);

                    SetIdentitiesForAccounts(Constants.CustomerIdPrefix + customerId, accDoc);
                    accDoc.GetTransactionResult(ref result);
                }
            }
            catch (Exception addCustomerException)
            {
                result.Add(accDoc.SetTransactionStatus(TransactionStatus.FatalError, addCustomerException.ToString()));
                throw;
            }

            UpdateEmailsCollectionFromCustomer(customerId, accDoc.emails, config, ref result);
        }