예제 #1
0
        /// <summary>
        /// Appends fault details using StringBuilder, recurses inner faults
        /// </summary>
        /// <param name="fault">The current fault encountered</param>
        /// <param name="builder">The current message builder</param>
        /// <param name="isInnerFault">True = current fault is an inner fault</param>
        /// <returns>The provided StringBuilder instance. If arg is null, a new instance is created.</returns>
        public static StringBuilder ToFaultMessageString(this OrganizationServiceFault fault, StringBuilder builder = null, bool isInnerFault = false)
        {
            if (builder == null)
            {
                builder = new StringBuilder();
            }

            if (isInnerFault)
            {
                builder.Append(InnerPrefix);
            }

            // Append current fault
            builder.AppendFormat("OrganizationServiceFault: {0}", fault.Message).AppendLine();
            builder.AppendLine(StackTraceHeader);
            builder.AppendLine(fault.TraceText);

            // Recurse building the inner fault message string
            if (fault.InnerFault != null)
            {
                fault.InnerFault.ToFaultMessageString(builder, true);
            }

            return(builder);
        }
        protected void ParseExecuteMultipleResponse(ExecuteMultipleRequest exeMultiReq, ExecuteMultipleResponse exeMultiResp,
                                                    Tuple <List <Entity>, List <Tuple <Entity, string> > > entitySetOkFail)
        {
            for (int iRespNum = 0, iReqNum = 0; iRespNum < exeMultiResp.Responses.Count; iRespNum++)
            {
                iReqNum = exeMultiResp.Responses[iRespNum].RequestIndex;

                object target = null;
                exeMultiReq.Requests[iReqNum].Parameters.TryGetValue(SettingCtxt.Target, out target);

                Entity entity = (target != null) ? (typeof(EntityReference).Equals(target.GetType()) ? new Entity() : (Entity)target) : null;

                if (exeMultiResp.Responses[iRespNum].Response != null)
                {
                    if (entity != null && exeMultiResp.Responses[iRespNum].Response.Results.ContainsKey(SettingCtxt.Id))
                    {
                        entity.Id = (Guid)exeMultiResp.Responses[iRespNum].Response.Results[SettingCtxt.Id];
                    }
                    entitySetOkFail.Item1.Add(entity);
                }
                else if (exeMultiResp.Responses[iRespNum].Fault != null)
                {
                    OrganizationServiceFault orgSvcFault = exeMultiResp.Responses[iRespNum].Fault;
                    entitySetOkFail.Item2.Add(new Tuple <Entity, string>(entity, string.Format("MAIN: {0}{1}\n{2}", orgSvcFault.Message,
                                                                                               ((orgSvcFault.InnerFault != null) ? string.Format("INNER: {0}", orgSvcFault.InnerFault.Message) : string.Empty), orgSvcFault.TraceText)));
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Pretty-prints an OrganizationServiceFault
        /// </summary>
        /// <param name="fault">The fault to print</param>
        /// <returns>A formatted representation of the fault</returns>
        public static string Print(this OrganizationServiceFault fault)
        {
            if (fault == null)
            {
                throw new ArgumentNullException(nameof(fault));
            }

            var sb = new StringBuilder();

            sb.Append("Message: ").Append(fault.Message).AppendLine();
            sb.Append("Error code: ").Append(fault.ErrorCode).AppendLine();
            sb.Append("Error details: ").AppendLine();
            foreach (var errorDetail in fault.ErrorDetails)
            {
                sb.Append("\t").Append(errorDetail.Key).Append(": ").Append(errorDetail.Value).AppendLine();
            }
            sb.Append("Trace:").Append(fault.TraceText).AppendLine();

            if (fault.InnerFault != null)
            {
                sb.AppendLine();
                sb.Append("--- INNER FAULT ").Append(new string('-', 50));
                sb.AppendLine(fault.InnerFault.Print());
            }
            return(sb.ToString());
        }
 /// <summary>
 /// Display the fault that resulted from processing an organization message request.
 /// </summary>
 /// <param name="organizationRequest">The organization message request.</param>
 /// <param name="count">nth request number from ExecuteMultiple request</param>
 /// <param name="organizationServiceFault">A WCF fault.</param>
 private void DisplayFault(OrganizationRequest organizationRequest, int count,
                           OrganizationServiceFault organizationServiceFault)
 {
     Console.WriteLine("A fault occurred when processing {1} request, at index {0} in the request collection with a fault message: {2}", count + 1,
                       organizationRequest.RequestName,
                       organizationServiceFault.Message);
 }
        private static string FormatFaultException(OrganizationRequest request, OrganizationServiceFault fault)
        {
            var    message        = new StringBuilder();
            string requestMessage = request.FormatFaultException();

            message.AppendLine(requestMessage);
            if (fault.Message != null)
            {
                message.AppendLine("Message: " + fault.Message);
            }
            if (fault.TraceText != null)
            {
                message.AppendLine("TraceText: " + fault.TraceText);
            }
            if (fault.InnerFault != null)
            {
                if (fault.InnerFault.Message != null)
                {
                    message.AppendLine("InnerFault Message: " + fault.InnerFault.Message);
                }
                if (fault.InnerFault.TraceText != null)
                {
                    message.AppendLine("InnerFault TraceText: " + fault.InnerFault.TraceText);
                }
            }

            return(message.ToString());
        }
예제 #6
0
        protected bool IsAggregateQueryLimitExceeded(OrganizationServiceFault fault)
        {
            /*
             * 0x8004E023 / -2147164125
             * Name: AggregateQueryRecordLimitExceeded
             * Message: The maximum record limit is exceeded. Reduce the number of records.
             */
            if (fault.ErrorCode == -2147164125)
            {
                return(true);
            }

            return(false);
        }
예제 #7
0
        protected bool IsAggregateQueryRetryable(OrganizationServiceFault fault)
        {
            if (IsAggregateQueryLimitExceeded(fault))
            {
                return(true);
            }

            // Triggered when trying to use aggregates on log storage tables
            if (fault.ErrorCode == -2147220970 && fault.Message == "Aggregates are not supported")
            {
                return(true);
            }

            return(false);
        }
예제 #8
0
        private static string GetOperationResultError(OrganizationServiceFault fault)
        {
            StringBuilder error = new StringBuilder();

            if (fault != null)
            {
                if (fault.InnerFault != null)
                {
                    error.Append(GetOperationResultError(fault.InnerFault));
                }
                else
                {
                    error.Append($"Error:{fault.Message}");
                }
            }

            return(error.ToString());
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            Trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                Context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                ExecutionRecursionDepth = Context.Depth;

                Container = ContainerFactory.CreateContainer();
                RegisterFrequentlyUsedDependencies(Container, serviceProvider);

                EnvironmentInitialized();
                RegisterDependencies(Container);
                HandleRequest();
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                OrganizationServiceFault fault = ex.Detail;
                while (fault != null)
                {
                    Trace.Trace(fault.Message);
                    fault = fault.InnerFault;
                }

                ThrowException(ex);
            }
            catch (SaveChangesException ex)
            {
                ThrowException(ex.InnerException ?? ex);
            }
            catch (Exception ex)
            {
                ThrowException(ex);
            }
            finally
            {
                if (Container != null)
                {
                    Container.Dispose();
                    Container = null;
                }
            }
        }
        /// <summary>
        /// Executes the specified requests in a batch against Dynamics 365.
        /// </summary>
        /// <param name="requests">The requests to execute.</param>
        /// <param name="service">The organisation service.</param>
        /// <param name="cancel">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        protected void ExecuteBatchedRequests(List <OrganizationRequest> requests, IOrganizationService service, CancellationToken cancel, IProgress <ExecutionProgress> progress)
        {
            ExecuteMultipleRequest executeMultipleRequest = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = ContinuteOnError,
                    ReturnResponses = false
                },
                Requests = new OrganizationRequestCollection()
            };

            executeMultipleRequest.Requests.AddRange(requests.GetRange(0, requests.Count));

            ExecuteMultipleResponse response = (ExecuteMultipleResponse)service.Execute(executeMultipleRequest);

            if (response.IsFaulted)
            {
                List <ExecuteMultipleResponseItem> errors = response.Responses.Where(r => r.Fault != null).ToList();

                if (errors.Count > 0)
                {
                    OrganizationServiceFault error = errors.First().Fault;
                    string errorMessage            = string.Format(Properties.Resources.Dynamics365RecordOperationExecuteBatchErrors, errors.Count, executeMultipleRequest.Requests.Count, error.Message);

                    if (ContinuteOnError)
                    {
                        progress?.Report(new ExecutionProgress(NotificationType.Warning, errorMessage));
                    }
                    else
                    {
                        throw new ApplicationException(errorMessage);
                    }
                }
            }
            else
            {
                progress?.Report(new ExecutionProgress(NotificationType.Information, string.Format(Properties.Resources.Dynamics365RecordOperationExecuteBatchSuccess, executeMultipleRequest.Requests.Count)));
            }

            cancel.ThrowIfCancellationRequested();
        }
