Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
        public override SyncFeedEntry GetFeedEntry(string idString)
        {
            #region declarations
            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;
            if (!(Int32.TryParse(idString, out id)))
            {
                id = 0;
            }
            #endregion


            #region fill dataset
            using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
            {
                tableAdapter.Connection = connection;
                recordCount             = tableAdapter.FillBy(order.CalculatedOrders, id);
                if (recordCount == 0)
                {
                    return(null);
                }

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

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


            SyncFeedEntry entry = new SyncFeedEntry();
            entry.Id = String.Format("{0}{1}('{2}')", _context.DatasetLink, _resourceKind.ToString(), idString);

            entry.Title   = String.Format("{0}: {1}", _resourceKind.ToString(), idString);
            entry.Updated = DateTime.Now;

            entry.Payload = GetPayload((DataSets.Order.CalculatedOrdersRow)order.CalculatedOrders[0],
                                       order.CalculatedOrderDetails,
                                       //order.DeletedOrderDetails,
                                       _context.Config);

            entry.SyncLinks.AddRange(GetLinks(entry.Payload.ForeignIds));

            return(entry);
        }
Ejemplo n.º 4
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));
        }
Ejemplo n.º 5
0
        public override SdataTransactionResult Delete(string id)
        {
            SdataTransactionResult tmpTransactionResult;
            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
            DataSets.Order order = new DataSets.Order();

            int productId;
            int orderId;
            if (GetLocalIds(id, out orderId, out productId))
            {
                using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
                {
                    try
                    {
                        detailsTableAdapter.Connection = connection;
                        int recordCount = detailsTableAdapter.FillBy(order.Order_Details, orderId);
                        if (recordCount == 0)
                        {
                            tmpTransactionResult = new SdataTransactionResult();
                            tmpTransactionResult.LocalId = id;
                            tmpTransactionResult.HttpMethod = "DELETE";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage = ("salesorder not found");
                            return tmpTransactionResult;
                        }

                        foreach (Sage.Integration.Northwind.Adapter.Data.SalesOrders.DataSets.Order.Order_DetailsRow row in order.Order_Details.Rows)
                        {
                            if (row.ProductID == productId)
                            {
                                row.Delete();
                                break;
                            }
                        }

                        detailsTableAdapter.Update(order.Order_Details);
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.LocalId = id;
                        tmpTransactionResult.HttpMethod = "DELETE";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.OK;
                        return tmpTransactionResult;
                    }
                    catch (Exception e)
                    {
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.LocalId = id;
                        tmpTransactionResult.HttpMethod = "DELETE";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage = e.Message;
                        return tmpTransactionResult;
                    }

                }

            }
            tmpTransactionResult = new SdataTransactionResult();
            tmpTransactionResult.LocalId = id;
            tmpTransactionResult.HttpMethod = "DELETE";
            tmpTransactionResult.ResourceKind = _resourceKind;
            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
            tmpTransactionResult.HttpMessage = "Not found";
            return tmpTransactionResult;
        }
