Beispiel #1
0
        public Fault(FaultException e) : base(e.Reason.ToString(), e)
        {
            this.Code = "qc:E502"; // 502 : by default a bad gateway

            if (e.Code.SubCode != null)
            {
                Code = formatFaultCode(e.Code.SubCode);
            }

            if (e.Code.SubCode.SubCode != null)
            {
                SubCode = formatFaultCode(e.Code.SubCode.SubCode);
            }

            MessageFault msgFault = e.CreateMessageFault();

            if (msgFault.HasDetail)
            {
                MessageInserts = msgFault.GetReaderAtDetailContents().ReadOuterXml();
                XmlReader reader = msgFault.GetReaderAtDetailContents();
                if (reader.ReadToFollowing("messageInserts"))
                {
                    MessageInserts = reader.ReadOuterXml();
                }
            }
        }
Beispiel #2
0
        public Fault(FaultException e) : base(e.Reason.ToString(), e)
        {
            if (e.Code.SubCode != null)
            {
                Code = e.Code.SubCode.Name;
            }
            else
            {
                Code = "502";
            }

            if (e.Code.SubCode.SubCode != null)
            {
                SubCode = e.Code.SubCode.SubCode.Name;
            }

            MessageFault msgFault = e.CreateMessageFault();

            if (msgFault.HasDetail)
            {
                MessageInserts = msgFault.GetReaderAtDetailContents().ReadOuterXml();
                XmlReader reader = msgFault.GetReaderAtDetailContents();
                if (reader.ReadToFollowing("messageInserts"))
                {
                    MessageInserts = reader.ReadOuterXml();
                }
            }
        }
Beispiel #3
0
        public static AdwsFault ConstructFault(Message response)
        {
            AdwsFault     adwsFault;
            MessageBuffer buffer       = AdwsMessage.MessageToBuffer(response);
            MessageFault  messageFault = MessageFault.CreateFault(AdwsMessage.BufferToMessage(buffer), 0x500000);
            object        obj          = null;

            if (messageFault.HasDetail)
            {
                try
                {
                    string str  = string.Concat(messageFault.Code.SubCode.Namespace, ":", messageFault.Code.SubCode.Name);
                    Type   item = (Type)AdwsFaultUtil._faultSubCodeType[str];
                    if (item != null)
                    {
                        XmlReader     readerAtDetailContents = messageFault.GetReaderAtDetailContents();
                        XmlSerializer xmlSerializer          = new XmlSerializer(item);
                        obj = xmlSerializer.Deserialize(readerAtDetailContents);
                    }
                }
                catch (Exception exception)
                {
                }
            }
            if (obj == null)
            {
                adwsFault = new AdwsFault(messageFault);
            }
            else
            {
                adwsFault = new AdwsFault(messageFault, obj);
            }
            return(adwsFault);
        }
        public async void EditVideoAsync(VideoSubmition v)
        {
            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.AccessKey, _client.InnerChannel))
                {
                    await this._client.EditVideoAsync(v, null, null);
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
        }
        public IAsyncOperation <string> DummyEchoAsync(string echoStr)
        {
            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    return(_client
                           .DummyEchoAsync(echoStr)
                           .ContinueWith(t => t.Result.DummyEchoResult)
                           .AsAsyncOperation());
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            throw new Exception("Request cannot be fulfilled");
        }
 private static void LogFaultException(FaultException ex)
 {
     if (ex == null)
     {
         return;
     }
     try
     {
         TraceHelper.WriteError("Fault Exception");
         TraceHelper.WriteError("Fault Message: {0}", ex.Message);
         TraceHelper.WriteError("Fault Action: {0}", ex.Action);
         TraceHelper.WriteError("Fault Code: {0}-{1}", ex.Code.Name, ex.Code);
         TraceHelper.WriteError("Fault Reason: {0}", ex.Reason);
         MessageFault fault = ex.CreateMessageFault();
         if (fault.HasDetail)
         {
             XmlReader reader = fault.GetReaderAtDetailContents();
             if (reader != null && reader.Name == "ExceptionDetail")
             {
                 var detail = fault.GetDetail <ExceptionDetail>();
                 if (detail != null)
                 {
                     TraceHelper.WriteError("-Detail Message: {0}", detail.Message);
                     TraceHelper.WriteError("-Detail Stack: {0}", detail.StackTrace);
                 }
             }
         }
     }
     catch (Exception e)
     {
         TraceHelper.WriteError("Error handling Fault Exception: {0}", e.Message);
     }
 }
        static public bool TryCreateFault(Message message, MessageFault fault, out MakeConnectionMessageFault wsmcFault)
        {
            // all WS-MakeConnection faults are receiver faults
            if (!fault.Code.IsReceiverFault)
            {
                wsmcFault = null;
                return(false);
            }

            if ((fault.Code.SubCode == null) ||
                (fault.Code.SubCode.Namespace != MakeConnectionConstants.Namespace))
            {
                wsmcFault = null;
                return(false);
            }

            XmlDictionaryReader detailReader = null;
            string subcodeName = fault.Code.SubCode.Name;

            if (fault.HasDetail)
            {
                detailReader = fault.GetReaderAtDetailContents();
            }

            wsmcFault = CreateMakeConnectionFault(message, fault.Code, subcodeName, fault.Reason, detailReader);
            return(wsmcFault != null);
        }
