public MessageFault Serialize(FaultException faultException, out string action)
 {
     try
     {
         return this.faultFormatter.Serialize(faultException, out action);
     }
     catch (Exception e)
     {
         if (Fx.IsFatal(e))
         {
             throw;
         }
         action = null;
         return MessageFault.Default;
     }
 }
            public void IfAggregatedExceptionContainsInnerAggregateExceptionsFaultExceptionShouldContainAllExceptions()
            {
                try
                {
                    throw new AggregateException(new AggregateException(new TimeoutException()));
                }
                catch (AggregateException exception)
                {
                    Assert.DoesNotThrow(() => { new FaultException(exception); });

                    var sut = new FaultException(exception);
                    CollectionAssert.IsNotEmpty(sut.InnerExceptions, "Должны быть внутренние исключения.");
                    Assert.AreEqual(1, sut.InnerExceptions.Count, "Должно быть одно внутреннее исключение.");
                    Assert.IsNotEmpty(sut.InnerExceptions.First().InnerExceptions, "Внутренне исключение должно содержать исключения.");
                    Assert.AreEqual(1, sut.InnerExceptions.First().InnerExceptions.Count, "Внутренне исключение должно содержать одно внутреннее исключение.");
                    Assert.AreEqual(exception.InnerExceptions.First().InnerException.GetType().FullName, sut.InnerExceptions.First().InnerExceptions.First().Type);
                }
            }
            public void IfExceptionWIthAggregatedExceptionShouldContainException()
            {
                try
                {
                    var task = new Task<int>(
                        () =>
                            {
                                this.ThrowException();
                                return 0;
                            });
                    task.Start();
                    task.Wait(10);
                }
                catch (AggregateException exception)
                {
                    var sut = new FaultException(exception);

                    CollectionAssert.IsNotEmpty(sut.InnerExceptions, "Должны быть внутренние исключения.");
                    Assert.AreEqual(1, sut.InnerExceptions.Count, "Должно быть одно внутреннее исключение.");
                }
            }
        object Request(OperationDescription od, bool isAsync, ref object [] parameters, OperationContext context)
        {
            ClientOperation op = runtime.Operations [od.Name];

            object [] inspections = new object [runtime.MessageInspectors.Count];
            Message   req         = CreateRequest(op, parameters, context);

            for (int i = 0; i < inspections.Length; i++)
            {
                inspections [i] = runtime.MessageInspectors [i].BeforeSendRequest(ref req, this);
            }

            Message res = Request(req, OperationTimeout);

            if (res.IsFault)
            {
                var          resb  = res.CreateBufferedCopy(runtime.MaxFaultSize);
                MessageFault fault = MessageFault.CreateFault(resb.CreateMessage(), runtime.MaxFaultSize);
                var          conv  = OperationChannel.GetProperty <FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter(res.Version);
                Exception    ex;
                if (!conv.TryCreateException(resb.CreateMessage(), fault, out ex))
                {
                    if (fault.HasDetail)
                    {
                        Type detailType           = typeof(ExceptionDetail);
                        var  freader              = fault.GetReaderAtDetailContents();
                        DataContractSerializer ds = null;
                        foreach (var fci in op.FaultContractInfos)
                        {
                            if (res.Headers.Action == fci.Action || fci.Serializer.IsStartObject(freader))
                            {
                                detailType = fci.Detail;
                                ds         = fci.Serializer;
                                break;
                            }
                        }
                        if (ds == null)
                        {
                            ds = new DataContractSerializer(detailType);
                        }
                        var detail = ds.ReadObject(freader);
                        ex = (Exception)Activator.CreateInstance(typeof(FaultException <>).MakeGenericType(detailType), new object [] { detail, fault.Reason, fault.Code, res.Headers.Action });
                    }

                    if (ex == null)
                    {
                        ex = new FaultException(fault);
                    }
                }
                throw ex;
            }

            for (int i = 0; i < inspections.Length; i++)
            {
                runtime.MessageInspectors [i].AfterReceiveReply(ref res, inspections [i]);
            }

            if (!op.DeserializeReply)
            {
                return(res);
            }

            if (isAsync && od.EndMethod != null)
            {
                var endParams = od.EndMethod.GetParameters();
                parameters = new object [endParams.Length - 1];
            }

            return(op.Formatter.DeserializeReply(res, parameters));
        }
 public ParallelOperationFailure(TRequest request, FaultException <TFault> exception)
 {
     this.Request   = request;
     this.Exception = exception;
 }
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     if (!(error is FaultException))
     {
         LoggingExceptionDetails guidException = new LoggingExceptionDetails();
         FaultException<LoggingExceptionDetails> faultException = new FaultException<LoggingExceptionDetails>(guidException, new FaultReason(guidException.Message));
         fault = Message.CreateMessage(version, faultException.CreateMessageFault(), faultException.Action);
         this.LogMessage(error, guidException);
     }
 }
        /// <summary>
        /// Executes the specified service provider.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <exception cref="ArgumentNullException">serviceProvider is null</exception>
        /// <exception cref="InvalidPluginExecutionException"></exception>
        /// <exception cref="InvalidPluginExecutionException"></exception>
        /// <exception cref="InvalidPluginExecutionException"></exception>
        /// <exception cref="System.ArgumentNullException">serviceProvider is null</exception>
        /// <exception cref="Microsoft.Xrm.Sdk.InvalidPluginExecutionException"></exception>
        public void Execute(IServiceProvider serviceProvider)
        {
            var watch = Stopwatch.StartNew();

            try
            {
                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider is null");
                }

                // Obtain the tracing service from the service provider.
                cubeBase.LogSystem = new DetailedLog()
                {
                    TraceService = (ITracingService)serviceProvider.GetService(typeof(ITracingService))
                };

                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "Entered the Execute() method : {0}", this.GetType().ToString()));

                // Obtain the execution context from the service provider.
                cubeBase.Context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                // Use the factory to generate the Organization Service.
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                cubeBase.XrmService = serviceFactory.CreateOrganizationService(((IPluginExecutionContext)cubeBase.Context).UserId);

                cubeBase.BaseSystemObject = serviceProvider;

                Execute(cubeBase);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                cubeBase.LogSystem.CreateLog("The application terminated with an Organization Service Fault error.");
                cubeBase.LogSystem.CreateLog(string.Format("Timestamp: {0}", ex.Detail.Timestamp));
                cubeBase.LogSystem.CreateLog(string.Format("Code: {0}", ex.Detail.ErrorCode));
                cubeBase.LogSystem.CreateLog(string.Format("Message: {0}", ex.Detail.Message));
                cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}",
                                                           null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            catch (System.TimeoutException ex)
            {
                cubeBase.LogSystem.CreateLog("The application terminated with an timeout error.");
                cubeBase.LogSystem.CreateLog(string.Format("Message: {0}", ex.Message));
                cubeBase.LogSystem.CreateLog(string.Format("Stack Trace: {0}", ex.StackTrace));
                cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}",
                                                           null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message));

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            catch (System.Exception ex)
            {
                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "General Exception with message: {0}", ex.Message));
                if (ex.InnerException != null)
                {
                    cubeBase.LogSystem.CreateLog("Inner Exception Message:" + ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Timestamp: {0}", fe.Detail.Timestamp));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Code: {0}", fe.Detail.ErrorCode));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Message: {0}", fe.Detail.Message));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Trace: {0}", fe.Detail.TraceText));
                        cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));
                    }
                }

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            finally
            {
                watch.Stop();
                cubeBase.LogSystem.CreateLog(ContextWriter.Write((IPluginExecutionContext)cubeBase.Context));
                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "Finished the Execute() method : {0}", this.GetType().ToString()));
                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "Internal execution time: {0} ms", watch.ElapsedMilliseconds));
            }
        }
        internal static FaultException CreateDummyFaultException()
        {
            var exception = new FaultException(new FaultReason("reason"), new FaultCode("code"));

            return(exception);
        }