Ejemplo n.º 6
0
        public override SdataTransactionResult Update(PayloadBase payload, List<SyncFeedEntryLink> links)
        {
            SdataTransactionResult tmpTransactionResult;

            if (!(payload is SalesOrderLinePayload))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("salesorder payload missing");
                return tmpTransactionResult;
            }
            salesOrderLinetype soLine = (payload as SalesOrderLinePayload).SalesOrderLinetype;
            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
            DataSets.Order order = new DataSets.Order();

            int productId;
            int orderId;
            if (GetLocalIds(payload.LocalID, out orderId, out productId))
            {
                using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
                {
                    try
                    {
                        detailsTableAdapter.Connection = connection;
                        int recordCount = detailsTableAdapter.FillBy(order.Order_Details, orderId);
                        if (recordCount == 0)
                        {
                            tmpTransactionResult = new SdataTransactionResult();
                            tmpTransactionResult.LocalId = payload.LocalID;
                            tmpTransactionResult.HttpMethod = "PUT";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage = ("salesorder not found");
                            return tmpTransactionResult;
                        }

                        foreach (Sage.Integration.Northwind.Adapter.Data.SalesOrders.DataSets.Order.Order_DetailsRow detailsRow in order.Order_Details.Rows)
                        {
                            if (detailsRow.ProductID == productId)
                            {
                                detailsRow.ModifyUser = _context.Config.CrmUser;
                                detailsRow.ModifyID = _context.Config.SequenceNumber;
                                if (soLine.quantitySpecified)
                                    detailsRow.Quantity = Convert.ToInt16(soLine.quantity);
                                else
                                    detailsRow.Quantity = 0;

                                if (soLine.initialPriceSpecified)
                                    detailsRow.UnitPrice = (Decimal)soLine.initialPrice;
                                else
                                    detailsRow.UnitPrice = 0;

                                if ((!soLine.discountTotalSpecified) || (detailsRow.Quantity == 0) || (detailsRow.UnitPrice == 0))
                                {
                                    detailsRow.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)soLine.discountTotal / (detailsRow.UnitPrice));
                                    if (discount > 1)
                                        discount = 0;
                                    detailsRow.Discount = discount;
                                }

                                break;
                            }
                        }

                        detailsTableAdapter.Update(order.Order_Details);
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.LocalId = payload.LocalID;
                        tmpTransactionResult.HttpMethod = "PUT";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.OK;
                        return tmpTransactionResult;
                    }
                    catch (Exception e)
                    {
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.LocalId = payload.LocalID;
                        tmpTransactionResult.HttpMethod = "PUT";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage = e.Message;
                        return tmpTransactionResult;
                    }

                }

            }
            tmpTransactionResult = new SdataTransactionResult();
            tmpTransactionResult.LocalId = payload.LocalID;
            tmpTransactionResult.HttpMethod = "PUT";
            tmpTransactionResult.ResourceKind = _resourceKind;
            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
            tmpTransactionResult.HttpMessage = "Not found";
            return tmpTransactionResult;
        }
        public override SdataTransactionResult Update(PayloadBase payload, List <SyncFeedEntryLink> links)
        {
            SdataTransactionResult tmpTransactionResult;

            if (!(payload is SalesOrderLinePayload))
            {
                tmpTransactionResult              = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod   = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage  = ("salesorder payload missing");
                return(tmpTransactionResult);
            }
            salesOrderLinetype soLine = (payload as SalesOrderLinePayload).SalesOrderLinetype;

            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
            DataSets.Order order = new DataSets.Order();

            int productId;
            int orderId;

            if (GetLocalIds(payload.LocalID, out orderId, out productId))
            {
                using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
                {
                    try
                    {
                        detailsTableAdapter.Connection = connection;
                        int recordCount = detailsTableAdapter.FillBy(order.Order_Details, orderId);
                        if (recordCount == 0)
                        {
                            tmpTransactionResult              = new SdataTransactionResult();
                            tmpTransactionResult.LocalId      = payload.LocalID;
                            tmpTransactionResult.HttpMethod   = "PUT";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage  = ("salesorder not found");
                            return(tmpTransactionResult);
                        }

                        foreach (Sage.Integration.Northwind.Adapter.Data.SalesOrders.DataSets.Order.Order_DetailsRow detailsRow in order.Order_Details.Rows)
                        {
                            if (detailsRow.ProductID == productId)
                            {
                                detailsRow.ModifyUser = _context.Config.CrmUser;
                                detailsRow.ModifyID   = _context.Config.SequenceNumber;
                                if (soLine.quantitySpecified)
                                {
                                    detailsRow.Quantity = Convert.ToInt16(soLine.quantity);
                                }
                                else
                                {
                                    detailsRow.Quantity = 0;
                                }

                                if (soLine.initialPriceSpecified)
                                {
                                    detailsRow.UnitPrice = (Decimal)soLine.initialPrice;
                                }
                                else
                                {
                                    detailsRow.UnitPrice = 0;
                                }

                                if ((!soLine.discountTotalSpecified) || (detailsRow.Quantity == 0) || (detailsRow.UnitPrice == 0))
                                {
                                    detailsRow.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)soLine.discountTotal / (detailsRow.UnitPrice));
                                    if (discount > 1)
                                    {
                                        discount = 0;
                                    }
                                    detailsRow.Discount = discount;
                                }

                                break;
                            }
                        }

                        detailsTableAdapter.Update(order.Order_Details);
                        tmpTransactionResult              = new SdataTransactionResult();
                        tmpTransactionResult.LocalId      = payload.LocalID;
                        tmpTransactionResult.HttpMethod   = "PUT";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.OK;
                        return(tmpTransactionResult);
                    }
                    catch (Exception e)
                    {
                        tmpTransactionResult              = new SdataTransactionResult();
                        tmpTransactionResult.LocalId      = payload.LocalID;
                        tmpTransactionResult.HttpMethod   = "PUT";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage  = e.Message;
                        return(tmpTransactionResult);
                    }
                }
            }
            tmpTransactionResult              = new SdataTransactionResult();
            tmpTransactionResult.LocalId      = payload.LocalID;
            tmpTransactionResult.HttpMethod   = "PUT";
            tmpTransactionResult.ResourceKind = _resourceKind;
            tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
            tmpTransactionResult.HttpMessage  = "Not found";
            return(tmpTransactionResult);
        }
        public override SdataTransactionResult Delete(string id)
        {
            SdataTransactionResult tmpTransactionResult;

            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
            DataSets.Order order = new DataSets.Order();

            int productId;
            int orderId;

            if (GetLocalIds(id, out orderId, out productId))
            {
                using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
                {
                    try
                    {
                        detailsTableAdapter.Connection = connection;
                        int recordCount = detailsTableAdapter.FillBy(order.Order_Details, orderId);
                        if (recordCount == 0)
                        {
                            tmpTransactionResult              = new SdataTransactionResult();
                            tmpTransactionResult.LocalId      = id;
                            tmpTransactionResult.HttpMethod   = "DELETE";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage  = ("salesorder not found");
                            return(tmpTransactionResult);
                        }

                        foreach (Sage.Integration.Northwind.Adapter.Data.SalesOrders.DataSets.Order.Order_DetailsRow row in order.Order_Details.Rows)
                        {
                            if (row.ProductID == productId)
                            {
                                row.Delete();
                                break;
                            }
                        }

                        detailsTableAdapter.Update(order.Order_Details);
                        tmpTransactionResult              = new SdataTransactionResult();
                        tmpTransactionResult.LocalId      = id;
                        tmpTransactionResult.HttpMethod   = "DELETE";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.OK;
                        return(tmpTransactionResult);
                    }
                    catch (Exception e)
                    {
                        tmpTransactionResult              = new SdataTransactionResult();
                        tmpTransactionResult.LocalId      = id;
                        tmpTransactionResult.HttpMethod   = "DELETE";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage  = e.Message;
                        return(tmpTransactionResult);
                    }
                }
            }
            tmpTransactionResult              = new SdataTransactionResult();
            tmpTransactionResult.LocalId      = id;
            tmpTransactionResult.HttpMethod   = "DELETE";
            tmpTransactionResult.ResourceKind = _resourceKind;
            tmpTransactionResult.HttpStatus   = System.Net.HttpStatusCode.BadRequest;
            tmpTransactionResult.HttpMessage  = "Not found";
            return(tmpTransactionResult);
        }