Beispiel #8
0
        // TO DO: Add this method to SellBitcoins
        private async void GetQuote()
        {
            try
            {
                // Gets a quote for bitcoins - Not a balance.  Bad Method Name - TODO

                FiatAmount = Convert.ToDecimal(txtAmount.Text);

                // TODO: Refresh Service Reference
                //      BitcoinAmount = await client.GetBitcoinAmountAsync(FiatAmount, "AUD");

                Price = BitcoinAmount / FiatAmount;

                txtBitcoins.Text = BitcoinAmount.ToString();

                txtRate.Text = Price.ToString();
            }
            catch (FaultException ex)
            {
                string       msg   = "FaultException: " + ex.Message;
                MessageFault fault = ex.CreateMessageFault();
                if (fault.HasDetail == true)
                {
                    System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
                    if (reader.Name == "ExceptionDetail")
                    {
                        ExceptionDetail detail = fault.GetDetail <ExceptionDetail>();
                        msg += "\n\nStack Trace: " + detail.StackTrace;
                    }
                }
                MessageBox.Show(msg);
            }
        }
        public static Exception GetExceptionFromFaultMessage(MessageFault fault)
        {
            if (fault.Code?.SubCode == null)
            {
                return(new FaultException(fault));
            }

            switch (fault.Code.SubCode.Name)
            {
            case "InvalidRepresentation":
                return(GetInvalidRepresentationException(fault));

            case "PermissionDenied":
                return(GetPermissionDeniedException(fault));

            case "UnwillingToPerform":
                return(GetUnwillingToPerformException(fault));

            case "AuthorizationRequiredFault":
                return(GetAuthorizationRequiredException(fault));

            default:
                break;
            }

            return(new FaultException(fault, fault.GetReaderAtDetailContents().ReadOuterXml()));
        }
        public static T DeserializeMessageWithPayload <T>(this MessageFault messageWithPayload)
        {
            if (!messageWithPayload.HasDetail)
            {
                return(default(T));
            }

            if (typeof(IXmlSerializable).IsAssignableFrom(typeof(T)))
            {
                IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(typeof(T));
                serializable.ReadXml(messageWithPayload.GetReaderAtDetailContents());
                return((T)serializable);
            }

            XmlSerializer xs = new XmlSerializer(typeof(T));

            return((T)xs.Deserialize(messageWithPayload.GetReaderAtDetailContents()));
        }
Beispiel #11
0
        private void FillErrors(MessageFault messageFault)
        {
            var reader = messageFault.GetReaderAtDetailContents();

            XElement xElement = (XElement)XNode.ReadFrom(reader);

            Errors = new List <T>();

            xElement.Elements().ForEach(x => Errors.Add(x.DeserializeFromXML <T>()));
        }
Beispiel #12
0
        private static void CreateFaultException(Message message)
        {
            //TODO: Get the maxFaultSize from somewhere other than a hardcoded version.
            MessageFault        messageFault = MessageFault.CreateFault(message, 0x10000);
            XmlDictionaryReader reader       = messageFault.GetReaderAtDetailContents();

            DataContractSerializer   serializer    = new DataContractSerializer(typeof(InfoServiceFaultContract));
            InfoServiceFaultContract faultContract = (InfoServiceFaultContract)serializer.ReadObject(reader);

            throw new FaultException <InfoServiceFaultContract>(faultContract, messageFault.Reason, messageFault.Code, message.Headers.Action);
        }