Example #9
0
        private static MessageFault CreateMessageFault(XmlObjectSerializer serializer, FaultException faultException, Type detailType)
        {
            if (detailType == null)
            {
                if (faultException.Fault != null)
                {
                    return(faultException.Fault);
                }
                return(MessageFault.CreateFault(faultException.Code, faultException.Reason));
            }
            Fx.Assert(serializer != null, "");

            Type operationFaultType = typeof(OperationFault <>).MakeGenericType(detailType);

            return((MessageFault)Activator.CreateInstance(operationFaultType, serializer, faultException));
        }
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_fundingcase")
                {
                    return;
                }

                FaultException ex1 = new FaultException();
                //  throw new InvalidPluginExecutionException("test", ex1);

                try
                {
                    //// Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    AutoNumbering autoNumbering = new AutoNumbering(entity, service);
                    String        caseNumber    = autoNumbering.getAutoNumber();

                    entity["gcbase_name"] = caseNumber;
                    service.Update(entity);
                    if (entity.Attributes.Contains("gcbase_amountsbyfiscalyearserver"))
                    {
                        char[] delimitedChar = { ';' };

                        Entity          fundingAmountByFY = new Entity("gcbase_fundingcaseamountbyfy");
                        string[]        yearlyAmounts     = entity.Attributes["gcbase_amountsbyfiscalyearserver"].ToString().Split(delimitedChar);
                        EntityReference fundCentre        = entity.GetAttributeValue <EntityReference>("gcbase_program");
                        foreach (string ya in yearlyAmounts)
                        {
                            fundingAmountByFY["gcbase_fundingcase"] = new EntityReference("gcbase_fundingcase", entity.Id);
                            //fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                            OptionSetValue fy             = new OptionSetValue();
                            var            indexForFY     = ya.IndexOf("Y");
                            var            indexForAmount = ya.IndexOf("-");
                            var            yearStr        = ya.Substring(indexForFY + 1, 4);
                            var            amountStr      = ya.Substring(indexForAmount + 1);
                            tracingService.Trace("year is:" + yearStr);
                            tracingService.Trace("amount is:" + amountStr);
                            Money amount = new Money(decimal.Parse(amountStr));
                            fy.Value = Int32.Parse(yearStr);
                            fundingAmountByFY["gcbase_fiscalyear"] = fy;
                            fundingAmountByFY["gcbase_amount"]     = amount;
                            fundingAmountByFY["gcbase_fundcentre"] = fundCentre;
                            tracingService.Trace("PostFundingCasePlugin: Creating the budget item.");
                            service.Create(fundingAmountByFY);
                            tracingService.Trace(ya);
                        }
                    }
                    if (entity.Attributes.Contains("gcbase_program"))
                    {
                        ColumnSet cols = new ColumnSet
                                         (
                            new String[] { "gcbase_fundingcaseriskrequired" }
                                         );

                        //program configuration options
                        var program = service.Retrieve("gcbase_fundcentre", entity.GetAttributeValue <EntityReference>("gcbase_program").Id, cols);
                        tracingService.Trace("there");
                        if (program.GetAttributeValue <Boolean>("gcbase_fundingcaseriskrequired"))
                        {
                            var            ratype    = new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_fundingcaseriskassessmenttype", "Initial", service);
                            OptionSetValue raTypeOpt = new OptionSetValue(ratype);

                            //create initial risk assessment - should be custom class since this will be reused by other plugins
                            if (!new RiskTemplate(null, service).generateRiskAssessment(entity, raTypeOpt))
                            {
                                throw new InvalidPluginExecutionException("The funding program is not fully configured therefore a funding case cannot be created yet", ex1);
                            }

                            //newRA.generateAssessment();
                        }


                        //var results = service.Retrieve("gcbase_fundcentre", entity.GetAttributeValue<Guid>("gcbase_program"), null);
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the FollowupPlugin plug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
Example #11
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(service);
            FaultException             ex1 = new FaultException();


            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                Entity entity     = (Entity)context.InputParameters["Target"];
                var    entityName = entity.LogicalName;

                QueryExpression qe = new QueryExpression("fp_preventduplicatefield");
                qe.Criteria.AddCondition("fp_name", ConditionOperator.Equal, entityName);
                qe.ColumnSet = new ColumnSet("fp_fieldnames");
                var fieldNames = service.RetrieveMultiple(qe).Entities.First().GetAttributeValue <string>("fp_fieldnames");

                char[] comma        = { ',' };
                var    fieldNameArr = fieldNames.Split(comma).ToList();

                //var publisherPrefix = entityName.Split('_')[0] + "_";
                QueryExpression qe1 = new QueryExpression();
                qe1.EntityName = entityName;
                qe1.ColumnSet  = new ColumnSet();
                foreach (string fieldName in fieldNameArr)
                {
                    string fn = fieldName.Trim();
                    qe1.ColumnSet.AddColumn(fn);

                    //MUST ADD IMAGE AT SOME POINT


                    if (context.MessageName.ToUpper() == "UPDATE")
                    {
                        var thisEntity = service.Retrieve(entityName, entity.Id, new ColumnSet(fn));

                        // throw new InvalidPluginExecutionException(thisEntity.Attributes[fn].ToString(), ex1);
                        if (thisEntity.Attributes[fn] is EntityReference)
                        {
                            qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, thisEntity.GetAttributeValue <EntityReference>(fn).Id);
                        }
                        if (thisEntity.Attributes[fn] is string)
                        {
                            qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, thisEntity.GetAttributeValue <string>(fn));
                        }
                    }
                    else
                    {
                        if (entity.Attributes[fn] is EntityReference)
                        {
                            qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, entity.GetAttributeValue <EntityReference>(fn).Id);
                        }
                        if (entity.Attributes[fn] is string)
                        {
                            qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, entity.GetAttributeValue <string>(fn));
                        }
                    }
                }


                if (service.RetrieveMultiple(qe1).Entities.Count() > 1)
                {
                    throw new InvalidPluginExecutionException("You cannot add a duplicate record", ex1);
                }
            }
        }
        public void SubscribeTest()
        {
            EndpointReferenceType subscriptionReference = null;
            int terminationTime = 10;

            RunTest <object>(
                () => null,
                () =>
            {
                Proxies.Event.Subscribe request = new Subscribe();
                request.InitialTerminationTime  = "PT10S";

                // Some endpoint reference. There is no information if the DUT must
                // immediately validate it.
                request.ConsumerReference               = new EndpointReferenceType();
                request.ConsumerReference.Address       = new AttributedURIType();
                request.ConsumerReference.Address.Value = _subscriberAddress;

                // request.Filter is null - CR 63

                SubscribeResponse response = null;

                bool retry = false;


                try
                {
                    response = Subscribe(request);
                }
                catch (FaultException exc)
                {
                    FaultException <UnacceptableInitialTerminationTimeFaultType> invalidTerminationTimeFault =
                        exc as FaultException <UnacceptableInitialTerminationTimeFaultType>;

                    if (invalidTerminationTimeFault != null)
                    {
                        LogStepEvent(string.Format("Exception of type FaultException<UnacceptableInitialTerminationTimeFaultType> received. Try to subscribe with new parameters"));
                        StepPassed();

                        string duration = string.Empty;
                        terminationTime = GetRecommendedDuration(invalidTerminationTimeFault, out duration);

                        retry = true;
                        request.InitialTerminationTime = duration;
                    }
                    else
                    {
                        //throw;
                        StepPassed();
                        return;
                    }
                }

                if (retry)
                {
                    response = Subscribe(request, "Retry subscribe");
                }

                subscriptionReference = response.SubscriptionReference;

                //
                // validate EndPointReference
                //
                Assert(subscriptionReference != null, "The DUT did not return SubscriptionReference",
                       "Check if the DUT returned SubscriptionReference");

                Assert(subscriptionReference.Address != null && subscriptionReference.Address.Value != null,
                       "SubscriptionReference does not contain address",
                       "Check if SubscriptionReference contains address");

                Assert(subscriptionReference.Address.Value.IsValidUrl(), "URL passed in SubscriptionReference is not valid",
                       "Check that URL specified is valid");


                Assert(response.CurrentTimeSpecified, "Current time is not specified",
                       "Check that CurrentTime is specified");
                Assert(response.TerminationTimeSpecified, "Termination time is not specified",
                       "Check that TerminationTime is specified");

                Assert(response.CurrentTime.AddSeconds(terminationTime) <= response.TerminationTime,
                       "TerminationTime < CurrentTime + InitialTerminationTime",
                       "Validate times");
            },
                (o) =>
            {
                if (subscriptionReference != null)
                {
                    if (_subscriptionManagerClient == null)
                    {
                        CreateSubscriptionManagerClient(subscriptionReference);
                    }
                    ReleaseSubscriptionManager(terminationTime * 1000);
                }
            });
        }
        public void RenewTest()
        {
            EndpointReferenceType subscriptionReference = null;
            bool subscribed      = false;
            int  terminationTime = 10;

            RunTest <object>(
                new Backup <object>(
                    () => { return(null); }),
                () =>
            {
                SubscribeResponse subscribeResponse = CreateStandardSubscription();

                if (subscribeResponse == null)
                {
                    return;
                }

                subscribed            = true;
                subscriptionReference = subscribeResponse.SubscriptionReference;

                Renew renew           = new Renew();
                renew.TerminationTime = "PT10S";

                RenewResponse renewResponse = null;
                bool retry = false;

                try
                {
                    renewResponse = Renew(renew);
                }
                catch (FaultException exc)
                {
                    FaultException <UnacceptableTerminationTimeFaultType> invalidTerminationTimeFault =
                        exc as FaultException <UnacceptableTerminationTimeFaultType>;

                    if (invalidTerminationTimeFault != null)
                    {
                        LogStepEvent(string.Format("Exception of type FaultException<UnacceptableTerminationTimeFaultType> received. Try to renew subscription with new parameters"));
                        StepPassed();

                        string duration = string.Empty;

                        terminationTime = GetRecommendedDuration <UnacceptableTerminationTimeFaultType>(invalidTerminationTimeFault, out duration);

                        retry = true;
                        renew.TerminationTime = duration;
                    }
                    else
                    {
                        throw;
                    }
                }

                if (retry)
                {
                    renewResponse = Renew(renew);
                }

                ValidateRenewResponse(renewResponse, terminationTime);

                DateTime requestTerminationTime = DateTime.UtcNow.AddSeconds(terminationTime);

                requestTerminationTime = new DateTime(requestTerminationTime.Year,
                                                      requestTerminationTime.Month,
                                                      requestTerminationTime.Day,
                                                      requestTerminationTime.Hour,
                                                      requestTerminationTime.Minute,
                                                      requestTerminationTime.Second,
                                                      requestTerminationTime.Kind);



                // TEST -->
                // requestTerminationTime = DateTime.Parse("2011-06-09T13:27:46Z").ToUniversalTime();
                // TEST <--

                string xsDateTime = requestTerminationTime.ToString("yyyy-MM-ddTHH:mm:ssZ");

                // TEST -->
                //xsDateTime = "2011-06-09T13:27:46Z";
                //requestTerminationTime = DateTime.Parse(xsDateTime);
                // <--

                renew.TerminationTime = xsDateTime;

                try
                {
                    renewResponse = Renew(renew, "Renew subscription - use xs:DateTime format for TerminationTime");
                }
                catch (FaultException exc)
                {
                    FaultException <UnacceptableTerminationTimeFaultType> invalidTerminationTimeFault =
                        exc as FaultException <UnacceptableTerminationTimeFaultType>;

                    if (invalidTerminationTimeFault != null)
                    {
                        LogStepEvent(string.Format("Exception of type FaultException<UnacceptableTerminationTimeFaultType> received. Try to renew subscription with new parameters"));
                        StepPassed();

                        string duration = string.Empty;

                        terminationTime = GetRecommendedDuration <UnacceptableTerminationTimeFaultType>(invalidTerminationTimeFault, out duration);

                        requestTerminationTime = DateTime.UtcNow.AddSeconds(terminationTime);
                        requestTerminationTime = new DateTime(requestTerminationTime.Year,
                                                              requestTerminationTime.Month,
                                                              requestTerminationTime.Day,
                                                              requestTerminationTime.Hour,
                                                              requestTerminationTime.Minute,
                                                              requestTerminationTime.Second,
                                                              requestTerminationTime.Kind);

                        xsDateTime = requestTerminationTime.ToString("yyyy-MM-ddTHH:mm:ssZ");

                        //LogStepEvent(string.Format("Send TerminationTime '{0}'", xsDateTime));

                        retry = true;
                        renew.TerminationTime = xsDateTime;
                    }
                    else
                    {
                        throw;
                    }
                }
                if (retry)
                {
                    renewResponse = Renew(renew);
                }

                ValidateRenewResponse(renewResponse, requestTerminationTime);
            },
                (o) =>
            {
                if (subscribed)
                {
                    if (subscriptionReference != null)
                    {
                        CreateSubscriptionManagerClient(subscriptionReference);
                    }
                    ReleaseSubscriptionManager(terminationTime * 1000);
                }
            });
        }