Ejemplo n.º 9
0
        public override SdataTransactionResult Update(PayloadBase payload, List<SyncFeedEntryLink> links)
        {
            SdataTransactionResult tmpTransactionResult;
            salesOrdertype salesorder = null;

            #region check input values
            if (!(payload is SalesOrderPayload))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("salesorder payload missing");
                return tmpTransactionResult;
            }
            salesorder = (payload as SalesOrderPayload).SalesOrdertype;

            if (salesorder == null)
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("salesorder payload missing");
                return tmpTransactionResult;

            }
            foreach (SyncFeedEntryLink link in links)
            {
                if (link.LinkRel != RelEnum.related.ToString())
                    continue;
                string localID = string.Empty;
                if (link.Href.StartsWith(_context.DatasetLink, StringComparison.InvariantCultureIgnoreCase))
                    if (link.Href.LastIndexOf("('") < link.Href.LastIndexOf("')"))
                        localID = link.Href.Substring(link.Href.LastIndexOf("('") + 2,
                            link.Href.LastIndexOf("')") - link.Href.LastIndexOf("('") - 2);

                SupportedResourceKinds reskind = ResourceKindHelpers.GetResourceKind(link.PayloadPath);

                if (localID == string.Empty)
                    localID = GetLocalId(link.Uuid, reskind);

                payload.ForeignIds.Add(link.PayloadPath, localID);
            }

            if (payload == null)
                return null;

            string customerID;

            if (!payload.ForeignIds.TryGetValue("tradingAccount", out customerID))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("Trading Acount Id missing");
                return tmpTransactionResult;
            }

            if (!customerID.StartsWith(Sage.Integration.Northwind.Application.API.Constants.CustomerIdPrefix))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("Salesorder submission is only supported by customers");
                return tmpTransactionResult;
            }
            #endregion

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

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

            int id;
            if (!(Int32.TryParse(payload.LocalID, out id)))
                id = 0;
            int recordCount;

            using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
            {
                tableAdapter.Connection = connection;
                recordCount = tableAdapter.FillBy(order.Orders, id);
                if (recordCount == 0)
                    return null;

                detailsTableAdapter.Connection = connection;
                detailsTableAdapter.FillBy(order.Order_Details, id);

            }

            DataSets.Order.OrdersRow row = (DataSets.Order.OrdersRow)order.Orders[0];

            #region fill dataset from document
            try
            {
                if (!salesorder.dateSpecified)
                    row.SetOrderDateNull();
                else
                    row.OrderDate = salesorder.date;

                if (!salesorder.dueDateSpecified)
                    row.SetRequiredDateNull();
                else
                    row.RequiredDate = (DateTime)salesorder.dueDate;

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

                if (salesorder.postalAddresses == null || salesorder.postalAddresses.Length == 0)
                {
                    row.SetShipAddressNull();
                    row.SetShipCityNull();
                    row.SetShipCountryNull();
                    row.SetShipPostalCodeNull();
                }
                else
                {
                    postalAddresstype postadress = salesorder.postalAddresses[0];
                    row.ShipAddress = postadress.address1;
                    row.ShipCity = postadress.townCity;
                    row.ShipPostalCode = postadress.zipPostCode;
                    row.ShipCountry = postadress.country;

                }

                if (!salesorder.carrierTotalPriceSpecified)
                    row.Freight = (decimal)0;
                else
                    row.Freight = (decimal)salesorder.carrierTotalPrice;

                //row.CreateUser = _context.Config.CrmUser;
                row.ModifyUser = _context.Config.CrmUser;
                //row.CreateID = _context.Config.SequenceNumber;
                row.ModifyID = _context.Config.SequenceNumber;

                Dictionary<Guid, SyncFeedEntryLink> itemLinks = new Dictionary<Guid, SyncFeedEntryLink>();
                GuidConverter converter = new GuidConverter();
                 Guid itemUuid;

                foreach (SyncFeedEntryLink link in links)
                {
                    SupportedResourceKinds resKind = ResourceKindHelpers.GetResourceKind(link.PayloadPath);
                    if (resKind != SupportedResourceKinds.salesOrderLines)
                        continue;
                    try
                    {

                        itemUuid = (Guid)converter.ConvertFromString(link.Uuid);
                        if (!Guid.Empty.Equals(itemUuid))
                            itemLinks.Add(itemUuid, link);
                    }
                    catch (Exception)
                    {
                    }
                }
                List<DataSets.Order.Order_DetailsRow> rowsToDelete = new List<DataSets.Order.Order_DetailsRow>();

                //foreach (DataSets.Order.Order_DetailsRow detailsRow in rowsToDelete)
                //{
                //    detailsRow.Delete();
                //}

                foreach (DataSets.Order.Order_DetailsRow detailsRow in order.Order_Details)
                {
                    string itemId = detailsRow.OrderID.ToString() + "-" + detailsRow.ProductID.ToString();
                    itemUuid = GetUuid(itemId, "", SupportedResourceKinds.salesOrderLines);
                    SyncFeedEntryLink itemlink;
                    if (itemLinks.TryGetValue(itemUuid, out itemlink))
                    {
                        string lineNumberstring = itemlink.PayloadPath.Substring(itemlink.PayloadPath.IndexOf("[") + 1, itemlink.PayloadPath.IndexOf("]") - itemlink.PayloadPath.IndexOf("[") - 1);
                        int lineNumber;
                        if (Int32.TryParse(lineNumberstring, out lineNumber))
                        {
                            if (lineNumber < salesorder.salesOrderLines.Length)
                            {
                                salesOrderLinetype soLine = salesorder.salesOrderLines[lineNumber];
                                detailsRow.ModifyUser = _context.Config.CrmUser;
                                detailsRow.ModifyID = _context.Config.SequenceNumber;
                                if (soLine.quantitySpecified)
                                    detailsRow.Quantity = Convert.ToInt16(soLine.quantity);
                                else
                                    detailsRow.Quantity = 0;

                                if (soLine.initialPriceSpecified)
                                    detailsRow.UnitPrice = (Decimal)soLine.initialPrice;
                                else
                                    detailsRow.UnitPrice = 0;

                                if ((!soLine.discountTotalSpecified) || (detailsRow.Quantity == 0) || (detailsRow.UnitPrice == 0))
                                {
                                    detailsRow.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)soLine.discountTotal / (detailsRow.UnitPrice));
                                    if (discount > 1)
                                        discount = 0;
                                    detailsRow.Discount = discount;
                                }

                            }
                        }
                        itemLinks.Remove(itemUuid);
                    }
                    else
                    {
                        //delete item
                        rowsToDelete.Add(detailsRow);
                    }

                }

                foreach (SyncFeedEntryLink itemlink in itemLinks.Values)
                {
                    {
                        try
                        {
                            int productID;
                            string productIdString;
                            string productIdPayload = String.Format("{0}/{1}", itemlink.PayloadPath, "commodity");

                            if (payload.ForeignIds.TryGetValue(productIdPayload, out productIdString))
                            {
                                try
                                {
                                    productID = Convert.ToInt32(productIdString);
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                            }
                            else
                                continue;

                            string lineNumberstring = itemlink.PayloadPath.Substring(itemlink.PayloadPath.IndexOf("[") + 1, itemlink.PayloadPath.IndexOf("]") - itemlink.PayloadPath.IndexOf("[") - 1);
                            int lineNumber;
                            if (Int32.TryParse(lineNumberstring, out lineNumber))
                            {
                                if (lineNumber < salesorder.salesOrderLines.Length)
                                {
                                    salesOrderLinetype soLine = salesorder.salesOrderLines[lineNumber];

                                    DataSets.Order.Order_DetailsRow detailRow = order.Order_Details.NewOrder_DetailsRow();
                                    soLine.applicationID = payload.LocalID + "-" + productID.ToString();
                                    detailRow.OrderID = Convert.ToInt32(payload.LocalID);
                                    detailRow.ProductID = productID;
                                    if (soLine.quantitySpecified)
                                        detailRow.Quantity = Convert.ToInt16(soLine.quantity);
                                    else
                                        detailRow.Quantity = 0;

                                    if (soLine.initialPriceSpecified)
                                        detailRow.UnitPrice = (Decimal)soLine.initialPrice;
                                    else
                                        detailRow.UnitPrice = 0;

                                    if ((!soLine.discountTotalSpecified) || (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)soLine.discountTotal / (detailRow.UnitPrice));
                                        if (discount > 1)
                                            discount = 0;
                                        detailRow.Discount = discount;
                                    }

                                    detailRow.CreateUser = _context.Config.CrmUser;
                                    detailRow.ModifyUser = _context.Config.CrmUser;
                                    detailRow.CreateID = _context.Config.SequenceNumber;
                                    detailRow.ModifyID = _context.Config.SequenceNumber;
                                    order.Order_Details.AddOrder_DetailsRow(detailRow);
                                }
                            }
                        }
                        // this error occours in case of invalid data types
                        catch (Exception e)
                        {

                            tmpTransactionResult = new SdataTransactionResult();
                            tmpTransactionResult.HttpMethod = "POST";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage = e.Message;
                            return tmpTransactionResult;

                        }

                    }

                }

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

                        tableAdapter.Connection = connection;
                        detailsTableAdapter.Connection = connection;

                        tableAdapter.SetTransaction(transaction);
                        detailsTableAdapter.SetTransaction(transaction);

                        foreach (DataSets.Order.Order_DetailsRow detailsRow in rowsToDelete)
                        {
                            detailsTableAdapter.Delete(detailsRow.OrderID,
                                detailsRow.ProductID,
                                detailsRow.UnitPrice, detailsRow.Quantity,
                                detailsRow.Discount, detailsRow.CreateID, detailsRow.CreateUser, detailsRow.ModifyID, detailsRow.ModifyUser);
                        }

                        tableAdapter.Update(order.Orders);
                        detailsTableAdapter.Update(order.Order_Details);

                        transaction.Commit();

                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.HttpMethod = "PUT";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.OK;
                        tmpTransactionResult.LocalId = payload.LocalID;
                        return tmpTransactionResult;

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

                }
            }
            catch (Exception e)
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "PUT";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = e.ToString();
                return tmpTransactionResult;
            }

            #endregion
        }