Beispiel #13
0
        protected override FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> faultInfos;

            if (action != null)
            {
                faultInfos = new List <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
                for (int i = 0; i < _xmlSerializerFaultContractInfos.Count; i++)
                {
                    if (_xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == action ||
                        _xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == MessageHeaders.WildcardAction)
                    {
                        faultInfos.Add(_xmlSerializerFaultContractInfos[i]);
                    }
                }
            }
            else
            {
                faultInfos = _xmlSerializerFaultContractInfos;
            }

            Type   detailType = null;
            object detailObj  = null;

            for (int i = 0; i < faultInfos.Count; i++)
            {
                XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo faultInfo = faultInfos[i];
                XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer   = faultInfo.Serializer;

                if (serializer.IsStartObject(detailReader))
                {
                    detailType = faultInfo.FaultContractInfo.Detail;
                    try
                    {
                        detailObj = serializer.ReadObject(detailReader);
                        FaultException faultException = CreateFaultException(messageFault, action,
                                                                             detailObj, detailType, detailReader);
                        if (faultException != null)
                        {
                            return(faultException);
                        }
                    }
                    catch (SerializationException)
                    {
                    }
                }
            }
            return(new FaultException(messageFault, action));
        }
Beispiel #14
0
        private static MethodFault GetVIServerFault(FaultException soapEx)
        {
            if (soapEx == null)
            {
                throw new ArgumentNullException("soapEx");
            }
            PropertyInfo property = soapEx.GetType().GetTypeInfo().GetProperty("Detail");

            VimApi_65.MethodFault methodFault;
            if (property != (PropertyInfo)null)
            {
                methodFault = property.GetValue((object)soapEx) as VimApi_65.MethodFault;
            }
            else
            {
                MessageFault  messageFault  = soapEx.CreateMessageFault();
                XmlSerializer xmlSerializer = FaultUtility.GetFaultSerializer();
                if (xmlSerializer == null)
                {
                    /* XElement xelement = (XElement)XNode.ReadFrom((XmlReader)messageFault.GetReaderAtDetailContents());
                     * System.Type type = typeof(VimApi_65.MethodFault).Assembly.GetType(string.Format("{0}.{1}", (object)typeof(VimApi_65.MethodFault).Namespace, (object)xelement.Attribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance")).Value));
                     * XmlRootAttribute xmlRootAttribute = new XmlRootAttribute(xelement.Name.LocalName);
                     * // ISSUE: variable of the null type
                     * __Null local1 = null;
                     * // ISSUE: variable of the null type
                     * __Null local2 = null;
                     * XmlRootAttribute root = xmlRootAttribute;
                     * string defaultNamespace = "urn:vim25";
                     * xmlSerializer = new XmlSerializer(type, (XmlAttributeOverrides)local1, (System.Type[])local2, root, defaultNamespace); */
                    XElement         xElement   = (XElement)XNode.ReadFrom(messageFault.GetReaderAtDetailContents());
                    XAttribute       xAttribute = xElement.Attribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"));
                    string           name       = string.Format("{0}.{1}", typeof(VimApi_65.MethodFault).Namespace, xAttribute.Value);
                    Type             arg_D0_0   = typeof(VimApi_65.MethodFault).Assembly.GetType(name);
                    XmlRootAttribute root       = new XmlRootAttribute(xElement.Name.LocalName);
                    xmlSerializer = new XmlSerializer(arg_D0_0, null, null, root, "urn:vim25");
                }
                StringReader stringReader = new StringReader(messageFault.GetDetail <XElement>().ToString().Replace("xsd:", ""));
                using (XmlReader xmlReader = XmlReader.Create((TextReader)stringReader, new XmlReaderSettings()
                {
                    ConformanceLevel = ConformanceLevel.Fragment,
                    CloseInput = true
                }))
                {
                    int content = (int)xmlReader.MoveToContent();
                    methodFault = xmlSerializer.Deserialize(xmlReader) as VimApi_65.MethodFault;
                }
            }
            return(VIConvert.ToVim((object)methodFault) as MethodFault);
        }
        public async Task <string> CreateVideoAsync(IStorageFile file, Video v)
        {
            VideoSubmition videoSubmition = new VideoSubmition
            {
                Tags    = v.Tags,
                Title   = v.Title,
                Synopse = v.Synopse
            };

            Video createdVideo = null;

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.AccessKey, _client.InnerChannel))
                {
                    createdVideo = await this._client.AddVideoPostAsync(videoSubmition, null);
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }

            string token = createdVideo.Token;

            BackgroundUploader uploader = new BackgroundUploader();

            UploadOperation uploadOperation =
                await VideosServiceClient.CreateUploadOperationForCreateVideo(file, token, uploader);

            await uploadOperation.StartAsync();

            return(await GetResponseMessage(uploadOperation));
        }
        protected override FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> faultInfos;

            if (action != null)
            {
                faultInfos = new List <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
                for (int i = 0; i < _xmlSerializerFaultContractInfos.Count; i++)
                {
                    if (_xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == action ||
                        _xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == MessageHeaders.WildcardAction)
                    {
                        faultInfos.Add(_xmlSerializerFaultContractInfos[i]);
                    }
                }
            }
            else
            {
                faultInfos = _xmlSerializerFaultContractInfos;
            }

            for (int i = 0; i < faultInfos.Count; i++)
            {
                XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo faultInfo = faultInfos[i];
                XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer   = faultInfo.Serializer;

                if (serializer.IsStartObject(detailReader))
                {
                    Type detailType = faultInfo.FaultContractInfo.Detail;
                    try
                    {
                        object         detailObj      = serializer.ReadObject(detailReader);
                        FaultException faultException = CreateFaultException(messageFault, action,
                                                                             detailObj, detailType, detailReader);
                        if (faultException != null)
                        {
                            return(faultException);
                        }
                    }
#pragma warning disable CA1031 // Do not catch general exception types - if we can't deserialie the message fault detail, return plain FaultException
                    catch (SerializationException)
                    {
                    }
#pragma warning restore CA1031 // Do not catch general exception types
                }
            }
            return(new FaultException(messageFault, action));
        }