Example #14
0
            public void IfExceptionWithInnerExceptionShouldContainInnerException()
            {
                try
                {
                    this.GetType()
                        .GetMethod("ThrowException", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod)
                        .Invoke(this, new object[] { });
                }
                catch (TargetInvocationException ex)
                {
                    var sut = new FaultException(ex);

                    CollectionAssert.IsNotEmpty(sut.InnerExceptions, "Должны быть внутренние исключения.");
                    Assert.AreEqual(1, sut.InnerExceptions.Count, "Должно быть одно внутреннее исключение.");
                }
            }
Example #15
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);
        }
 private void ReplyFailure(RequestContext request, Message fault, string action, string reason, FaultCode code)
 {
     FaultException exception = new FaultException(reason, code);
     ErrorBehavior.ThrowAndCatch(exception);
     ErrorHandlerFaultInfo faultInfo = new ErrorHandlerFaultInfo(action);
     faultInfo.Fault = fault;
     bool replied, replySentAsync;
     ProvideFaultAndReplyFailure(request, exception, ref faultInfo, out replied, out replySentAsync);
     this.HandleError(exception, ref faultInfo);
 }
Example #17
0
        void changeAccountType(AccountType accountType)
        {
            if (ApplicationState.Current.ProfileInfo.Licence.AccountType > accountType)
            {
                int accountDiff = accountType - ApplicationState.Current.ProfileInfo.Licence.AccountType;
                int kara        = Math.Abs(accountDiff) * ApplicationState.Current.ProfileInfo.Licence.Payments.Kara;
                if (BAMessageBox.Ask(string.Format(ApplicationStrings.AccountTypePage_QChangeAccountToLower, kara)) == MessageBoxResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                if (BAMessageBox.Ask(string.Format(ApplicationStrings.AccountTypePage_QChangeAccountToHigher)) == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            progressBar.ShowProgress(true, ApplicationStrings.AccountTypePage_ChangingAccountType);
            updateButtons(false);
            var m = new ServiceManager <AsyncCompletedEventArgs>(delegate(BodyArchitectAccessServiceClient client1, EventHandler <AsyncCompletedEventArgs> operationCompleted)
            {
                var param         = new ProfileOperationParam();
                param.Operation   = ProfileOperation.AccountType;
                param.ProfileId   = ApplicationState.Current.SessionData.Profile.GlobalId;
                param.AccountType = accountType;

                client1.ProfileOperationAsync(ApplicationState.Current.SessionData.Token, param);
                client1.ProfileOperationCompleted -= operationCompleted;
                client1.ProfileOperationCompleted += operationCompleted;
            });

            m.OperationCompleted += (s, a) =>
            {
                FaultException <BAServiceException> serviceEx = a.Error as FaultException <BAServiceException>;
                if (serviceEx != null && serviceEx.Detail.ErrorCode == ErrorCode.ConsistencyException)
                {
                    updateButtons(true);
                    BAMessageBox.ShowError(ApplicationStrings.AccountTypePage_ErrNotEnoughPoints);
                    return;
                }
                if (a.Error != null)
                {
                    BugSenseHandler.Instance.SendExceptionAsync(a.Error);
                    updateButtons(true);
                    progressBar.ShowProgress(false);

                    BAMessageBox.ShowError(ApplicationStrings.AccountTypePage_ErrCannotChangeAccountType);
                    return;
                }


                refreshProfileInfo();
            };

            if (!m.Run())
            {
                updateButtons(true);
                progressBar.ShowProgress(false);
                if (ApplicationState.Current.IsOffline)
                {
                    BAMessageBox.ShowError(ApplicationStrings.ErrOfflineMode);
                }
                else
                {
                    BAMessageBox.ShowError(ApplicationStrings.ErrNoNetwork);
                }
            }
        }
Example #18
0
            public void IfExceptionWithoutInnerExceptionsShouldBeWithoutInnerExceptions()
            {
                var convertedException = new ArgumentException("Неверно задан параметр.");

                var sut = new FaultException(convertedException);

                CollectionAssert.IsEmpty(sut.InnerExceptions, "Список исключений дожен быть пустым.");
            }
        public static Fault CreateAccessDeniedFault(MessageVersion version)
        {
            FaultException exception = (FaultException)AuthorizationBehavior.CreateAccessDeniedFaultException();

            return(new Fault(version.Addressing.DefaultFaultAction, exception.Code, exception.Reason.ToString()));
        }
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(service);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_isosetup")
                {
                    return;
                }

                FaultException ex1 = new FaultException();
                //throw new InvalidPluginExecutionException("test", ex1);

                if (entity.Attributes.Contains("statuscode"))
                {
                    try
                    {
                        QueryExpression countries = new QueryExpression
                        {
                            EntityName = "gcbase_isocountry",
                            ColumnSet  = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                        };


                        QueryExpression subDivisions = new QueryExpression
                        {
                            EntityName = "gcbase_isosubdivision",
                            ColumnSet  = new ColumnSet("gcbase_name", "gcbase_countrycode"),
                        };

                        DataCollection <Entity> allCountries    = service.RetrieveMultiple(countries).Entities;
                        DataCollection <Entity> allSubDivisions = service.RetrieveMultiple(subDivisions).Entities;
                        foreach (Entity sd in allSubDivisions)
                        {
                            var countryCode = sd.GetAttributeValue <string>("gcbase_countrycode").ToString();
                            tracingService.Trace("ios plugin: {0}", countryCode);
                            QueryExpression countryRef = new QueryExpression
                            {
                                EntityName = "gcbase_isocountry",
                                ColumnSet  = new ColumnSet("gcbase_name", "gcbase_iso316612lettercode"),
                                Criteria   = new FilterExpression
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression {
                                            AttributeName = "gcbase_iso316612lettercode",
                                            Operator      = ConditionOperator.Equal,
                                            Values        =     { countryCode}
                                        }
                                    }
                                }
                            };
                            EntityCollection countryData = service.RetrieveMultiple(countryRef);
                            if (countryData.Entities.Count() > 0)
                            {
                                Entity          country    = (Entity)countryData.Entities.FirstOrDefault();
                                EntityReference isoCountry = new EntityReference("gcbase_isocountry", country.Id);
                                sd["gcbase_isocountry"] = isoCountry;
                                ctx.Attach(sd);
                                ctx.UpdateObject(sd);
                                ctx.SaveChanges();
                            }
                        }
                        ;
                    }

                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the IOS Setup plug-in.", ex);
                    }

                    catch (Exception ex)
                    {
                        tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
Example #21
0
        /// <summary>
        /// Standard Main() method used by most SDK samples.
        /// </summary>
        /// <param name="args"></param>
        static public void Main(string[] args)
        {
            try
            {
                // Obtain connection configuration information for the Microsoft Dynamics
                // CRM organization web service.
                String connectionString = GetServiceConfiguration();

                if (connectionString != null)
                {
                    SimplifiedConnection app = new SimplifiedConnection();
                    app.Run(connectionString, true);
                }
            }

            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }

            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #22
0
 /// <summary>
 /// Fault validation method with standard signature.
 /// For these test cases does nothing.
 /// </summary>
 /// <param name="fault">Exception (null if no exception).</param>
 /// <param name="reason">Validation text result.</param>
 /// <returns></returns>
 protected bool ValidateFault(FaultException fault, out string reason)
 {
     reason = string.Empty;
     return(true);
 }
Example #23
0
            public object Invoke(object instance, object[] inputs, out object[] outputs)
            {
                outputs = EmptyArray <object> .Allocate(0);

                Message message = inputs[0] as Message;

                if (message == null)
                {
                    return(null);
                }

                string action = message.Headers.Action;

                //if (DiagnosticUtility.ShouldTraceInformation)
                //{
                //    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.UnhandledAction,
                //        SR.TraceCodeUnhandledAction,
                //        new StringTraceRecord("Action", action),
                //        this, null, message);
                //}

                FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
                                                                 message.Version.Addressing.Namespace);
                string      reasonText = SR.Format(SR.SFxNoEndpointMatchingContract, action);
                FaultReason reason     = new FaultReason(reasonText);

                FaultException exception = new FaultException(reason, code);

                ErrorBehavior.ThrowAndCatch(exception);

                ServiceChannel serviceChannel = OperationContext.Current.InternalServiceChannel;

                OperationContext.Current.OperationCompleted +=
                    delegate(object sender, EventArgs e)
                {
                    ChannelDispatcher channelDispatcher = dispatchRuntime.ChannelDispatcher;
                    if (!channelDispatcher.HandleError(exception) && serviceChannel.HasSession)
                    {
                        try
                        {
                            var helper = new TimeoutHelper(ChannelHandler.CloseAfterFaultTimeout);
                            serviceChannel.CloseAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            channelDispatcher.HandleError(ex);
                        }
                    }
                };

                if (dispatchRuntime.shared.EnableFaults)
                {
                    MessageFault fault = MessageFault.CreateFault(code, reason, action);
                    return(Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultFaultAction));
                }
                else
                {
                    OperationContext.Current.RequestContext.CloseAsync().GetAwaiter().GetResult();
                    OperationContext.Current.RequestContext = null;
                    return(null);
                }
            }