Ejemplo n.º 10
0
        public override SyncFeedEntry GetFeedEntry(string idString)
        {
            #region declarations
            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;
            if (!(Int32.TryParse(idString, out id)))
                id = 0;
            #endregion

            #region fill dataset
            using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
            {
                tableAdapter.Connection = connection;
                recordCount = tableAdapter.FillBy(order.CalculatedOrders, id);
                if (recordCount == 0)
                    return null;

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

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

            SyncFeedEntry entry = new SyncFeedEntry();
            entry.Id = String.Format("{0}{1}('{2}')", _context.DatasetLink, _resourceKind.ToString(), idString);

            entry.Title = String.Format("{0}: {1}", _resourceKind.ToString(), idString);
            entry.Updated = DateTime.Now;

            entry.Payload = GetPayload((DataSets.Order.CalculatedOrdersRow)order.CalculatedOrders[0],
                order.CalculatedOrderDetails,
                //order.DeletedOrderDetails,
                 _context.Config);

            entry.SyncLinks.AddRange(GetLinks(entry.Payload.ForeignIds));

            return entry;
        }
Ejemplo n.º 11
0
        public override SdataTransactionResult Add(PayloadBase payload, List<SyncFeedEntryLink> links)
        {
            SdataTransactionResult tmpTransactionResult;
            salesOrdertype salesorder = null;
            if (!(payload is SalesOrderPayload))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "POST";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("salesorder payload missing");
                return tmpTransactionResult;
            }
            salesorder = (payload as SalesOrderPayload).SalesOrdertype;

            if (salesorder == null)
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "POST";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("salesorder payload missing");
                return tmpTransactionResult;

            }
            foreach (SyncFeedEntryLink link in links)
            {
                if (link.LinkRel != RelEnum.related.ToString())
                    continue;
                string localID = string.Empty;
                if(link.Href.StartsWith(_context.DatasetLink, StringComparison.InvariantCultureIgnoreCase))
                    if (link.Href.LastIndexOf("('") < link.Href.LastIndexOf("')"))
                        localID = link.Href.Substring(link.Href.LastIndexOf("('")+2,
                            link.Href.LastIndexOf("')") - link.Href.LastIndexOf("('") -2);

                SupportedResourceKinds reskind = ResourceKindHelpers.GetResourceKind(link.PayloadPath);

                if (localID == string.Empty)
                    localID = GetLocalId(link.Uuid, reskind);

                payload.ForeignIds.Add(link.PayloadPath, localID);
            }

            #region check input values
            if (payload == null)
                return null;

            string customerID;

            if (!payload.ForeignIds.TryGetValue("tradingAccount", out customerID))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "POST";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("Trading Acount Id missing");
                return tmpTransactionResult;
            }

            if (!customerID.StartsWith(Sage.Integration.Northwind.Application.API.Constants.CustomerIdPrefix))
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "POST";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = ("Salesorder submission is only supported by customers");
                return tmpTransactionResult;
            }
            #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(Sage.Integration.Northwind.Application.API.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(_context.Config.ConnectionString))
                {
                    dataAdapter = new OleDbDataAdapter(sqlQuery, connection);
                    if (dataAdapter.Fill(dataSet, "Customers") == 0)
                    {
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.HttpMethod = "POST";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage = ("trading account not found");
                        return tmpTransactionResult;
                    }
                    newOrder.ShipName = dataSet.Tables[0].Rows[0][0].ToString();
                }
            }
            catch (Exception e)
            {
                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(!salesorder.dateSpecified)
                    newOrder.SetOrderDateNull();
                else
                    newOrder.OrderDate = salesorder.date;

                if (!salesorder.dueDateSpecified)
                    newOrder.SetRequiredDateNull();
                else
                    newOrder.RequiredDate = (DateTime)salesorder.dueDate;

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

                if (salesorder.postalAddresses == null || salesorder.postalAddresses.Length == 0)
                {
                    newOrder.SetShipAddressNull();
                    newOrder.SetShipCityNull();
                    newOrder.SetShipCountryNull();
                    newOrder.SetShipPostalCodeNull();
                }
                else
                {
                    postalAddresstype postadress = salesorder.postalAddresses[0];
                    newOrder.ShipAddress = postadress.address1;
                    newOrder.ShipCity = postadress.townCity;
                    newOrder.ShipPostalCode = postadress.zipPostCode;
                    newOrder.ShipCountry = postadress.country;

                }

                if (!salesorder.carrierTotalPriceSpecified)
                    newOrder.Freight = (decimal)0;
                else
                    newOrder.Freight = (decimal)salesorder.carrierTotalPrice;

                newOrder.CreateUser = _context.Config.CrmUser;
                newOrder.ModifyUser = _context.Config.CrmUser;
                newOrder.CreateID = _context.Config.SequenceNumber;
                newOrder.ModifyID = _context.Config.SequenceNumber;
            }
            catch (Exception e)
            {
                tmpTransactionResult = new SdataTransactionResult();
                tmpTransactionResult.HttpMethod = "POST";
                tmpTransactionResult.ResourceKind = _resourceKind;
                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                tmpTransactionResult.HttpMessage = e.ToString();
                return tmpTransactionResult;
            }

            #endregion

            using (OleDbConnection connection = new OleDbConnection(_context.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();
                    payload.LocalID = ((int)lastid).ToString();
                    // add line Items

                    DataSets.Order.Order_DetailsRow detailRow;

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

                    int productIndex= 0;
                    foreach (salesOrderLinetype salesOrderLine in salesorder.salesOrderLines)
                    {
                        try
                        {
                            string productIdString;
                            string productIdPayload = String.Format("salesOrderLines[{0}]/{1}",
                            productIndex.ToString(),
                            "commodity");
                            if (payload.ForeignIds.TryGetValue(productIdPayload, out productIdString))
                            {
                                try
                                {
                                    productID = Convert.ToInt32( productIdString);
                                }
                                catch (Exception)
                                {
            #warning only to test unsupported products
                                    productID = 0;
                                }
                            }
                            else
                                productID = 0;

                            if (addedProductsProducts.Contains(productID))
                            {
                                transaction.Rollback();
                                tmpTransactionResult = new SdataTransactionResult();
                                tmpTransactionResult.HttpMethod = "POST";
                                tmpTransactionResult.ResourceKind = _resourceKind;
                                tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                                tmpTransactionResult.HttpMessage = "Order contains a product twice";
                                return tmpTransactionResult;

                            }
                            addedProductsProducts.Add(productID, productID);

                            detailRow = order.Order_Details.NewOrder_DetailsRow();
                            salesOrderLine.applicationID = payload.LocalID + "-" + productID.ToString();
                            detailRow.OrderID = Convert.ToInt32(payload.LocalID);
                            detailRow.ProductID = productID;
                            if (salesOrderLine.quantitySpecified)
                                detailRow.Quantity = Convert.ToInt16(salesOrderLine.quantity);
                            else
                                detailRow.Quantity = 0;

                            if (salesOrderLine.initialPriceSpecified)
                                detailRow.UnitPrice = (Decimal)salesOrderLine.initialPrice;
                            else
                                detailRow.UnitPrice = 0;

                            if ((!salesOrderLine.discountTotalSpecified) || (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)salesOrderLine.discountTotal / (detailRow.UnitPrice));
                                if (discount > 1)
                                    discount = 0;
                                detailRow.Discount = discount;
                            }

                            detailRow.CreateUser = _context.Config.CrmUser;
                            detailRow.ModifyUser = _context.Config.CrmUser;
                            detailRow.CreateID = _context.Config.SequenceNumber;
                            detailRow.ModifyID = _context.Config.SequenceNumber;
                        }
                        // this error occours in case of invalid data types
                        catch (Exception e)
                        {
                            transaction.Rollback();

                            tmpTransactionResult = new SdataTransactionResult();
                            tmpTransactionResult.HttpMethod = "POST";
                            tmpTransactionResult.ResourceKind = _resourceKind;
                            tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                            tmpTransactionResult.HttpMessage = e.Message;
                            return tmpTransactionResult;

                        }
                        order.Order_Details.AddOrder_DetailsRow(detailRow);
                        productIndex++;
                    }

                    // 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();
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.HttpMethod = "POST";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage = e.Message;
                        return tmpTransactionResult;
                    }
                    transaction.Commit();

                    tmpTransactionResult = new SdataTransactionResult();
                    tmpTransactionResult.HttpMethod = "POST";
                    tmpTransactionResult.ResourceKind = _resourceKind;
                    tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.Created;
                    tmpTransactionResult.LocalId = payload.LocalID;
                    return tmpTransactionResult;

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

                }

            }
        }