Beispiel #17
0
        protected virtual FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList <FaultContractInfo> faultInfos;

            if (action != null)
            {
                faultInfos = new List <FaultContractInfo>();
                for (int i = 0; i < _faultContractInfos.Length; i++)
                {
                    if (_faultContractInfos[i].Action == action || _faultContractInfos[i].Action == MessageHeaders.WildcardAction)
                    {
                        faultInfos.Add(_faultContractInfos[i]);
                    }
                }
            }
            else
            {
                faultInfos = _faultContractInfos;
            }

            for (int i = 0; i < faultInfos.Count; i++)
            {
                FaultContractInfo   faultInfo    = faultInfos[i];
                XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer   = faultInfo.Serializer;
                if (serializer.IsStartObject(detailReader))
                {
                    Type detailType = faultInfo.Detail;
                    try
                    {
                        object         detailObj      = serializer.ReadObject(detailReader);
                        FaultException faultException = CreateFaultException(messageFault, action,
                                                                             detailObj, detailType, detailReader);
                        if (faultException != null)
                        {
                            return(faultException);
                        }
                    }
#pragma warning disable CA1031 // Do not catch general exception types - return a non-specific FaultException is can't deserializer MessageFault
                    catch (SerializationException)
                    {
                    }
#pragma warning restore CA1031 // Do not catch general exception types
                }
            }
            return(new FaultException(messageFault, action));
        }
        protected override FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos;

            if (action != null)
            {
                xmlSerializerFaultContractInfos = new List <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
                for (int j = 0; j < this.xmlSerializerFaultContractInfos.Count; j++)
                {
                    if ((this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == action) || (this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == "*"))
                    {
                        xmlSerializerFaultContractInfos.Add(this.xmlSerializerFaultContractInfos[j]);
                    }
                }
            }
            else
            {
                xmlSerializerFaultContractInfos = this.xmlSerializerFaultContractInfos;
            }
            System.Type detailType = null;
            object      detailObj  = null;

            for (int i = 0; i < xmlSerializerFaultContractInfos.Count; i++)
            {
                XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo info = xmlSerializerFaultContractInfos[i];
                XmlDictionaryReader readerAtDetailContents = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer             = info.Serializer;
                if (serializer.IsStartObject(readerAtDetailContents))
                {
                    detailType = info.FaultContractInfo.Detail;
                    try
                    {
                        detailObj = serializer.ReadObject(readerAtDetailContents);
                        FaultException exception = base.CreateFaultException(messageFault, action, detailObj, detailType, readerAtDetailContents);
                        if (exception != null)
                        {
                            return(exception);
                        }
                    }
                    catch (SerializationException)
                    {
                    }
                }
            }
            return(new FaultException(messageFault, action));
        }
        protected virtual FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList <FaultContractInfo> faultContractInfos;

            if (action != null)
            {
                faultContractInfos = new List <FaultContractInfo>();
                for (int j = 0; j < this.faultContractInfos.Length; j++)
                {
                    if ((this.faultContractInfos[j].Action == action) || (this.faultContractInfos[j].Action == "*"))
                    {
                        faultContractInfos.Add(this.faultContractInfos[j]);
                    }
                }
            }
            else
            {
                faultContractInfos = this.faultContractInfos;
            }
            System.Type detailType = null;
            object      detailObj  = null;

            for (int i = 0; i < faultContractInfos.Count; i++)
            {
                FaultContractInfo   info = faultContractInfos[i];
                XmlDictionaryReader readerAtDetailContents = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer             = info.Serializer;
                if (serializer.IsStartObject(readerAtDetailContents))
                {
                    detailType = info.Detail;
                    try
                    {
                        detailObj = serializer.ReadObject(readerAtDetailContents);
                        FaultException exception = this.CreateFaultException(messageFault, action, detailObj, detailType, readerAtDetailContents);
                        if (exception != null)
                        {
                            return(exception);
                        }
                    }
                    catch (SerializationException)
                    {
                    }
                }
            }
            return(new FaultException(messageFault, action));
        }
        /// <summary>
        /// A method used to verify argument out of range exception.
        /// </summary>
        /// <param name="faultException">A parameter represents a fault exception.</param>
        /// <param name="argumentName">A parameter represents an argument name.</param>
        /// <returns>A return value represents the fault exception's type and its argument name.</returns>
        public bool VerifyArgumentOutOfRangeException(FaultException faultException, string argumentName)
        {
            MessageFault fault = faultException.CreateMessageFault();
            XmlDocument  doc   = new XmlDocument();

            doc.Load(fault.GetReaderAtDetailContents());

            XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);

            xnm.AddNamespace("ex", @"http://schemas.datacontract.org/2004/07/System.ServiceModel");
            XmlNode messageNode = doc.SelectNodes("//ex:Message", xnm).OfType <XmlNode>().SingleOrDefault();
            XmlNode typeNode    = doc.SelectNodes("//ex:Type", xnm).OfType <XmlNode>().SingleOrDefault();

            string message = messageNode.InnerText;
            string type    = typeNode.InnerText;

            return(type.Contains("ArgumentOutOfRangeException") && message.Contains(argumentName));
        }
        //Tested providing username
        public async Task <User> GetUserDetailsAsync(string username)
        {
            User user = new User
            {
                username = username,
            };

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    return(await this._client
                           .UserDetailsAsync(user, new Format())
                           .ContinueWith(t =>
                    {
                        if (t.Result.result.ok)
                        {
                            return t.Result.user;
                        }
                        throw new Exception("Server returned error");
                    }));
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            throw new Exception("Request cannot be fulfilled");
        }
 protected override FaultException CreateFaultException(MessageFault messageFault, string action)
 {
     IList<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos;
     if (action != null)
     {
         xmlSerializerFaultContractInfos = new List<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
         for (int j = 0; j < this.xmlSerializerFaultContractInfos.Count; j++)
         {
             if ((this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == action) || (this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == "*"))
             {
                 xmlSerializerFaultContractInfos.Add(this.xmlSerializerFaultContractInfos[j]);
             }
         }
     }
     else
     {
         xmlSerializerFaultContractInfos = this.xmlSerializerFaultContractInfos;
     }
     System.Type detailType = null;
     object detailObj = null;
     for (int i = 0; i < xmlSerializerFaultContractInfos.Count; i++)
     {
         XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo info = xmlSerializerFaultContractInfos[i];
         XmlDictionaryReader readerAtDetailContents = messageFault.GetReaderAtDetailContents();
         XmlObjectSerializer serializer = info.Serializer;
         if (serializer.IsStartObject(readerAtDetailContents))
         {
             detailType = info.FaultContractInfo.Detail;
             try
             {
                 detailObj = serializer.ReadObject(readerAtDetailContents);
                 FaultException exception = base.CreateFaultException(messageFault, action, detailObj, detailType, readerAtDetailContents);
                 if (exception != null)
                 {
                     return exception;
                 }
             }
             catch (SerializationException)
             {
             }
         }
     }
     return new FaultException(messageFault, action);
 }
        //ImageAddToAlbumAsync requires not only the Album::id but also Album::idSpecified
        public async Task <bool> AddImageToAlbums(string imageId, int[] albunsIds)
        {
            Image img = new Image {
                uid = imageId, albums = new Album[albunsIds.Length]
            };

            for (int i = 0; i < img.albums.Length; i++)
            {
                img.albums[i] = new Album {
                    id = albunsIds[i], idSpecified = true
                };
            }

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    return(await this._client
                           .ImageAddToAlbumAsync(img, PhotosServiceClient.FotosSapoPtInterface)
                           .ContinueWith(t => t.Result.result.ok));
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            throw new Exception("Request cannot be fulfilled");
        }
        public async Task <bool> DeleteImageAsync(string imageUid)
        {
            Image img = new Image {
                uid = imageUid
            };

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    return(await this._client.ImageDeleteAsync(img).ContinueWith(t =>
                    {
                        if (t.Result.ok)
                        {
                            return t.Result.ok;
                        }
                        throw new Exception("Server returned error");
                    }));
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            throw new Exception("Request cannot be fulfilled");
        }
        public async Task <Video[]> QueryAsync(string emails, string tags,
                                               int cos, int limit, string order, int viewAll, string itfc, int showTags)
        {
            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.AccessKey, _client.InnerChannel))
                {
                    return(await this._client.QueryAsync(emails, tags, cos, limit, order, viewAll, itfc, showTags)
                           .ContinueWith(t => t.Result.QueryResult));
                }
            }
            catch (AggregateException e)
            {
                var faultException = e.InnerException as FaultException;

                if (faultException != null)
                {
                    MessageFault messageFault = faultException.CreateMessageFault();

                    if (messageFault.HasDetail)
                    {
                        string innerErrorXml;
                        using (var xmlReader = messageFault.GetReaderAtDetailContents())
                        {
                            innerErrorXml = xmlReader.ReadInnerXml();
                        }
                        if (innerErrorXml != null)
                        {
                            throw new Exception(innerErrorXml);
                        }
                        throw;
                    }
                }
            }
            throw new Exception("Error!");
        }
        public async Task <Album[]> GetUserAlbumsList()
        {
            User user = new User()
            {
                username = "******",
            };

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    return(await this._client
                           .AlbumGetListByUserAsync(user, 0, null, FotosSapoPtInterface)
                           .ContinueWith(t => t.Result.albums));
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            throw new Exception("Request cannot be fulfilled");
        }
        public async Task <Video[]> GetUserVideos(string email, string Interface, string order, int limit, int page)
        {
            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.AccessKey, _client.InnerChannel))
                {
                    return(await this._client.ListUserVideosAsync(email, Interface, order, limit, page)
                           .ContinueWith(t => t.Result.ListUserVideosResult));
                }
            }
            catch (AggregateException e)
            {
                var faultException = e.InnerException as FaultException;

                if (faultException != null)
                {
                    MessageFault messageFault = faultException.CreateMessageFault();

                    if (messageFault.HasDetail)
                    {
                        string innerErrorXml;
                        using (var xmlReader = messageFault.GetReaderAtDetailContents())
                        {
                            innerErrorXml = xmlReader.ReadInnerXml();
                        }
                        if (innerErrorXml != null)
                        {
                            throw new Exception(innerErrorXml);
                        }
                        throw;
                    }
                }
            }
            throw new Exception("Error!");
        }