Example #24
0
        static void Main(string[] args)
        {
            try
            {
                string connectionString = Properties.Settings.Default.CrmConnectionString;
                using (OrganizationServiceProxy orgSvc = CrmConnectorUtil.Connect(connectionString) as OrganizationServiceProxy)
                {
                    // This statement is required to enable early-bound type support.
                    orgSvc.EnableProxyTypes();

                    FunctionType functionType = Prompter.ChooseFunction();
                    switch (functionType)
                    {
                    case FunctionType.ShowSolutionDependencies:
                    {
                        new SolutionComponentDependencyReport(orgSvc).Create();
                        break;
                    }

                    case FunctionType.MarkAttributesAsDepricated:
                    {
                        var reporter = new AttributeNoDependencyReport(orgSvc);
                        IList <ComponentInfo> componentInfos = reporter.Find();

                        bool prompt     = Prompter.YesNo("Prompt before marking depricated", true);
                        var  depricator = new AttributeDeprecator(orgSvc, prompt);
                        depricator.Process(componentInfos);

                        break;
                    }

                    case FunctionType.ShowAttributesWithNoDependencies:
                    {
                        var reporter = new AttributeNoDependencyReport(orgSvc);
                        IList <ComponentInfo> componentInfos = reporter.Find();
                        break;
                    }

                    case FunctionType.ShowGlobalOptionSetDependecies:
                    {
                        new GlobalOptionSetDependecyReport(orgSvc).Create();
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException($"Function type {functionType} is not implemented");
                    }
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}", ex.InnerException.Message ?? "No Inner Fault");
            }
            catch (Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <OrganizationServiceFault> fe = ex.InnerException
                                                                   as FaultException <OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.
            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #25
0
        public static void CrearProxyAuxiliar(string usuario, string password, ref ISvcAuxdSWin servicio, string servidor)
        {
            var host = Properties.Settings.Default.HostAuxiliar;

            try
            {
                _factoryAuxiliar = new ChannelFactory <ISvcAuxdSWin>(host);
                Ayudas.SetDataContractSerializerBehavior(_factoryAuxiliar.Endpoint.Contract);
                if (_factoryAuxiliar.Credentials != null)
                {
                    _factoryAuxiliar.Credentials.UserName.UserName = usuario;
                    _factoryAuxiliar.Credentials.UserName.Password = password;
                }
                if (servidor == null)
                {
                    servicio = _factoryAuxiliar.CreateChannel();
                }
                else
                {
                    var abs = _factoryAuxiliar.Endpoint.Address.Uri.AbsolutePath;
                    EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("Prueba");
                    var strUri           = string.Format("http://{0}{1}", servidor, abs);
                    Uri uri     = new Uri(strUri);
                    var address = new EndpointAddress(uri, spn);
                    servicio = _factoryAuxiliar.CreateChannel(address);
                }
                //servicio = _factoryAuxiliar.CreateChannel();
            }
            catch (CommunicationException e)
            {
                Abort((IChannel)servicio, _factoryAuxiliar);

                // if there is a fault then print it out
                FaultException fe  = null;
                Exception      tmp = e;
                while (tmp != null)
                {
                    fe = tmp as FaultException;
                    if (fe != null)
                    {
                        break;
                    }
                    tmp = tmp.InnerException;
                }
                if (fe != null)
                {
                    string msgError = string.Format("Ha ocurrido un error en el Servidor {0} ",
                                                    fe.CreateMessageFault().Reason.GetMatchingTranslation().Text);
                    msgError += Environment.NewLine;
                    ManejoExcepciones.ShowException(msgError, "Error de Aplicación", "Error de Aplicación");
                }
                else
                {
                    string msgError = string.Format("Solicitud erronea {0} ", e);
                    msgError += Environment.NewLine;
                    ManejoExcepciones.ShowException(msgError, "Error de Aplicación", "Error de Aplicación");
                }
            }
            catch (TimeoutException)
            {
                Abort((IChannel)servicio, _factoryAuxiliar);
                string msgError = "Se ha excedido el tiempo de espera";
                msgError += Environment.NewLine;
                ManejoExcepciones.ShowException(msgError, "Error de Aplicación", "Error de Aplicación");
            }
            catch (Exception e)
            {
                Abort((IChannel)servicio, _factoryAuxiliar);
                string msgError = string.Format("Error inesperado en la solicitud {0} ", e);
                msgError += Environment.NewLine;
                ManejoExcepciones.ShowException(msgError, "Error de Aplicación", "Error de Aplicación");
            }
        }
 public ParallelOrganizationOperationFailure(TRequest request, FaultException <OrganizationServiceFault> fault)
     : base(request, fault)
 {
 }
Example #27
0
 public static void AssertDetailIsNotNull <T>(this FaultException <T> arg)
 {
     ArgsCheck.DetailIsNotNull(arg);
     //$ $END$
 }
Example #28
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("spkl Task Runner v" + Assembly.GetEntryAssembly().GetName().Version + "\tTasks v" + Assembly.GetAssembly(typeof(SparkleXrm.Tasks.BaseTask)).GetName().Version);

            Console.ForegroundColor = ConsoleColor.Gray;
            bool            error     = false;
            CommandLineArgs arguments = null;

            try
            {
                arguments = CommandLine.Parse <CommandLineArgs>();

                Run(arguments);
            }
            catch (CommandLineException exception)
            {
                Console.WriteLine(exception.ArgumentHelp.Message);
                Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth));
            }
            catch (SparkleTaskException ex)
            {
                Console.WriteLine(ex.Message);
                error = true;
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine(ex.StackTrace);

                if (!string.IsNullOrEmpty(ex.Detail.TraceText))
                {
                    Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                }
                if (ex.Detail.InnerFault != null)
                {
                    Console.WriteLine("Inner Fault: {0}",
                                      null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (System.TimeoutException ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner Fault: {0}",
                                      null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (System.Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine(ex.StackTrace);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        if (!string.IsNullOrEmpty(fe.Detail.TraceText))
                        {
                            Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        }
                        if (fe.Detail.InnerFault != null)
                        {
                            Console.WriteLine("Inner Fault: {0}",
                                              null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                        }
                    }
                }
                error = true;
                Console.ForegroundColor = ConsoleColor.White;
            }
            finally
            {
                if (error)
                {
                    Environment.ExitCode = 1;
                }
            }
            if (arguments != null && arguments.WaitForKey == true)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
            Console.ForegroundColor = ConsoleColor.Gray;
        }
Example #29
0
        /// <summary>
        /// Set "Session" instance to CurrentSession
        /// </summary>
        /// <param name="sessionVariable">Session</param>
        /// <param name="callback">True/False</param>
        public void SetSession(Session sessionVariable, Action <bool?> callback)
        {
            SessionOperationsClient client = new SessionOperationsClient();

            client.Endpoint.Behaviors.Add(new CookieBehavior());
            client.SetSessionAsync(sessionVariable);
            client.SetSessionCompleted += (se, e) =>
            {
                if (e.Error == null)
                {
                    if (callback != null)
                    {
                        callback(e.Result);
                    }
                }
                else if (e.Error is FaultException <GreenField.ServiceCaller.SessionDefinitions.ServiceFault> )
                {
                    FaultException <GreenField.ServiceCaller.SessionDefinitions.ServiceFault> fault
                        = e.Error as FaultException <GreenField.ServiceCaller.SessionDefinitions.ServiceFault>;
                    Prompt.ShowDialog(fault.Reason.ToString(), fault.Detail.Description, MessageBoxButton.OK);
                    if (callback != null)
                    {
                        callback(null);
                    }
                }
                else
                {
                    Prompt.ShowDialog(e.Error.Message, e.Error.GetType().ToString(), MessageBoxButton.OK);
                    if (callback != null)
                    {
                        callback(null);
                    }
                }
            };
        }
Example #30
0
 public static bool IsA(this FaultException exception, FaultFactory factory)
 {
     return(factory.Check(exception));
 }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            Guid guid = Guid.Empty;

            if (correlationState is Guid)
            {
                guid = (Guid)correlationState;
            }

            // This trace is included in the user trace.
            ServiceContext.Logger.TraceEvent(
                TraceEventType.Verbose,
                0,
                "[HpcServiceHost]: Response is sent back. IsFault = {0}",
                reply.IsFault);

            RuntimeTraceHelper.TraceEvent(
                TraceEventType.Verbose,
                "[HpcServiceHost]: Response {0} is sent back. IsFault = {1}",
                guid,
                reply.IsFault);

            if (this.propagateActivity)
            {
                System.Diagnostics.Trace.CorrelationManager.ActivityId = Guid.Empty;
            }

            if (this.hostWrapper.EnableMessageLevelPreemption)
            {
                // If the message is skipped, reply a fault message to the broker.
                if (this.hostWrapper.SkippedMessageIds.Contains(guid))
                {
                    this.hostWrapper.SkippedMessageIds.Remove(guid);

                    // For Service_Preempted error, reuse SessionFault.reason property to pass "processing message count" to the broker.
                    int          messageCount = this.hostWrapper.ProcessingMessageIds.Count;
                    SessionFault fault        = new SessionFault(SOAFaultCode.Service_Preempted, messageCount.ToString());

                    FaultException faultException = new FaultException <SessionFault>(fault, string.Empty, null, SessionFault.Action);
                    reply = GenerateFaultMessage(guid, reply.Headers.MessageVersion, faultException);
                }
                else if (this.hostWrapper.ProcessingMessageIds.Contains(guid))
                {
                    this.hostWrapper.ProcessingMessageIds.Remove(guid);

                    // The service host receives the cancel event when the request is being processed, so add a header to notice the broker.
                    if (this.hostWrapper.ReceivedCancelEvent)
                    {
                        // Use the header to pass "processing message count" to the broker.
                        int messageCount = this.hostWrapper.ProcessingMessageIds.Count;
                        reply.Headers.Add(MessageHeader.CreateHeader(Constant.MessageHeaderPreemption, Constant.HpcHeaderNS, messageCount));
                    }
                }
                else
                {
                    // If the message is not in above two lists, the message doesn't come into the invoker. No need to change its response.
                }
            }

            if (this.hostWrapper.AllMessageIds.Contains(guid))
            {
                this.hostWrapper.AllMessageIds.Remove(guid);
                lock (this.hostWrapper.AllMessageIds.SyncRoot)
                {
                    if (this.hostWrapper.AllMessageIds.Count == 0)
                    {
                        this.hostWrapper.SerivceHostIdleTimer?.Change(this.hostWrapper.ServiceHostIdleTimeout, Timeout.Infinite);
                        this.hostWrapper.ServiceHangTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                    else
                    {
                        this.hostWrapper.ServiceHangTimer?.Change(this.hostWrapper.ServiceHangTimeout, Timeout.Infinite);
                    }
                }
            }
        }
Example #32
0
        /// <summary>
        /// Validates fault for invalid topic filter.
        /// </summary>
        /// <param name="fault"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        protected bool ValidateInvalidTopicFilterFault(FaultException fault, out string reason)
        {
            if (fault == null)
            {
                reason = "No SOAP fault received.";
                return(false);
            }

            //[12.03.2013] AKS: added checking that we got exception of known type(i.e. described using System.ServiceModel.FaultContractAttribute)
            if (!validateFaultExceptionType(fault, out reason))
            {
                return(false);
            }

            var invalidFilterFault = fault as FaultException <InvalidFilterFaultType>;

            if (invalidFilterFault != null)
            {
                if (invalidFilterFault.Detail == null)
                {
                    reason = "Fault received is of type FaultException<InvalidFilterFaultType>, but Details field is null";
                    return(false);
                }
                if (!ValidateBaseFault(invalidFilterFault.Detail, out reason))
                {
                    return(false);
                }
                // Timestamp format is validated when a fault is being deserialized. So here it should be valid.
            }

            var topicNotSupportedFault = fault as FaultException <TopicNotSupportedFaultType>;

            if (topicNotSupportedFault != null)
            {
                if (topicNotSupportedFault.Detail == null)
                {
                    reason = "Fault received is of type FaultException<TopicNotSupportedFaultType>, but Details field is null";
                    return(false);
                }
                if (!ValidateBaseFault(topicNotSupportedFault.Detail, out reason))
                {
                    return(false);
                }
                // Timestamp format is validated when a fault is being deserialized. So here it should be valid.
            }

            var invalidTopicExpressionFault = fault as FaultException <InvalidTopicExpressionFaultType>;

            if (invalidTopicExpressionFault != null)
            {
                if (invalidTopicExpressionFault.Detail == null)
                {
                    reason = "Fault received is of type FaultException<InvalidTopicExpressionFaultType>, but Details field is null";
                    return(false);
                }
                if (!ValidateBaseFault(invalidTopicExpressionFault.Detail, out reason))
                {
                    return(false);
                }
                // Timestamp format is validated when a fault is being deserialized. So here it should be valid.
            }

            if (null == invalidFilterFault && null == topicNotSupportedFault && null == invalidTopicExpressionFault)
            {
                LogStepEvent("Warning: Fault received is neither  FaultException<InvalidFilterFaultType> nor FaultException<TopicNotSupportedFaultType> nor FaultException<InvalidTopicExpressionFaultType>");
            }

            reason = string.Empty;
            return(true);
        }
        /// <summary>
        /// Build a fault message by the input info.
        /// </summary>
        /// <param name="messageId">message id</param>
        /// <param name="version">message version</param>
        /// <param name="faultException">fault exception</param>
        /// <returns>fault message</returns>
        private static Message GenerateFaultMessage(Guid messageId, MessageVersion version, FaultException faultException)
        {
            UniqueId relatesTo = null;

            if (messageId != null)
            {
                relatesTo = new UniqueId(messageId);
            }

            MessageFault fault        = faultException.CreateMessageFault();
            Message      faultMessage = Message.CreateMessage(version, fault, faultException.Action);

            if (relatesTo != null && version.Addressing == AddressingVersion.WSAddressing10)
            {
                // Only add relatesTo header to WSAddressing messages
                faultMessage.Headers.RelatesTo = relatesTo;
            }

            return(faultMessage);
        }
Example #34
0
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(service);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_fundcentre")
                {
                    return;
                }

                FaultException ex1 = new FaultException();
                //throw new InvalidPluginExecutionException("test", ex1);

                if (entity.Attributes.Contains("gcbase_estimatedannualbudget") && entity.Attributes.Contains("gcbase_startdate") && entity.Attributes.Contains("gcbase_enddate"))
                {
                    try
                    {
                        //create budget lines
                        //throw new InvalidPluginExecutionException("testing", ex1);
                        int[] fiscalYears = new FiscalYear(entity.GetAttributeValue <DateTime>("gcbase_startdate"), entity.GetAttributeValue <DateTime>("gcbase_enddate")).getFiscalYears();

                        QueryExpression existingFundCentreBudgets = new QueryExpression
                        {
                            EntityName = "gcbase_fundcentrebudget",
                            ColumnSet  = new ColumnSet("gcbase_fundcentre", "gcbase_fiscalyear"),
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression {
                                        AttributeName = "gcbase_fundcentre",
                                        Operator      = ConditionOperator.Equal,
                                        Values        =     { entity.Id}
                                    }
                                }
                            }
                        };

                        DataCollection <Entity> fundCentreBudgetsToDelete = service.RetrieveMultiple(existingFundCentreBudgets).Entities;

                        if (fundCentreBudgetsToDelete.Count > 0)
                        {
                            // here we should validate if we have projects pending instead of deleting budgets

                            var currentYears = fundCentreBudgetsToDelete.Select(s => (int)s.GetAttributeValue <OptionSetValue>("gcbase_fiscalyear").Value).ToArray();
                            var newYears     = fiscalYears.ToArray();
                            //newYears.Except(currentYears);

                            var illegalYears = currentYears.Except(newYears);

                            if (illegalYears.Count() > 0)
                            {
                                throw new InvalidPluginExecutionException(@"Cannot save your new start and end dates because there are budgets entered in
                                        fiscal years that fall outside of those dates. If you want to revise the dates please first delete the budgets in 
                                        fiscal years: " + string.Join("-", illegalYears) + " and try again!", ex1);
                            }
                            else
                            {
                                foreach (Entity fcb in fundCentreBudgetsToDelete)
                                {
                                    service.Delete("gcbase_fundcentrebudget", fcb.Id);
                                }
                            }
                        }

                        Array    values = Enum.GetValues(typeof(goal_fiscalyear));
                        string[] fys    = new string[fiscalYears.Count()];
                        int      index  = 0;

                        //throw new InvalidPluginExecutionException("testing", ex1);

                        //EntityReference fundRef = new EntityReference("gcbase_fund", preEntity.GetAttributeValue<EntityReference>("gcbase_fund").Id);
                        var fundEntity      = service.Retrieve("gcbase_fund", entity.GetAttributeValue <EntityReference>("gcbase_fund").Id, new ColumnSet("gcbase_name", "gcbase_fundid", "gcbase_fundtype"));
                        var fundTypeEntity  = service.Retrieve("gcbase_fundtype", fundEntity.GetAttributeValue <EntityReference>("gcbase_fundtype").Id, new ColumnSet("gcbase_name"));
                        var budgetEntryName = entity.GetAttributeValue <string>("gcbase_name") + "-" + fundEntity.GetAttributeValue <string>("gcbase_name") + "-" + fundTypeEntity.GetAttributeValue <string>("gcbase_name");
                        //  throw new InvalidPluginExecutionException(fiscalYears.Count().ToString(), ex1);
                        foreach (int year in fiscalYears)
                        {
                            var amount = entity.GetAttributeValue <Money>("gcbase_estimatedannualbudget");

                            if (amount.Value > 0)
                            {
                                Entity fundCentreBudget = new Entity("gcbase_fundcentrebudget");
                                // fundCentreBudget.Id = Guid.NewGuid();
                                fundCentreBudget["gcbase_amount"] = amount;
                                fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                                OptionSetValue fy = new OptionSetValue();
                                fy.Value = year;
                                fundCentreBudget["gcbase_fiscalyear"] = fy;

                                EntityReference fundCentre = new EntityReference("gcbase_fundcentre", entity.Id);
                                fundCentreBudget["gcbase_fundcentre"] = fundCentre;
                                fundCentreBudget["gcbase_name"]       = budgetEntryName + "-" + fy.Value;
                                // ctx.Attach(fundCentreBudget)
                                ctx.AddObject(fundCentreBudget);
                                ctx.SaveChanges();
                            }

                            index++;
                        }
                    }

                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the PostFundCentreCreate plug-in.", ex);
                    }

                    catch (Exception ex)
                    {
                        tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
Example #35
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;
        }
Example #36
0
        /// <summary>
        /// Standard Main() method used by most SDK samples.
        /// </summary>
        /// <param name="args"></param>
        static public void Main(string[] args)
        {
            try
            {
                // Obtain the target organization's Web address and client logon
                // credentials from the user.
                ServerConnection serverConnect        = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                QueryWorkingHoursOfMultipleUsers app = new QueryWorkingHoursOfMultipleUsers();
                app.Run(config, true);
            }

            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                          as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        /// <summary>
        /// Executes the specified execution context.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        /// <exception cref="System.ArgumentNullException">ExecutionContext is null</exception>
        /// <exception cref="Microsoft.Xrm.Sdk.InvalidPluginExecutionException">
        /// </exception>
        protected override void Execute(CodeActivityContext executionContext)
        {
            CubeBase cubeBase = new CubeBase();

            try
            {
                if (executionContext == null)
                {
                    throw new ArgumentNullException("ExecutionContext is null");
                }

                // Obtain the tracing service from the service provider.
                cubeBase.LogSystem = new DetailedLog()
                {
                    TraceService = executionContext.GetExtension <ITracingService>()
                };

                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "Entered the Execute() method : {0}", this.GetType().ToString()));

                // Obtain the execution context from the service provider.
                cubeBase.Context = executionContext.GetExtension <IWorkflowContext>();

                // Use the factory to generate the Organization Service.
                IOrganizationServiceFactory ServiceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                cubeBase.XrmService = ServiceFactory.CreateOrganizationService(((IWorkflowContext)cubeBase.Context).UserId);

                cubeBase.BaseSystemObject = executionContext;

                Execute(cubeBase);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                cubeBase.LogSystem.CreateLog("The application terminated with an Organization Service Fault error.");
                cubeBase.LogSystem.CreateLog(string.Format("Timestamp: {0}", ex.Detail.Timestamp));
                cubeBase.LogSystem.CreateLog(string.Format("Code: {0}", ex.Detail.ErrorCode));
                cubeBase.LogSystem.CreateLog(string.Format("Message: {0}", ex.Detail.Message));
                cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}",
                                                           null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            catch (System.TimeoutException ex)
            {
                cubeBase.LogSystem.CreateLog("The application terminated with an timeout error.");
                cubeBase.LogSystem.CreateLog(string.Format("Message: {0}", ex.Message));
                cubeBase.LogSystem.CreateLog(string.Format("Stack Trace: {0}", ex.StackTrace));
                cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}",
                                                           null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message));

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            catch (System.Exception ex)
            {
                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "General Exception with message: {0}", ex.Message));
                if (ex.InnerException != null)
                {
                    cubeBase.LogSystem.CreateLog("Inner Exception Message:" + ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Timestamp: {0}", fe.Detail.Timestamp));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Code: {0}", fe.Detail.ErrorCode));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Message: {0}", fe.Detail.Message));
                        cubeBase.LogSystem.CreateLog(string.Format("Fault Exception Trace: {0}", fe.Detail.TraceText));
                        cubeBase.LogSystem.CreateLog(string.Format("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));
                    }
                }

                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
            finally
            {
                cubeBase.LogSystem.CreateLog(string.Format(CultureInfo.InvariantCulture, "Finished the Execute() method : {0}", this.GetType().ToString()));
            }
        }