Ejemplo n.º 12
0
        public override SdataTransactionResult Delete(string localID)
        {
            SdataTransactionResult tmpTransactionResult;
            DataSets.OrderTableAdapters.OrdersTableAdapter tableAdapter = new OrdersTableAdapter();
            DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
            DataSets.Order order = new DataSets.Order();

            int id;
            if (!(Int32.TryParse(localID, out id)))
                id = 0;
            int recordCount;

            using (OleDbConnection connection = new OleDbConnection(_context.Config.ConnectionString))
            {
                try
                {
                    tableAdapter.Connection = connection;
                    recordCount = tableAdapter.FillBy(order.Orders, id);
                    if (recordCount == 0)
                    {
                        tmpTransactionResult = new SdataTransactionResult();
                        tmpTransactionResult.LocalId = localID;
                        tmpTransactionResult.HttpMethod = "DELETE";
                        tmpTransactionResult.ResourceKind = _resourceKind;
                        tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                        tmpTransactionResult.HttpMessage = ("salesorder not found");
                        return tmpTransactionResult;
                    }

                    detailsTableAdapter.Connection = connection;
                    detailsTableAdapter.FillBy(order.Order_Details, id);
                    foreach (DataRow row in order.Order_Details.Rows)
                    {
                        row.Delete();
                    }
                    order.Orders[0].Delete();
                    detailsTableAdapter.Update(order.Order_Details);
                    tableAdapter.Update(order.Orders);
                    tmpTransactionResult = new SdataTransactionResult();
                    tmpTransactionResult.LocalId = localID;
                    tmpTransactionResult.HttpMethod = "DELETE";
                    tmpTransactionResult.ResourceKind = _resourceKind;
                    tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.OK;
                    return tmpTransactionResult;
                }
                catch (Exception e)
                {
                    tmpTransactionResult = new SdataTransactionResult();
                    tmpTransactionResult.LocalId = localID;
                    tmpTransactionResult.HttpMethod = "DELETE";
                    tmpTransactionResult.ResourceKind = _resourceKind;
                    tmpTransactionResult.HttpStatus = System.Net.HttpStatusCode.BadRequest;
                    tmpTransactionResult.HttpMessage = e.Message;
                    return tmpTransactionResult;
                }

            }
        }
Ejemplo n.º 13
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;
                }
            }
        }