Beispiel #28
0
 private bool PlaceBuyOrder(string PublicKey, decimal btc)
 {
     try
     {
         srAtm.Order order = client.CreateOrder(PublicKey, btc);
         return(true);
     }
     catch (FaultException ex)
     {
         string       msg   = "FaultException: " + ex.Message;
         MessageFault fault = ex.CreateMessageFault();
         if (fault.HasDetail == true)
         {
             System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
             if (reader.Name == "ExceptionDetail")
             {
                 ExceptionDetail detail = fault.GetDetail <ExceptionDetail>();
                 msg += "\n\nStack Trace: " + detail.StackTrace;
             }
         }
         MessageBox.Show(msg);
     }
     return(false);
 }
        public static bool TryCreateFault12(ReliableMessagingVersion reliableMessagingVersion, Message message,
            MessageFault fault, out WsrmHeaderFault wsrmFault)
        {
            // All wsrm header faults must be sender or receiver faults.
            if (!fault.Code.IsSenderFault && !fault.Code.IsReceiverFault)
            {
                wsrmFault = null;
                return false;
            }

            if ((fault.Code.SubCode == null)
                || (fault.Code.SubCode.Namespace != WsrmIndex.GetNamespaceString(reliableMessagingVersion)) || !fault.HasDetail)
            {
                wsrmFault = null;
                return false;
            }

            string subcodeName = fault.Code.SubCode.Name;
            XmlDictionaryReader detailReader = fault.GetReaderAtDetailContents();
            wsrmFault = CreateWsrmHeaderFault(reliableMessagingVersion, fault.Code, subcodeName, fault.Reason,
                detailReader);

            return (wsrmFault != null);
        }