예제 #11
0
        /// <summary>
        /// Adds the message description for <see cref="OrganizationServiceFault" />.
        /// </summary>
        /// <param name="orgServiceFault">The org service fault.</param>
        /// <param name="includeInnerFaultTraceText">if set to <c>true</c> [include inner fault trace text].</param>
        /// <param name="depth">The depth.</param>
        /// <exception cref="System.ArgumentNullException">orgServiceFault</exception>
        protected virtual void AddTraceDetailsInfo(OrganizationServiceFault orgServiceFault, bool includeInnerFaultTraceText, int depth = 0)
        {
            if (orgServiceFault == null)
            {
                throw new ArgumentNullException(nameof(orgServiceFault));
            }

            StringBuilder detailsStringBuilder = this.TraceDetailsStringBuilder;

            detailsStringBuilder.AppendLine($"Detail Error Code: {orgServiceFault.ErrorCode}");
            detailsStringBuilder.AppendLine($"Detail Timestamp: {orgServiceFault.Timestamp}");
            detailsStringBuilder.AppendLine($"Detail Message: {orgServiceFault.Message}");

            if (includeInnerFaultTraceText)
            {
                this.TracingService.Trace($"- INNER FAULT {depth} START -");
                this.TracingService.Trace(orgServiceFault.TraceText);
                this.TracingService.Trace($"- INNER FAULT {depth} END -");
            }

            if (orgServiceFault.ErrorDetails.Count > 0)
            {
                detailsStringBuilder.AppendLine("- ERROR DETAILS START -");
                foreach (var errorDetail in orgServiceFault.ErrorDetails)
                {
                    detailsStringBuilder.AppendLine($" {errorDetail.Key,20} = {errorDetail.Value}");
                }

                detailsStringBuilder.AppendLine("- ERROR DETAILS END -");
            }

            if (orgServiceFault.InnerFault == null)
            {
                return;
            }

            depth++;
            detailsStringBuilder.AppendLine($"- INNER FAULT {depth} START -");
            this.AddTraceDetailsInfo(orgServiceFault.InnerFault, includeInnerFaultTraceText, depth);
            detailsStringBuilder.AppendLine($"- INNER FAULT {depth} END -");
        }
예제 #12
0
        protected bool GetOrganizationServiceFault(Exception ex, out OrganizationServiceFault fault)
        {
            fault = null;

            if (ex is QueryExecutionException qee)
            {
                ex = qee.InnerException;
            }

            if (!(ex is FaultException <OrganizationServiceFault> faultEx))
            {
                return(false);
            }

            fault = faultEx.Detail;
            while (fault.InnerFault != null)
            {
                fault = fault.InnerFault;
            }

            return(true);
        }
예제 #13
0
 /// <summary>
 /// Show correct message to the user based on error code.
 /// Don't show the error to the user If the same error code is being displayed.
 /// </summary>
 /// <param name="serviceFault"></param>
 public async void OrganizationServiceFaultHandler(OrganizationServiceFault serviceFault, bool showErrorUser = true)
 {
     if (serviceFault != null &&
         (CurrentServiceFault == null ||
          (serviceFault.ErrorCode == 404 && CurrentServiceFault.ErrorCode != serviceFault.ErrorCode)))
     {
         // No network available
         this.AccessMode = DataAccessMode.Offline;
         if (showErrorUser)
         {
             CurrentServiceFault = serviceFault;
             if (String.IsNullOrEmpty(serviceFault.Message))
             {
                 await MessageCenter.ShowErrorMessage(AppResources.NoNetwork);
             }
             else
             {
                 await MessageCenter.ShowError(serviceFault.Message);
             }
             CurrentServiceFault = null;
         }
     }
 }
예제 #14
0
 private static String GetFaultInfo(OrganizationRequest organizationRequest, int count,
                                    OrganizationServiceFault organizationServiceFault)
 {
     return($"A fault occurred when processing {organizationRequest.RequestName} request, " +
            $"at index {count + 1} in the request collection with a fault message: {organizationServiceFault.Message}\r\n");
 }
예제 #15
0
 public string FormatFaultException(AssignRequest assignRequest, OrganizationServiceFault fault)
 {
     throw new NotImplementedException();
 }
예제 #16
0
 /// <summary>
 /// Display the fault that resulted from processing an organization message request.
 /// </summary>
 /// <param name="organizationRequest">The organization message request.</param>
 /// <param name="count">nth request number from ExecuteMultiple request</param>
 /// <param name="organizationServiceFault">A WCF fault.</param>
 private void DisplayFault(OrganizationRequest organizationRequest, int count,
     OrganizationServiceFault organizationServiceFault)
 {
     Console.WriteLine("A fault occurred when processing {1} request, at index {0} in the request collection with a fault message: {2}", count + 1,
         organizationRequest.RequestName,
         organizationServiceFault.Message);
 }