Beispiel #30
0
        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));
        }
Beispiel #31
0
        private void button1_Click(object sender, EventArgs e)
        {
            string txtDestinationFolder = @"c:\pobrane_z_ePUAP";
            //string txtAdresSkrytki = "/zsisigidspzoo/skrytkaKD";
            string txtAdresSkrytki = "skrytkaKD";
            string txtNazwaSkrytki = "test KD";
            string txtPodmiot      = "zsisigidspzoo";


            //nowy komentarz

            //parametry do zapytania
            ZapytaniePullOczekujaceTyp zapBody = new ZapytaniePullOczekujaceTyp();

            zapBody.adresSkrytki = txtAdresSkrytki;
            zapBody.nazwaSkrytki = txtNazwaSkrytki;
            zapBody.podmiot      = txtPodmiot;

            textBox1.AppendText("Adres skrytki: " + zapBody.adresSkrytki + Environment.NewLine);
            textBox1.AppendText("Nazwa skrytki: " + zapBody.nazwaSkrytki + Environment.NewLine);
            textBox1.AppendText("Podmiot: " + zapBody.podmiot + Environment.NewLine);

            CustomBinding   pullBinding  = CreatePullBinding();
            EndpointAddress pullEndpoint = CreatePullEndpoint();

            //klient pull
            pullClient _client = new pullClient(pullBinding, pullEndpoint);

            X509Certificate2 certyfikatKlienta = GetClientCert();
            X509Certificate2 certyfikatSerwisu = GetServiceCert();

            _client.ClientCredentials.ClientCertificate.Certificate         = certyfikatKlienta;
            _client.ClientCredentials.ServiceCertificate.DefaultCertificate = certyfikatSerwisu;

            //certyfikat dostarczony przez ePUAP do podpisywanie nie daje się zwalidować pod względem nadrzędnych instytucji
            //tzn. chyba sami go sobie wystawiają
            _client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

            try
            {
                //sprawdź oczekujące dokumenty
                OdpowiedzPullOczekujaceTyp odp = _client.oczekujaceDokumenty(zapBody);

                textBox1.AppendText("Oczekujące dokumenty: " + odp.oczekujace.ToString());
            }
            catch (MessageSecurityException ex)
            {
                try
                {
                    System.ServiceModel.FaultException exInner = (FaultException)ex.InnerException;
                    textBox1.AppendText("Wyjątek 1: " + ex.Message);
                    if (ex.InnerException == null)
                    {
                        throw new Exception("Brak szczegółowych informacji o błędzie.");
                    }
                    FaultException fe = ex.InnerException as FaultException;
                    textBox1.AppendText("Wyjątek 2: " + fe.Message);
                    if (fe == null)
                    {
                        throw new Exception("Szczegółowe informacje zapisane zostały w nieprzewidzianym formacie.");
                    }
                    MessageFault mf = fe.CreateMessageFault();
                    if (mf == null)
                    {
                        throw new Exception("Wystąpił problem podczas odtwarzania szczegółowych informacji.");
                    }
                    XmlReader   xr = mf.GetReaderAtDetailContents();
                    XmlDocument xd = new XmlDocument();
                    xd.Load(xr);
                    XmlNode       elemKomunikat = xd.SelectSingleNode("//*[local-name() = 'komunikat']");
                    XmlNode       elemKod       = xd.SelectSingleNode("//*[local-name() = 'kod']");
                    StringBuilder msg           = new StringBuilder();
                    msg.Append("Wystąpił problem z doręczeniem dokumentów. Poniżej znajdują się szczegółowe informacje (komunikaty) przekazane przez ePUAP.");
                    msg.AppendFormat("Informacja z ePUAP: \"{0}, kod błędu: {1}\"", elemKomunikat.InnerText, elemKod.InnerText);
                    textBox1.AppendText(msg.ToString());
                }
                catch (Exception iex)
                {
                    //textBox1.AppendText(ex.Message);
                    //textBox1.AppendText(iex.Message);
                }
            }
            catch (Exception ex)
            {
                textBox1.AppendText(string.Format("Wystąpił błąd podczas pobierania liczby oczekujacych dokumentow:   " + ex.Message));
                textBox1.AppendText(string.Format("Wystąpił błąd podczas pobierania liczby oczekujacych source:   " + ex));
            }
        }
        public static bool TryCreateFault(Message message, MessageFault fault, out MakeConnectionMessageFault wsmcFault)
        {
            // all WS-MakeConnection faults are receiver faults
            if (!fault.Code.IsReceiverFault)
            {
                wsmcFault = null;
                return false;
            }

            if ((fault.Code.SubCode == null)
                || (fault.Code.SubCode.Namespace != MakeConnectionConstants.Namespace))
            {
                wsmcFault = null;
                return false;
            }

            XmlDictionaryReader detailReader = null;
            string subcodeName = fault.Code.SubCode.Name;
            if (fault.HasDetail)
            {
                detailReader = fault.GetReaderAtDetailContents();
            }

            wsmcFault = CreateMakeConnectionFault(message, fault.Code, subcodeName, fault.Reason, detailReader);
            return (wsmcFault != null);
        }
        protected override FaultException CreateFaultException(MessageFault messageFault, string action)
        {
            IList<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> faultInfos;
            if (action != null)
            {
                faultInfos = new List<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
                for (int i = 0; i < _xmlSerializerFaultContractInfos.Count; i++)
                {
                    if (_xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == action
                        || _xmlSerializerFaultContractInfos[i].FaultContractInfo.Action == MessageHeaders.WildcardAction)
                    {
                        faultInfos.Add(_xmlSerializerFaultContractInfos[i]);
                    }
                }
            }
            else
            {
                faultInfos = _xmlSerializerFaultContractInfos;
            }

            Type detailType = null;
            object detailObj = null;
            for (int i = 0; i < faultInfos.Count; i++)
            {
                XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo faultInfo = faultInfos[i];
                XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
                XmlObjectSerializer serializer = faultInfo.Serializer;

                if (serializer.IsStartObject(detailReader))
                {
                    detailType = faultInfo.FaultContractInfo.Detail;
                    try
                    {
                        detailObj = serializer.ReadObject(detailReader);
                        FaultException faultException = CreateFaultException(messageFault, action,
                            detailObj, detailType, detailReader);
                        if (faultException != null)
                            return faultException;
                    }
                    catch (SerializationException)
                    {
                    }
                }
            }
            return new FaultException(messageFault, action);
        }
        public async Task <CreateImageResult> CreateImageAsync(IStorageFile file, Image img)
        {
            ImageCreateResult res = null;

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    res = await this._client.ImageCreateAsync(img, FotosSapoPtInterface);
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }
            if (res != null && res.result.ok)
            {
                BackgroundUploader uploader = new BackgroundUploader();

                //Default HTTP Method is POST (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.networking.backgroundtransfer.backgrounduploader.method.aspx)
                //uploader.Method = "POST";

                UploadOperation uploadOperation =
                    await PhotosServiceClient.CreateUploadOperationForCreateImage(file, res.token, uploader);

                await uploadOperation.StartAsync();

                ResponseInformation responseInformation = uploadOperation.GetResponseInformation();

                uint contentLength = Convert.ToUInt32(responseInformation.Headers["Content-Length"]);

                uint statusCode = responseInformation.StatusCode;

                IInputStream resultStreamAt = uploadOperation.GetResultStreamAt(0);

                IBuffer result = await resultStreamAt.ReadAsync(
                    new Windows.Storage.Streams.Buffer(contentLength),
                    contentLength,
                    InputStreamOptions.None);

                Stream responseStream = result.AsStream();

                XDocument xDocument = XDocument.Load(responseStream);

                /*
                 *
                 * Bug!! Root element ("Upload") as diferent cases in error and in success responses
                 *
                 * Must ask SAPO Photos Team about the latency at User creation
                 *
                 * How can an application post photos for a user not being that user? Seems to be possible.
                 *
                 * Return usefull information
                 *
                 */

                string resultCode =
                    xDocument
                    .Descendants("uploadPost")
                    .Select(e => e.Element("Result").Value)
                    .SingleOrDefault();
                return(new CreateImageResult(res.image, resultCode));
            }
            throw new Exception("Request cannot be fulfilled");
        }