예제 #17
0
        log4net.ILog log = log4net.LogManager.GetLogger("fileLog");//获取一个日志记录器
        public CrmOrderResponse CreateCrmOrder(CreateCrmOrder CreateCrmOrder)
        {
            log.Info("Call CreateCrmOrder Interface....");
            CrmOrderResponse         response          = new CrmOrderResponse();
            CrmUtil                  cu                = new CrmUtil();
            OrganizationServiceProxy organizationProxy = cu.getCrmService();

            try
            {
                //1.Create order
                Entity salesorder = new Entity("salesorder");
                //if (CreateCrmOrder != null)
                //{
                //    log.Info("request is not null");
                //    log.Info(CreateCrmOrder);
                //    foreach (System.Reflection.PropertyInfo p in CreateCrmOrder.GetType().GetProperties())
                //    {
                //        log.Info("Name:" + p.Name + "--Value:" + p.GetValue(CreateCrmOrder));
                //    }
                //}


                salesorder["name"] = CreateCrmOrder.OrderName;

                Entity email_account = RetriveAccountByEmail(organizationProxy, CreateCrmOrder.CustomerId);
                salesorder["customerid"] = new EntityReference("account", email_account.Id);

                //salesorder["pricelevelid"] = new EntityReference("pricelevel", new Guid(CreateCrmOrder.PricelevelId));

                //salesorder["pricelevelid"] = new EntityReference("pricelevel", new Guid("52CFEDBC-FF7A-E411-80D6-AC162DB4BC5C"));
                salesorder["pricelevelid"] = new EntityReference("pricelevel", new Guid(cu.pricelevelid_value));

                string Po_Numbser = CreateCrmOrder.PoNumbser;
                if (Po_Numbser != null && Po_Numbser != "" && Po_Numbser.Length > 390)
                {
                    Po_Numbser = Po_Numbser.Substring(0, 390);
                }
                salesorder["new_ordernumber"] = Po_Numbser;
                OptionSetValue pv = new OptionSetValue(int.Parse(CreateCrmOrder.PaymenttermsCode));
                salesorder["paymenttermscode"]       = pv;
                salesorder["billto_name"]            = CreateCrmOrder.BilltoName;
                salesorder["billto_line1"]           = CreateCrmOrder.BilltoLine1;
                salesorder["billto_line2"]           = CreateCrmOrder.BilltoLine2;
                salesorder["billto_city"]            = CreateCrmOrder.BilltoCity;
                salesorder["billto_stateorprovince"] = CreateCrmOrder.BilltoStateOrProvince;
                salesorder["billto_country"]         = CreateCrmOrder.BilltoCountry;
                salesorder["billto_postalcode"]      = CreateCrmOrder.BilltoPostalcode;
                salesorder["shipto_name"]            = CreateCrmOrder.ShiptoName;
                salesorder["shipto_line1"]           = CreateCrmOrder.ShiptoLine1;
                salesorder["shipto_line2"]           = CreateCrmOrder.ShiptoLine2;
                salesorder["shipto_city"]            = CreateCrmOrder.ShiptoCity;
                salesorder["shipto_stateorprovince"] = CreateCrmOrder.ShiptoStateOrProvince;
                salesorder["shipto_country"]         = CreateCrmOrder.ShiptoCountry;
                salesorder["shipto_postalcode"]      = CreateCrmOrder.ShiptoPostalcode;

                List <CrmProduct> topProdcutList = CreateCrmOrder.CrmProductList;

                IEnumerable <IGrouping <string, CrmProduct> > query = topProdcutList.GroupBy(x => x.ManufacturerId);
                foreach (IGrouping <string, CrmProduct> info in query)
                {
                    List <CrmProduct> prodcutList = info.ToList <CrmProduct>();//分组后的集合

                    Entity vendor_account = RetriveAccountByManuFacturer(organizationProxy, prodcutList[0].ManufacturerId);
                    salesorder["new_vendor"] = new EntityReference("account", vendor_account.Id);

                    //Create Order
                    Guid orderId = organizationProxy.Create(salesorder);
                    log.Info("Create salesorder Success:" + orderId.ToString());


                    //2.Add prodcut to Order

                    log.Info("ProductList Count:" + prodcutList.Count);


                    #region Execute Multiple with Results
                    // Create an ExecuteMultipleRequest object.
                    ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
                    {
                        // Assign settings that define execution behavior: continue on error, return responses.
                        Settings = new ExecuteMultipleSettings()
                        {
                            ContinueOnError = false,
                            ReturnResponses = true
                        },
                        // Create an empty organization request collection.
                        Requests = new OrganizationRequestCollection()
                    };

                    // Create several (local, in memory) entities in a collection.
                    EntityCollection input = GetCollectionOfEntitiesToCreate(prodcutList, orderId, cu.uomid_value, organizationProxy);

                    // Add a CreateRequest for each entity to the request collection.
                    foreach (var entity in input.Entities)
                    {
                        CreateRequest createRequest = new CreateRequest {
                            Target = entity
                        };
                        requestWithResults.Requests.Add(createRequest);
                    }

                    // Execute all the requests in the request collection using a single web method call.
                    ExecuteMultipleResponse responseWithResults =
                        (ExecuteMultipleResponse)organizationProxy.Execute(requestWithResults);

                    // Display the results returned in the responses.
                    foreach (var responseItem in responseWithResults.Responses)
                    {
                        // A valid response.
                        if (responseItem.Response != null)
                        {
                            OrganizationRequest  orq = requestWithResults.Requests[responseItem.RequestIndex];
                            OrganizationResponse ors = responseItem.Response;
                        }

                        // An error has occurred.
                        else if (responseItem.Fault != null)
                        {
                            OrganizationRequest orq = requestWithResults.Requests[responseItem.RequestIndex];
                            int idx = responseItem.RequestIndex;
                            OrganizationServiceFault fa = responseItem.Fault;
                        }
                    }
                    #endregion Execute Multiple with Results

                    #region Execute Multiple with No Results

                    ExecuteMultipleRequest requestWithNoResults = new ExecuteMultipleRequest()
                    {
                        // Set the execution behavior to not continue after the first error is received
                        // and to not return responses.
                        Settings = new ExecuteMultipleSettings()
                        {
                            ContinueOnError = false,
                            ReturnResponses = false
                        },
                        Requests = new OrganizationRequestCollection()
                    };

                    // Update the entities that were previously created.
                    EntityCollection update = GetCollectionOfEntitiesToUpdate(prodcutList, organizationProxy);

                    foreach (var entity in update.Entities)
                    {
                        UpdateRequest updateRequest = new UpdateRequest {
                            Target = entity
                        };
                        requestWithNoResults.Requests.Add(updateRequest);
                    }

                    ExecuteMultipleResponse responseWithNoResults =
                        (ExecuteMultipleResponse)organizationProxy.Execute(requestWithNoResults);

                    // There should be no responses unless there was an error. Only the first error
                    // should be returned. That is the behavior defined in the settings.
                    if (responseWithNoResults.Responses.Count > 0)
                    {
                        foreach (var responseItem in responseWithNoResults.Responses)
                        {
                            if (responseItem.Fault != null)
                            {
                                OrganizationRequest orq = requestWithNoResults.Requests[responseItem.RequestIndex];
                                int ri = responseItem.RequestIndex;
                                OrganizationServiceFault fa = responseItem.Fault;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("All account records have been updated successfully.");
                    }

                    #endregion Execute Multiple with No Results



                    ////2.Add prodcut to Order
                    //log.Info("ProductList数量:"+CreateCrmOrder.CrmProductList.Count);
                    //List<CrmProduct> prodcutList = CreateCrmOrder.CrmProductList;
                    //foreach (CrmProduct prd in prodcutList)
                    //{
                    //    log.Info("Create salesorderdetail Begin:" + prd.ProductName);
                    //    Entity salesorderdetail = new Entity("salesorderdetail");
                    //    salesorderdetail["productid"] = new EntityReference("product", new Guid(prd.ProductName));
                    //    salesorderdetail["quantity"] = Decimal.Parse(prd.Quantity);
                    //    salesorderdetail["salesorderid"] = new EntityReference("salesorder", orderId);
                    //    //salesorderdetail["uomid"] = new EntityReference("uom", new Guid("CCFF5EBE-5407-4214-BD04-60461B7161AA"));
                    //    salesorderdetail["uomid"] = new EntityReference("uom", new Guid(cu.uomid_value));
                    //    //salesorderdetail["productid"] = prd.FreightAmount;
                    //    //salesorderdetail["productid"] = prd.AmountDiscount;
                    //    log.Info("Befor Create....");
                    //    Guid salesorderdetailId = organizationProxy.Create(salesorderdetail);
                    //    log.Info("创建salesorderdetail成功:" + salesorderdetailId.ToString());
                    //    //同时修改product的库存,用减法
                    //    Entity product = new Entity("product");
                    //    ColumnSet attributes = new ColumnSet(new string[] { "quantityonhand" });

                    //    product = organizationProxy.Retrieve(product.LogicalName, new Guid(prd.ProductName), attributes);
                    //    log.Info("Retrieved quantityonhand: " + product["quantityonhand"]);

                    //    decimal nowQuantity = (Decimal)product["quantityonhand"];
                    //    decimal newQuantity = nowQuantity - Decimal.Parse(prd.Quantity);
                    //    product["quantityonhand"] = newQuantity;
                    //    log.Info("newQuantity: " + newQuantity);

                    //    organizationProxy.Update(product);
                    //    log.Info("Update product quantity Success:" + prd.ProductName.ToString());
                    //}
                    //Add Free Shipping 4608DBBF-6E8F-E411-80DA-AC162DB4BC5C Flat Shipping Rate

                    //取消运费功能
                    //string isFreeShipping = CreateCrmOrder.IsFreeShipping;
                    //if(isFreeShipping.Equals("N"))//不免运费,加上运费的price list item
                    //{
                    //    Entity salesorderdetail = new Entity("salesorderdetail");
                    //    //salesorderdetail["productid"] = new EntityReference("product", new Guid("8698AE03-F994-E411-80E2-AC162DB41AC0"));
                    //    salesorderdetail["productid"] = new EntityReference("product", new Guid(cu.freeshipping_product_value));
                    //    salesorderdetail["quantity"] = Decimal.Parse("1");
                    //    salesorderdetail["salesorderid"] = new EntityReference("salesorder", orderId);
                    //    //salesorderdetail["uomid"] = new EntityReference("uom", new Guid("CCFF5EBE-5407-4214-BD04-60461B7161AA"));
                    //    salesorderdetail["uomid"] = new EntityReference("uom", new Guid(cu.uomid_value));
                    //    //salesorderdetail["productid"] = prd.FreightAmount;
                    //    //salesorderdetail["productid"] = prd.AmountDiscount;
                    //    Guid salesorderdetailId = organizationProxy.Create(salesorderdetail);
                    //    log.Info("创建运费成功:" + salesorderdetailId.ToString());
                    //}

                    Entity    isExistOrder     = new Entity("salesorder");
                    ColumnSet order_attributes = new ColumnSet(new string[] { "myce_taxratingid" });

                    isExistOrder = organizationProxy.Retrieve(isExistOrder.LogicalName, orderId, order_attributes);

                    isExistOrder["myce_taxratingid"] = new EntityReference("myce_taxrating", new Guid(cu.myce_taxratingid_value));
                    organizationProxy.Update(isExistOrder);

                    //fullfill salesorder
                    // FulfillSalesOrder(organizationProxy, orderId);

                    //create invoices
                    // CreateInvoice(organizationProxy, orderId);
                }



                response.ErrCode = "0";
                return(response);
            }
            catch (Exception ex)
            {
                log.Info(ex.Message + "--" + ex.ToString());
            }
            return(null);
        }
예제 #18
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered UpdateFXs.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("UpdateFXs.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            string serviceBaseCurrency = "RUB";

            using (var ctx = new OrganizationServiceContext(service))
            {
                try
                {
                    // Get exchange rates

                    DailyInfo client = new DailyInfo();
                    tracingService.Trace("Getting Most recent date available");
                    DateTime lastestDate = client.GetLatestDateTime();
                    tracingService.Trace("Getting FX Rates");
                    var exchangeRates = client.GetCursOnDateXML(lastestDate);



                    string baseCurrencyISO = string.Empty;
                    Guid   empty           = Guid.Empty;

                    var baseCurrency = (from c in ctx.CreateQuery <TransactionCurrency>()
                                        join o in ctx.CreateQuery <Organization>()
                                        on c.TransactionCurrencyId equals o.BaseCurrencyId.Id
                                        select new TransactionCurrency
                    {
                        TransactionCurrencyId = c.TransactionCurrencyId,
                        ISOCurrencyCode = c.ISOCurrencyCode,
                    }).FirstOrDefault();



                    if (baseCurrency != null)
                    {
                        baseCurrencyISO = baseCurrency.ISOCurrencyCode.ToUpper();

                        // Get the rate from service base rate to crm base currency
                        var serviceRateToCrmBase = GetExchangeRate(baseCurrencyISO, exchangeRates);
                        if (serviceRateToCrmBase == null)
                        {
                            throw new Exception(String.Format("Cannot find rate for base rate '{0}'", baseCurrencyISO));
                        }

                        // Get the currencies that are not the base currency
                        // Only update active currencies
                        var currencies = (from c in ctx.CreateQuery <TransactionCurrency>()
                                          where c.TransactionCurrencyId != baseCurrency.TransactionCurrencyId &&
                                          c.StateCode == TransactionCurrencyState.Active
                                          select new TransactionCurrency
                        {
                            TransactionCurrencyId = c.TransactionCurrencyId,
                            ISOCurrencyCode = c.ISOCurrencyCode,
                        });



                        foreach (TransactionCurrency currency in currencies)
                        {
                            string  isoCode    = currency.ISOCurrencyCode.ToUpper();
                            decimal?latestRate = null;

                            // Get rate from service base currency to this currency
                            decimal?serviceRate = 1;
                            if (isoCode != serviceBaseCurrency)
                            {
                                serviceRate = GetExchangeRate(isoCode, exchangeRates);
                            }


                            if (serviceRate != null)
                            {
                                // Get the rate from crm base rate
                                latestRate = serviceRateToCrmBase / serviceRate;
                            }
                            else
                            {
                                // The webserviceX currency service is no longer working - investigating alternatives
                                // latestRate = GetStandardRate(baseCurrencyISO, isoCode);
                            }


                            if (latestRate != null)
                            {
                                // We have a new rate so update it (even if it is the same!)
                                TransactionCurrency update = new TransactionCurrency();
                                update.TransactionCurrencyId = currency.TransactionCurrencyId;
                                update.ExchangeRate          = latestRate;
                                service.Update(update);
                            }
                        }
                    }
                }
                catch (FaultException <OrganizationServiceFault> e)
                {
                    tracingService.Trace("Exception: {0}", e.ToString());

                    // Handle the exception.
                    throw;
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Exception (will retry): {0}", ex.ToString());
                    // All exceptions must be retried since this workflow must call it's self to run on a daily basis
                    OrganizationServiceFault fault = new OrganizationServiceFault();
                    fault.ErrorCode = -2147204346; // This will cause the Async Server to retry up to 10 times before failing
                    fault.Message   = ex.ToString();
                    var networkException = new FaultException <OrganizationServiceFault>(fault);
                    throw networkException;
                }
            }
            tracingService.Trace("Exiting UpdateFXs.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
예제 #19
0
        /// <summary>
        /// Disassembles the Exception into a readable block
        /// </summary>
        /// <param name="objException">Exception to work with</param>
        /// <param name="sw">Writer to write too</param>
        /// <param name="level">depth</param>
        /// <param name="lastErrorMsg">Last Writer to write too</param>
        private void GetExceptionDetail(object objException, StringBuilder sw, int level, StringBuilder lastErrorMsg)
        {
            if (objException == null)
            {
                return;
            }

            //if (objException is SoapException)
            //{
            //	SoapException soapEx = (SoapException)objException;
            //	FormatExceptionMessage(
            //	soapEx.Source != null ? soapEx.Source.ToString().Trim() : "Not Provided",
            //	soapEx.TargetSite != null ? soapEx.TargetSite.Name.ToString() : "Not Provided",
            //	string.IsNullOrEmpty(soapEx.Message) ? "Not Provided" : soapEx.Message.ToString().Trim(),
            //	string.IsNullOrEmpty(soapEx.StackTrace) ? "Not Provided" : soapEx.StackTrace.ToString().Trim()
            //	, sw, level);

            //	lastErrorMsg.Append(string.IsNullOrEmpty(soapEx.Message) ? "Not Provided" : soapEx.Message.ToString().Trim());

            //	if (lastErrorMsg.Length > 0 && soapEx.InnerException != null)
            //		lastErrorMsg.Append(" => ");

            //	level++;
            //	if (soapEx.InnerException != null)
            //		GetExceptionDetail(soapEx.InnerException, sw, level, lastErrorMsg);

            //}
            //else
            if (objException is FaultException <OrganizationServiceFault> )
            {
                FaultException <OrganizationServiceFault> OrgFault = (FaultException <OrganizationServiceFault>)objException;
                string ErrorDetail = GenerateOrgErrorDetailsInfo(OrgFault.Detail.ErrorDetails);
                FormatExceptionMessage(
                    OrgFault.Source != null ? OrgFault.Source.ToString().Trim() : "Not Provided",
                    OrgFault.TargetSite != null ? OrgFault.TargetSite.Name.ToString() : "Not Provided",
                    OrgFault.Detail != null ? string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\nTrace: {2}{3}", OrgFault.Detail.Message, OrgFault.Detail.ErrorCode, OrgFault.Detail.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}") :
                    string.IsNullOrEmpty(OrgFault.Message) ? "Not Provided" : OrgFault.Message.ToString().Trim(),
                    string.IsNullOrEmpty(OrgFault.StackTrace) ? "Not Provided" : OrgFault.StackTrace.ToString().Trim()
                    , sw, level);

                lastErrorMsg.Append(OrgFault.Detail != null ? OrgFault.Detail.Message :
                                    string.IsNullOrEmpty(OrgFault.Message) ? string.Empty : OrgFault.Message.ToString().Trim());

                if (lastErrorMsg.Length > 0 && (OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    lastErrorMsg.Append(" => ");
                }

                level++;
                if ((OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    GetExceptionDetail(OrgFault.Detail != null && OrgFault.Detail.InnerFault != null ? OrgFault.Detail.InnerFault : (object)OrgFault.InnerException,
                                       sw, level, lastErrorMsg);
                }

                return;
            }
            else
            {
                if (objException is OrganizationServiceFault)
                {
                    OrganizationServiceFault oFault = (OrganizationServiceFault)objException;
                    string ErrorDetail = GenerateOrgErrorDetailsInfo(oFault.ErrorDetails);
                    FormatOrgFaultMessage(
                        string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\nTrace: {2}{3}", oFault.Message, oFault.ErrorCode, oFault.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}"),
                        oFault.Timestamp.ToString(),
                        oFault.ErrorCode.ToString(),
                        string.IsNullOrEmpty(oFault.TraceText) ? "Not Provided" : oFault.TraceText.ToString().Trim(), sw, level);

                    level++;

                    lastErrorMsg.Append(oFault.Message);
                    if (lastErrorMsg.Length > 0 && oFault.InnerFault != null)
                    {
                        lastErrorMsg.Append(" => ");
                    }

                    if (oFault.InnerFault != null)
                    {
                        GetExceptionDetail(oFault.InnerFault, sw, level, lastErrorMsg);
                    }

                    return;
                }
                else
                {
                    //			if (objException is FaultException<DeploymentServiceFault>)
                    //{
                    //	FaultException<DeploymentServiceFault> DeploymentFault = (FaultException<DeploymentServiceFault>)objException;
                    //	FormatExceptionMessage(
                    //	DeploymentFault.Source != null ? DeploymentFault.Source.ToString().Trim() : "Not Provided",
                    //	DeploymentFault.TargetSite != null ? DeploymentFault.TargetSite.Name.ToString() : "Not Provided",
                    //	DeploymentFault.Detail != null ? string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\n", DeploymentFault.Detail.Message, DeploymentFault.Detail.ErrorCode) :
                    //	string.IsNullOrEmpty(DeploymentFault.Message) ? "Not Provided" : DeploymentFault.Message.ToString().Trim(),
                    //	string.IsNullOrEmpty(DeploymentFault.StackTrace) ? "Not Provided" : DeploymentFault.StackTrace.ToString().Trim()
                    //	, sw, level);

                    //	lastErrorMsg.Append(DeploymentFault.Detail != null ? DeploymentFault.Detail.Message :
                    //	string.IsNullOrEmpty(DeploymentFault.Message) ? string.Empty : DeploymentFault.Message.ToString().Trim());

                    //	if (lastErrorMsg.Length > 0 && (DeploymentFault.InnerException != null || DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null))
                    //		lastErrorMsg.Append(" => ");

                    //	level++;
                    //	if ((DeploymentFault.InnerException != null || DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null))
                    //		GetExceptionDetail(DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null ? DeploymentFault.Detail.InnerFault : (object)DeploymentFault.InnerException,
                    //		sw, level, lastErrorMsg);

                    //	return;

                    //}
                    //else
                    //				if (objException is DeploymentServiceFault)
                    //{
                    //	DeploymentServiceFault oFault = (DeploymentServiceFault)objException;

                    //	StringBuilder errorText = new StringBuilder();
                    //	if (oFault.ErrorDetails != null && oFault.ErrorDetails.Count > 0)
                    //		foreach (var er in oFault.ErrorDetails)
                    //		{
                    //			errorText.AppendLine(string.Format(CultureInfo.InvariantCulture, "\t{0} raising error : {1}", er.Key, er.Value));
                    //		}

                    //	FormatDeploymentFaultMessage(
                    //	string.IsNullOrEmpty(oFault.Message) ? "Not Provided" : oFault.Message.ToString().Trim(),
                    //	oFault.Timestamp.ToString(),
                    //	oFault.ErrorCode.ToString(), errorText.ToString(), sw, level);

                    //	level++;

                    //	lastErrorMsg.Append(oFault.Message);
                    //	if (lastErrorMsg.Length > 0 && oFault.InnerFault != null)
                    //		lastErrorMsg.Append(" => ");

                    //	if (oFault.InnerFault != null)
                    //		GetExceptionDetail(oFault.InnerFault, sw, level, lastErrorMsg);

                    //	return;

                    //}
                    //else
                    if (objException is Exception)
                    {
                        Exception generalEx = (Exception)objException;
                        FormatExceptionMessage(
                            generalEx.Source != null ? generalEx.Source.ToString().Trim() : "Not Provided",
                            generalEx.TargetSite != null ? generalEx.TargetSite.Name.ToString() : "Not Provided",
                            string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim(),
                            string.IsNullOrEmpty(generalEx.StackTrace) ? "Not Provided" : generalEx.StackTrace.ToString().Trim()
                            , sw, level);

                        lastErrorMsg.Append(string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim());

                        if (lastErrorMsg.Length > 0 && generalEx.InnerException != null)
                        {
                            lastErrorMsg.Append(" => ");
                        }

                        level++;
                        if (generalEx.InnerException != null)
                        {
                            GetExceptionDetail(generalEx.InnerException, sw, level, lastErrorMsg);
                        }
                    }
                }
            }
            return;
        }
예제 #20
0
        /// <summary>
        /// Disassembles the Exception into a readable block
        /// </summary>
        /// <param name="objException">Exception to work with</param>
        /// <param name="sw">Writer to write too</param>
        /// <param name="level">depth</param>
        /// <param name="lastErrorMsg">Last Writer to write too</param>
        private void GetExceptionDetail(object objException, StringBuilder sw, int level, StringBuilder lastErrorMsg)
        {
            if (objException == null)
            {
                return;
            }

            if (objException is FaultException <OrganizationServiceFault> )
            {
                FaultException <OrganizationServiceFault> OrgFault = (FaultException <OrganizationServiceFault>)objException;
                string ErrorDetail = GenerateOrgErrorDetailsInfo(OrgFault.Detail.ErrorDetails);
                FormatExceptionMessage(
                    OrgFault.Source != null ? OrgFault.Source.ToString().Trim() : "Not Provided",
                    OrgFault.TargetSite != null ? OrgFault.TargetSite.Name.ToString() : "Not Provided",
                    OrgFault.Detail != null ? string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}{4}\nTrace: {2}{3}", OrgFault.Detail.Message, OrgFault.Detail.ErrorCode, OrgFault.Detail.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}", OrgFault.Detail.ActivityId == null ? "" : $"\nActivityId: {OrgFault.Detail.ActivityId}") :
                    string.IsNullOrEmpty(OrgFault.Message) ? "Not Provided" : OrgFault.Message.ToString().Trim(),
                    string.IsNullOrEmpty(OrgFault.HelpLink) ? "Not Provided" : OrgFault.HelpLink.ToString().Trim(),
                    string.IsNullOrEmpty(OrgFault.StackTrace) ? "Not Provided" : OrgFault.StackTrace.ToString().Trim()
                    , sw, level);

                lastErrorMsg.Append(OrgFault.Detail != null ? OrgFault.Detail.Message :
                                    string.IsNullOrEmpty(OrgFault.Message) ? string.Empty : OrgFault.Message.ToString().Trim());

                if (lastErrorMsg.Length > 0 && (OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    lastErrorMsg.Append(" => ");
                }

                level++;
                if ((OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    GetExceptionDetail(OrgFault.Detail != null && OrgFault.Detail.InnerFault != null ? OrgFault.Detail.InnerFault : (object)OrgFault.InnerException,
                                       sw, level, lastErrorMsg);
                }

                return;
            }
            else
            {
                if (objException is OrganizationServiceFault)
                {
                    OrganizationServiceFault oFault = (OrganizationServiceFault)objException;
                    string ErrorDetail = GenerateOrgErrorDetailsInfo(oFault.ErrorDetails);
                    FormatOrgFaultMessage(
                        string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}{4}\nTrace: {2}{3}", oFault.Message, oFault.ErrorCode, oFault.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}", oFault.ActivityId == null ? "" : $"\nActivityId: {oFault.ActivityId}"),
                        oFault.Timestamp.ToString(),
                        oFault.ErrorCode.ToString(),
                        string.IsNullOrEmpty(oFault.HelpLink) ? "Not Provided" : oFault.HelpLink.ToString().Trim(),
                        string.IsNullOrEmpty(oFault.TraceText) ? "Not Provided" : oFault.TraceText.ToString().Trim(), sw, level);

                    level++;

                    lastErrorMsg.Append(oFault.Message);
                    if (lastErrorMsg.Length > 0 && oFault.InnerFault != null)
                    {
                        lastErrorMsg.Append(" => ");
                    }

                    if (oFault.InnerFault != null)
                    {
                        GetExceptionDetail(oFault.InnerFault, sw, level, lastErrorMsg);
                    }

                    return;
                }
                else
                {
                    if (objException is HttpOperationException httpOperationException)
                    {
                        JObject contentBody = null;
                        if (!string.IsNullOrEmpty(httpOperationException.Response.Content))
                        {
                            contentBody = JObject.Parse(httpOperationException.Response.Content);
                        }

                        var ErrorBlock = contentBody?["error"];
                        FormatExceptionMessage(
                            httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
                            httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
                            string.IsNullOrEmpty(ErrorBlock?["message"]?.ToString()) ? "Not Provided" : string.Format("Message: {0}{1}\n", GetFirstLineFromString(ErrorBlock?["message"]?.ToString()).Trim(), httpOperationException.Response != null && httpOperationException.Response.Headers.ContainsKey("REQ_ID") ? $"\nActivityId: {ExtractString(httpOperationException.Response.Headers["REQ_ID"])}" : ""),
                            string.IsNullOrEmpty(httpOperationException.HelpLink) ? "Not Provided" : httpOperationException.HelpLink.ToString().Trim(),
                            string.IsNullOrEmpty(ErrorBlock?["stacktrace"]?.ToString()) ? "Not Provided" : ErrorBlock["stacktrace"]?.ToString().Trim()
                            , sw, level);

                        lastErrorMsg.Append(string.IsNullOrEmpty(httpOperationException.Message) ? "Not Provided" : httpOperationException.Message.ToString().Trim());

                        // WebEx currently only returns 1 level of error.
                        var InnerError = contentBody?["error"]["innererror"];
                        if (lastErrorMsg.Length > 0 && InnerError != null)
                        {
                            level++;
                            lastErrorMsg.Append(" => ");
                            FormatExceptionMessage(
                                httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
                                httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
                                string.IsNullOrEmpty(InnerError?["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(InnerError?["message"]?.ToString()).Trim(),
                                string.IsNullOrEmpty(InnerError?["@Microsoft.PowerApps.CDS.HelpLink"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(InnerError?["@Microsoft.PowerApps.CDS.HelpLink"]?.ToString()).Trim(),
                                string.IsNullOrEmpty(InnerError?["stacktrace"]?.ToString()) ? "Not Provided" : InnerError?["stacktrace"]?.ToString().Trim()
                                , sw, level);
                        }
                    }
                    else
                    {
                        if (objException is DataverseOperationException cdsOpExecp)
                        {
                            FormatSvcFaultMessage(
                                string.IsNullOrEmpty(cdsOpExecp.Message) ? "Not Provided" : cdsOpExecp.Message.ToString().Trim(),
                                string.IsNullOrEmpty(cdsOpExecp.Source) ? "Not Provided" : cdsOpExecp.Source.ToString().Trim(),
                                cdsOpExecp.HResult == -1 ? "Not Provided" : cdsOpExecp.HResult.ToString().Trim(),
                                cdsOpExecp.Data,
                                string.IsNullOrEmpty(cdsOpExecp.HelpLink) ? "Not Provided" : cdsOpExecp.HelpLink.ToString().Trim(),
                                sw,
                                level);

                            lastErrorMsg.Append(string.IsNullOrEmpty(cdsOpExecp.Message) ? "Not Provided" : cdsOpExecp.Message.ToString().Trim());

                            if (lastErrorMsg.Length > 0 && cdsOpExecp.InnerException != null)
                            {
                                lastErrorMsg.Append(" => ");
                            }

                            level++;
                            if (cdsOpExecp.InnerException != null)
                            {
                                GetExceptionDetail(cdsOpExecp.InnerException, sw, level, lastErrorMsg);
                            }
                        }
                        else
                        {
                            if (objException is Exception)
                            {
                                Exception generalEx = (Exception)objException;
                                FormatExceptionMessage(
                                    generalEx.Source != null ? generalEx.Source.ToString().Trim() : "Not Provided",
                                    generalEx.TargetSite != null ? generalEx.TargetSite.Name.ToString() : "Not Provided",
                                    string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim(),
                                    string.IsNullOrEmpty(generalEx.HelpLink) ? "Not Provided" : generalEx.HelpLink.ToString().Trim(),
                                    string.IsNullOrEmpty(generalEx.StackTrace) ? "Not Provided" : generalEx.StackTrace.ToString().Trim()
                                    , sw, level);

                                lastErrorMsg.Append(string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim());

                                if (lastErrorMsg.Length > 0 && generalEx.InnerException != null)
                                {
                                    lastErrorMsg.Append(" => ");
                                }

                                level++;
                                if (generalEx.InnerException != null)
                                {
                                    GetExceptionDetail(generalEx.InnerException, sw, level, lastErrorMsg);
                                }
                            }
                        }
                    }
                }
            }
            return;
        }
예제 #21
0
        public AppCrmOrderResponse AppCreateOrder(AppCrmOrderRequest orderRequest)
        {
            CrmUtil cu = new CrmUtil();
            OrganizationServiceProxy organizationProxy = cu.getCrmService();

            try
            {
                string email = orderRequest.email;
                log.Info("order-request:" + email);
                List <AppCrmOrderProduct> prodcutList = orderRequest.product;
                log.Info("order-request product:" + "----" + prodcutList.Count);

                string datetime_now = DateTime.Now.ToString("yyyyMMddHHmmss");

                Entity salesorder = new Entity("salesorder");


                Entity email_account = RetriveAccountByEmail(organizationProxy, email);
                salesorder["customerid"] = new EntityReference("account", email_account.Id);

                salesorder["pricelevelid"] = new EntityReference("pricelevel", new Guid(cu.pricelevelid_value));
                //salesorder["pricelevelid"] = new EntityReference("pricelevel", new Guid("780D3E7B-D6F9-E211-8ABD-984BE17C68D3"));

                //AN000001
                string new_orderno = this.readAppOrderNoFromXML();
                salesorder["name"]            = "AN" + new_orderno;
                salesorder["new_ordernumber"] = "PO" + new_orderno;
                Int32 exit_orderno = Int32.Parse(new_orderno);
                exit_orderno += 1;
                string new_exit_orderno = exit_orderno.ToString().PadLeft(6, '0');
                this.writeAppOrderNoToXML(new_exit_orderno);

                //From Mobile
                OptionSetValue orderfrom = new OptionSetValue(100000001);
                salesorder["new_orderfrom"] = orderfrom;

                //Payment
                OptionSetValue payment = new OptionSetValue(Int32.Parse(orderRequest.payment));
                salesorder["paymenttermscode"] = payment;

                //contact time
                salesorder["new_requestedringback"] = DateTime.Parse(orderRequest.contactTime);


                //OptionSetValue pv = new OptionSetValue(1);
                //salesorder["paymenttermscode"] = pv;
                //salesorder["billto_name"] = CreateCrmOrder.BilltoName;
                //salesorder["billto_line1"] = CreateCrmOrder.BilltoLine1;
                //salesorder["billto_line2"] = CreateCrmOrder.BilltoLine2;
                //salesorder["billto_city"] = CreateCrmOrder.BilltoCity;
                //salesorder["billto_stateorprovince"] = CreateCrmOrder.BilltoStateOrProvince;
                //salesorder["billto_country"] = CreateCrmOrder.BilltoCountry;
                //salesorder["billto_postalcode"] = CreateCrmOrder.BilltoPostalcode;
                //salesorder["shipto_line1"] = CreateCrmOrder.ShiptoLine1;
                //salesorder["shipto_line2"] = CreateCrmOrder.ShiptoLine2;
                //salesorder["shipto_city"] = CreateCrmOrder.ShiptoCity;
                //salesorder["shipto_stateorprovince"] = CreateCrmOrder.ShiptoStateOrProvince;
                //salesorder["shipto_country"] = CreateCrmOrder.ShiptoCountry;
                //salesorder["shipto_postalcode"] = CreateCrmOrder.ShiptoPostalcode;

                Guid orderId = organizationProxy.Create(salesorder);
                log.Info("创建salesorder成功:" + orderId.ToString());


                //2.Add prodcut to Order
                log.Info("ProductList数量:" + prodcutList.Count);
                #region Execute Multiple with Results
                // Create an ExecuteMultipleRequest object.
                ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };

                // Create several (local, in memory) entities in a collection.
                EntityCollection input = GetCollectionOfEntitiesToCreate2(prodcutList, orderId, cu.uomid_value, organizationProxy);

                // Add a CreateRequest for each entity to the request collection.
                foreach (var entity in input.Entities)
                {
                    CreateRequest createRequest = new CreateRequest {
                        Target = entity
                    };
                    requestWithResults.Requests.Add(createRequest);
                }

                // Execute all the requests in the request collection using a single web method call.
                ExecuteMultipleResponse responseWithResults =
                    (ExecuteMultipleResponse)organizationProxy.Execute(requestWithResults);

                // Display the results returned in the responses.
                foreach (var responseItem in responseWithResults.Responses)
                {
                    // A valid response.
                    if (responseItem.Response != null)
                    {
                        OrganizationRequest  orq = requestWithResults.Requests[responseItem.RequestIndex];
                        OrganizationResponse ors = responseItem.Response;
                    }

                    // An error has occurred.
                    else if (responseItem.Fault != null)
                    {
                        OrganizationRequest orq = requestWithResults.Requests[responseItem.RequestIndex];
                        int idx = responseItem.RequestIndex;
                        OrganizationServiceFault fa = responseItem.Fault;
                    }
                }
                #endregion Execute Multiple with Results

                #region Execute Multiple with No Results

                ExecuteMultipleRequest requestWithNoResults = new ExecuteMultipleRequest()
                {
                    // Set the execution behavior to not continue after the first error is received
                    // and to not return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = false
                    },
                    Requests = new OrganizationRequestCollection()
                };

                // Update the entities that were previously created.
                EntityCollection update = GetCollectionOfEntitiesToUpdate2(prodcutList, organizationProxy);

                foreach (var entity in update.Entities)
                {
                    UpdateRequest updateRequest = new UpdateRequest {
                        Target = entity
                    };
                    requestWithNoResults.Requests.Add(updateRequest);
                }

                ExecuteMultipleResponse responseWithNoResults =
                    (ExecuteMultipleResponse)organizationProxy.Execute(requestWithNoResults);

                // There should be no responses unless there was an error. Only the first error
                // should be returned. That is the behavior defined in the settings.
                if (responseWithNoResults.Responses.Count > 0)
                {
                    foreach (var responseItem in responseWithNoResults.Responses)
                    {
                        if (responseItem.Fault != null)
                        {
                            OrganizationRequest orq = requestWithNoResults.Requests[responseItem.RequestIndex];
                            int ri = responseItem.RequestIndex;
                            OrganizationServiceFault fa = responseItem.Fault;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("All account records have been updated successfully.");
                }

                #endregion Execute Multiple with No Results


                //Add Free Shipping 4608DBBF-6E8F-E411-80DA-AC162DB4BC5C Flat Shipping Rate
                //string isFreeShipping = CreateCrmOrder.IsFreeShipping;
                //if(isFreeShipping.Equals("N"))//不免运费,加上运费的price list item
                //{
                //    Entity salesorderdetail = new Entity("salesorderdetail");
                //    //salesorderdetail["productid"] = new EntityReference("product", new Guid("8698AE03-F994-E411-80E2-AC162DB41AC0"));
                //    salesorderdetail["productid"] = new EntityReference("product", new Guid("85ACAB90-7248-E411-9212-D89D67639EF0"));
                //    salesorderdetail["quantity"] = Decimal.Parse("1");
                //    salesorderdetail["salesorderid"] = new EntityReference("salesorder", orderId);
                //    //salesorderdetail["uomid"] = new EntityReference("uom", new Guid("CCFF5EBE-5407-4214-BD04-60461B7161AA"));
                //    salesorderdetail["uomid"] = new EntityReference("uom", new Guid("3E055750-D6F9-E211-8ABD-984BE17C68D3"));
                //    //salesorderdetail["productid"] = prd.FreightAmount;
                //    //salesorderdetail["productid"] = prd.AmountDiscount;
                //    Guid salesorderdetailId = organizationProxy.Create(salesorderdetail);
                //    log.Info("创建运费成功:" + salesorderdetailId.ToString());
                //}

                //Entity isExistOrder = new Entity("salesorder");
                //ColumnSet order_attributes = new ColumnSet(new string[] { "myce_taxratingid" });

                //isExistOrder = organizationProxy.Retrieve(isExistOrder.LogicalName, orderId, order_attributes);

                //isExistOrder["myce_taxratingid"] = new EntityReference("myce_taxrating", new Guid("99596F96-054E-E411-9212-D89D67639EF0"));
                //organizationProxy.Update(isExistOrder);

                AppCrmOrderResponse rs = new AppCrmOrderResponse();
                rs.orderId = orderId.ToString();
                return(rs);
            }
            catch (Exception ex)
            {
                log.Info(ex.Message + "--" + ex.ToString());
            }
            return(null);
        }
        private ExecuteMultipleResponse ExecuteInternal(ExecuteMultipleRequest request)
        {
            var settings = request.Settings;
            var response = new ExecuteMultipleResponse();
            response.Results["Responses"] = new ExecuteMultipleResponseItemCollection();

            for(int i=0; i<request.Requests.Count; i++)
            {
                var childRequest = request.Requests[i];
                OrganizationServiceFault fault = null;
                OrganizationResponse childResponse = null;
                try
                {
                    if (childRequest.RequestName == "ExecuteMultiple")
                    {
                        throw new Exception("ExecuteMultipleRequest cannot contain an ExecuteMultipleRequest");
                    }

                    childResponse = ExecuteInternal((dynamic) childRequest);
                    if (!settings.ReturnResponses)
                    {
                        childResponse = null;
                    }
                }
                catch (NotImplementedException)
                {
                    throw;
                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    response["IsFaulted"] = true;
                    fault = ex.Detail;
                    fault.ErrorDetails["CallStack"] = ex.StackTrace;
                    if (!settings.ContinueOnError)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    response["IsFaulted"] = true;
                    fault = new OrganizationServiceFault {Message = ex.Message, Timestamp = DateTime.UtcNow};
                    fault.ErrorDetails["CallStack"] = ex.StackTrace;
                    if (!settings.ContinueOnError)
                    {
                        break;
                    }
                }
                finally
                {
                    if (childResponse != null || fault != null)
                    {
                        response.Responses.Add(new ExecuteMultipleResponseItem
                        {
                            Fault = fault,
                            RequestIndex = i,
                            Response = childResponse
                        });
                    }
                }
            }
            return response;
        }
예제 #23
0
        private static void HandleException(Exception e, ITracingService tracingService)
        {
            tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e));
            tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "StackTrace: {0}", e.StackTrace));

            var organizationServiceFault = new OrganizationServiceFault { Message = e.Message };
            organizationServiceFault.ErrorDetails.Add("Original Exception", e);

            throw new FaultException<OrganizationServiceFault>(organizationServiceFault, e.Message);
        }
예제 #24
0
        private ExecuteMultipleResponse ExecuteInternal(ExecuteMultipleRequest request)
        {
            var settings = request.Settings;
            var response = new ExecuteMultipleResponse
            {
                Results =
                {
                    ["Responses"] = new ExecuteMultipleResponseItemCollection()
                }
            };

            for (int i = 0; i < request.Requests.Count; i++)
            {
                var childRequest = request.Requests[i];
                OrganizationServiceFault fault         = null;
                OrganizationResponse     childResponse = null;
                try
                {
                    if (childRequest.RequestName == "ExecuteMultiple")
                    {
                        throw new Exception("ExecuteMultipleRequest cannot contain an ExecuteMultipleRequest");
                    }

                    childResponse = ExecuteInternal((dynamic)childRequest);
                    if (!settings.ReturnResponses)
                    {
                        childResponse = null;
                    }
                }
                catch (NotImplementedException)
                {
                    throw;
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    response["IsFaulted"] = true;
                    fault = ex.Detail;
                    fault.ErrorDetails["CallStack"] = ex.StackTrace;
                    if (!settings.ContinueOnError)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    response["IsFaulted"] = true;
                    fault = new OrganizationServiceFault
                    {
                        Message      = ex.Message,
                        Timestamp    = DateTime.UtcNow,
                        ErrorDetails =
                        {
                            ["CallStack"] = ex.StackTrace
                        }
                    };
                    if (!settings.ContinueOnError)
                    {
                        break;
                    }
                }
                finally
                {
                    if (childResponse != null || fault != null)
                    {
                        response.Responses.Add(new ExecuteMultipleResponseItem
                        {
                            Fault        = fault,
                            RequestIndex = i,
                            Response     = childResponse
                        });
                    }
                }
            }
            return(response);
        }
        /// <summary>
        /// Disassembles the Exception into a readable block
        /// </summary>
        /// <param name="objException">Exception to work with</param>
        /// <param name="sw">Writer to write too</param>
        /// <param name="level">depth</param>
        /// <param name="lastErrorMsg">Last Writer to write too</param>
        private void GetExceptionDetail(object objException, StringBuilder sw, int level, StringBuilder lastErrorMsg)
        {
            if (objException == null)
            {
                return;
            }

            //if (objException is SoapException)
            //{
            //	SoapException soapEx = (SoapException)objException;
            //	FormatExceptionMessage(
            //	soapEx.Source != null ? soapEx.Source.ToString().Trim() : "Not Provided",
            //	soapEx.TargetSite != null ? soapEx.TargetSite.Name.ToString() : "Not Provided",
            //	string.IsNullOrEmpty(soapEx.Message) ? "Not Provided" : soapEx.Message.ToString().Trim(),
            //	string.IsNullOrEmpty(soapEx.StackTrace) ? "Not Provided" : soapEx.StackTrace.ToString().Trim()
            //	, sw, level);

            //	lastErrorMsg.Append(string.IsNullOrEmpty(soapEx.Message) ? "Not Provided" : soapEx.Message.ToString().Trim());

            //	if (lastErrorMsg.Length > 0 && soapEx.InnerException != null)
            //		lastErrorMsg.Append(" => ");

            //	level++;
            //	if (soapEx.InnerException != null)
            //		GetExceptionDetail(soapEx.InnerException, sw, level, lastErrorMsg);

            //}
            //else
            if (objException is FaultException <OrganizationServiceFault> )
            {
                FaultException <OrganizationServiceFault> OrgFault = (FaultException <OrganizationServiceFault>)objException;
                string ErrorDetail = GenerateOrgErrorDetailsInfo(OrgFault.Detail.ErrorDetails);
                FormatExceptionMessage(
                    OrgFault.Source != null ? OrgFault.Source.ToString().Trim() : "Not Provided",
                    OrgFault.TargetSite != null ? OrgFault.TargetSite.Name.ToString() : "Not Provided",
                    OrgFault.Detail != null ? string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\nTrace: {2}{3}", OrgFault.Detail.Message, OrgFault.Detail.ErrorCode, OrgFault.Detail.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}") :
                    string.IsNullOrEmpty(OrgFault.Message) ? "Not Provided" : OrgFault.Message.ToString().Trim(),
                    string.IsNullOrEmpty(OrgFault.StackTrace) ? "Not Provided" : OrgFault.StackTrace.ToString().Trim()
                    , sw, level);

                lastErrorMsg.Append(OrgFault.Detail != null ? OrgFault.Detail.Message :
                                    string.IsNullOrEmpty(OrgFault.Message) ? string.Empty : OrgFault.Message.ToString().Trim());

                if (lastErrorMsg.Length > 0 && (OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    lastErrorMsg.Append(" => ");
                }

                level++;
                if ((OrgFault.InnerException != null || OrgFault.Detail != null && OrgFault.Detail.InnerFault != null))
                {
                    GetExceptionDetail(OrgFault.Detail != null && OrgFault.Detail.InnerFault != null ? OrgFault.Detail.InnerFault : (object)OrgFault.InnerException,
                                       sw, level, lastErrorMsg);
                }

                return;
            }
            else
            {
                if (objException is OrganizationServiceFault)
                {
                    OrganizationServiceFault oFault = (OrganizationServiceFault)objException;
                    string ErrorDetail = GenerateOrgErrorDetailsInfo(oFault.ErrorDetails);
                    FormatOrgFaultMessage(
                        string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\nTrace: {2}{3}", oFault.Message, oFault.ErrorCode, oFault.TraceText, string.IsNullOrEmpty(ErrorDetail) ? "" : $"\n{ErrorDetail}"),
                        oFault.Timestamp.ToString(),
                        oFault.ErrorCode.ToString(),
                        string.IsNullOrEmpty(oFault.TraceText) ? "Not Provided" : oFault.TraceText.ToString().Trim(), sw, level);

                    level++;

                    lastErrorMsg.Append(oFault.Message);
                    if (lastErrorMsg.Length > 0 && oFault.InnerFault != null)
                    {
                        lastErrorMsg.Append(" => ");
                    }

                    if (oFault.InnerFault != null)
                    {
                        GetExceptionDetail(oFault.InnerFault, sw, level, lastErrorMsg);
                    }

                    return;
                }
                else
                {
                    if (objException is HttpOperationException httpOperationException)
                    {
                        JObject contentBody = JObject.Parse(httpOperationException.Response.Content);

                        FormatExceptionMessage(
                            httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
                            httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
                            string.IsNullOrEmpty(contentBody["error"]["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(contentBody["error"]["message"]?.ToString()).Trim(),
                            string.IsNullOrEmpty(contentBody["error"]["stacktrace"]?.ToString()) ? "Not Provided" : contentBody["error"]["stacktrace"]?.ToString().Trim()
                            , sw, level);

                        lastErrorMsg.Append(string.IsNullOrEmpty(httpOperationException.Message) ? "Not Provided" : httpOperationException.Message.ToString().Trim());

                        // WebEx currently only returns 1 leve of error.
                        var InnerError = contentBody["error"]["innererror"];
                        if (lastErrorMsg.Length > 0 && InnerError != null)
                        {
                            level++;
                            lastErrorMsg.Append(" => ");
                            FormatExceptionMessage(
                                httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
                                httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
                                string.IsNullOrEmpty(InnerError["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(InnerError["message"]?.ToString()).Trim(),
                                string.IsNullOrEmpty(InnerError["stacktrace"]?.ToString()) ? "Not Provided" : InnerError["stacktrace"]?.ToString().Trim()
                                , sw, level);
                        }
                    }
                    else
                    if (objException is Exception)
                    {
                        Exception generalEx = (Exception)objException;
                        FormatExceptionMessage(
                            generalEx.Source != null ? generalEx.Source.ToString().Trim() : "Not Provided",
                            generalEx.TargetSite != null ? generalEx.TargetSite.Name.ToString() : "Not Provided",
                            string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim(),
                            string.IsNullOrEmpty(generalEx.StackTrace) ? "Not Provided" : generalEx.StackTrace.ToString().Trim()
                            , sw, level);

                        lastErrorMsg.Append(string.IsNullOrEmpty(generalEx.Message) ? "Not Provided" : generalEx.Message.ToString().Trim());

                        if (lastErrorMsg.Length > 0 && generalEx.InnerException != null)
                        {
                            lastErrorMsg.Append(" => ");
                        }

                        level++;
                        if (generalEx.InnerException != null)
                        {
                            GetExceptionDetail(generalEx.InnerException, sw, level, lastErrorMsg);
                        }
                    }
                }
            }
            return;
        }