Inheritance: ActionResult
Example #1
0
        /// <summary>
        /// Validates a document.
        /// </summary>
        /// <param name="document">Xml document.</param>
        /// <param name="prefix">Namespace prefix.</param>
        /// <param name="namespaceManager">Namespace manager.</param>
        /// <returns>Error details.</returns>
        internal static XmlResult ValidateDocument(
            this XmlDocument document,
            string prefix,
            XmlNamespaceManager namespaceManager)
        {
            var errorPath = $"//{prefix}:Error";
            var error     = document.SelectNodes(errorPath, namespaceManager);

            var response = new XmlResult();

            if (error.Count > 0)
            {
                var errorChilds  = error.Item(0).Cast <XmlNode>().ToArray();
                var errorDetails = new ErrorDetails
                {
                    ErrorCode = errorChilds
                                .GetFirstOccuringValue("errorCode"),
                    ErrorMessage = errorChilds
                                   .GetFirstOccuringValue("errorMessage"),
                    ErrorDetail = errorChilds
                                  .GetFirstOccuringValue("errorDetail"),
                };

                response.ErrorDetails = errorDetails;
                response.HasError     = true;
            }

            return(response);
        }
        public XmlResult RequestGoogleMapsApiResponse(XElement xElement)
        {
            var result = new XmlResult();

            if (xElement == null || xElement.Value.Contains("OVER_QUERY_LIMIT"))
            {
                return(result);
            }

            if (xElement.Value.Contains("ZERO_RESULTS"))
            {
                result.ResultType = ResultTypeEnum.NoResults;

                return(result);
            }

            if (xElement.Element("result") == null)
            {
                return(result);
            }

            result.ResultType = ResultTypeEnum.Success;

            result.Result = xElement.Element("result");

            return(result);
        }
Example #3
0
 /// <summary>
 /// Handle returning the correct Type based on the template parameter.  If the type is ot Json, Jsonp, or XML, we'll handle
 /// it with the corresponding result type,  Otherwise, return with a cast.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static T GetReturnObject <T>(object obj)
 {
     // return standard JsonResult
     if (typeof(T) == typeof(JsonResult))
     {
         object result = new JsonResult();
         ((JsonResult)result).JsonRequestBehavior = JsonRequestBehavior.AllowGet;
         ((JsonResult)result).Data = obj;
         return((T)result);
     }
     // return JsonpResult (assign the data here and we'll handle the callback wrapping in the serializer)
     else if (typeof(T) == typeof(JsonpResult))
     {
         object result = new JsonpResult();
         ((JsonpResult)result).Data = obj;
         return((T)result);
     }
     // return XmlResult (assign the data here and we'll handle the rest in the serializer)
     else if (typeof(T) == typeof(XmlResult))
     {
         object result = new XmlResult();
         ((XmlResult)result).Data = obj;
         return((T)result);
     }
     // otherwise, let's cast and return it
     else
     {
         return((T)obj);
     }
 }
Example #4
0
        public void Should_set_content_type()
        {
            var result = new XmlResult(new[] { 2, 3, 4 });

            result.ExecuteResult(_controllerContext);
            Assert.AreEqual("text/xml", _controllerContext.HttpContext.Response.ContentType);
        }
 public void NullDataShouldNotThrowError()
 {
     var controllerContext = new ControllerContext { HttpContext = _httpContext.Object };
     var result = new XmlResult(null);
     result.ExecuteResult(controllerContext);
     // Passes if no exception is thrown
 }
Example #6
0
        public void ProcessResult_WhenCreatedWithCollection_ReturnsCorrectXmlRepresentation()
        {
            var response = new FakeResponseContext();
            var result = new XmlResult(new List<CustomType> { new CustomType { Data = "data1", Number = 1 }, new CustomType { Data = "data2", Number = 2 } });

            Assert.That(result.Data as List<CustomType>, Is.Not.Empty);

            result.ProcessResult(null, response);

            var expected = "";
            expected += "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n";
            expected += "<ArrayOfCustomType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n";
            expected += "  <CustomType>\r\n";
            expected += "    <Data>data1</Data>\r\n";
            expected += "    <Number>1</Number>\r\n";
            expected += "  </CustomType>\r\n";
            expected += "  <CustomType>\r\n";
            expected += "    <Data>data2</Data>\r\n";
            expected += "    <Number>2</Number>\r\n";
            expected += "  </CustomType>\r\n";
            expected += "</ArrayOfCustomType>";

            Assert.That(response.ContentType, Is.EqualTo("application/xml"));
            Assert.That(response.Response, Is.EqualTo(expected));
        }
Example #7
0
        private void SourceAndApplyGoogleMapsApiData(Org org, XElement element)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            var result = new XmlResult();

            if (!org.Tried)
            {
                result = _thirdPartyApiManager.RequestGoogleMapsApiResponse(element);

                org.GoogleMapData = result.Result.ToString();
            }
            else
            {
                result.ResultType = ResultTypeEnum.AlreadyTried;
            }

            if (result.ResultType != ResultTypeEnum.Success)
            {
                return;
            }

            _commandManager.UpdateOrgFromGoogleResponse(org, element);
        }
        public void XmlOverrides_can_change_root_node()
        {
            var people = new System.Collections.Generic.List <Person>()
            {
                new Person()
                {
                    Id = 5, Name = "Jeremy"
                },
                new Person()
                {
                    Id = 1, Name = "Bob"
                }
            };

            var attributes = new XmlAttributes();

            attributes.XmlRoot = new XmlRootAttribute("People");

            var xmlAttribueOverrides = new XmlAttributeOverrides();

            xmlAttribueOverrides.Add(people.GetType(), attributes);

            var result = new XmlResult(people, xmlAttribueOverrides);

            result.ExecuteResult(_controllerContext);

            var doc = new XmlDocument();

            doc.LoadXml(_controllerContext.HttpContext.Response.Output.ToString());
            Assert.That(doc.DocumentElement.Name, Is.EqualTo("People"));
        }
Example #9
0
        public XmlResultTests()
        {
            httpContext       = new Mock <HttpContextBase>();
            controllerContext = new ControllerContext(httpContext.Object, new RouteData(), new Mock <ControllerBase>().Object);

            actionResult = new XmlResult();
        }
Example #10
0
        public void Constructor_Sets_Data()
        {
            //Act
            var result = new XmlResult(54);

            //Assert
            Assert.AreEqual(54, result.Data);
        }
Example #11
0
        public void ObjectToSerialize_should_return_the_object_to_serialize()
        {
            var result = new XmlResult(new Person {
                Id = 1, Name = "Bob"
            });

            Assert.That(result.ObjectToSerialize, Is.InstanceOf <Person>());
            Assert.That(((Person)result.ObjectToSerialize).Name, Is.EqualTo("Bob"));
        }
        public void Should_serialise_xml()
        {
            var result = new XmlResult(new Person {Id = 5, Name = "Jeremy"});
            result.ExecuteResult(_controllerContext);

            var doc = new XmlDocument();
            doc.LoadXml(_controllerContext.HttpContext.Response.Output.ToString());
            Assert.That(doc.SelectSingleNode("/Person/Name").InnerText, Is.EqualTo("Jeremy"));
            Assert.That(doc.SelectSingleNode("/Person/Id").InnerText, Is.EqualTo("5"));
        }
Example #13
0
        public Task ExecuteAsync(ActionContext context, XmlResult result)
        {
            var serializerSettings = result.XmlSerializerSettings ?? FormattingUtilities.GetDefaultXmlWriterSettings();
            TextOutputFormatter formatter;

            // create the proper formatter
            formatter = new XmlDataContractSerializerOutputFormatter(serializerSettings);
            XmlResultExecutorBase xmlBase = new XmlResultExecutorBase(WriterFactory, LoggerFactory, formatter);

            return(xmlBase.ExecuteAsync(context, result));
        }
Example #14
0
 public bool Equals(XmlResult other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Equals(other.Document, Document));
 }
Example #15
0
        public string FormatXml()
        {
            var xmlStringBuilder  = new StringBuilder();
            var xmlWriterSettings = new XmlWriterSettings {
                Indent = true, IndentChars = "    "
            };

            using (var xmlWriter = XmlWriter.Create(xmlStringBuilder, xmlWriterSettings))
            {
                XmlResult.Save(xmlWriter);
            }
            return(xmlStringBuilder.ToString());
        }
Example #16
0
        internal static StatusResult ParseStatusResult(
            XmlResult response,
            Func <XmlElement, XmlNamespaceManager, Consumer> extractConsumer)
        {
            if (response.HasError)
            {
                return(new StatusResult {
                    HasError = response.HasError,
                    ErrorDetails = response.ErrorDetails,
                });
            }

            var namespaceManager = response.NameSpaceManager;

            namespaceManager.AddNamespaces(
                (XmlPrefixes.SamlProtocolPrefix, SamlNamespaces.Protocol),
                (XmlPrefixes.SamlAssertionPrefix, SamlNamespaces.Assertion),
                (XmlPrefixes.DsigPrefix, XmlNamespaces.Dsig),
                (XmlPrefixes.XmlEncPrefix, XmlNamespaces.XMLEncryptionSyntax)
                );

            var doc = response.ResponseDoc;

            var statusResult = new StatusResult {
                Status = doc.GetInnerTextFromChild(
                    "Transaction",
                    "status",
                    namespaceManager),
            };

            if (!statusResult.HasSuccessStatus)
            {
                return(statusResult);
            }

            var assertionXpath =
                $"//{CreateXmlName("Transaction")}/" +
                $"{CreateXmlName("container")}/" +
                $"{CreateXmlName("Response", XmlPrefixes.SamlProtocolPrefix)}/" +
                $"{CreateXmlName("Assertion", XmlPrefixes.SamlAssertionPrefix)}";

            var assertion = (XmlElement)response.ResponseDoc.SelectSingleNode(
                assertionXpath,
                namespaceManager);

            statusResult.Consumer    = extractConsumer(assertion, namespaceManager);
            statusResult.RawResponse = response.ResponseDoc.OuterXml;

            return(statusResult);
        }
Example #17
0
        public void Should_serialise_xml()
        {
            var result = new XmlResult(new Person {
                Id = 5, Name = "Jeremy"
            });

            result.ExecuteResult(_controllerContext);

            var doc = new XmlDocument();

            doc.LoadXml(_controllerContext.HttpContext.Response.Output.ToString());
            Assert.That(doc.SelectSingleNode("/Person/Name").InnerText, Is.EqualTo("Jeremy"));
            Assert.That(doc.SelectSingleNode("/Person/Id").InnerText, Is.EqualTo("5"));
        }
        /// <summary>
        /// Executes the <see cref="XmlResult"/> and writes the response.
        /// </summary>
        /// <param name="context">The <see cref="ActionContext"/>.</param>
        /// <param name="result">The <see cref="XmlResult"/>.</param>
        /// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns>
        public Task ExecuteAsync(ActionContext context, XmlResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            string   resolvedContentType         = null;
            Encoding resolvedContentTypeEncoding = null;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            var serializerSettings = result.XmlSerializerSettings ?? FormattingUtilities.GetDefaultXmlWriterSettings();



            var outputFormatterWriterContext = new OutputFormatterWriteContext(
                context.HttpContext,
                WriterFactory.CreateWriter,
                result.Value.GetType(), result.Value);

            outputFormatterWriterContext.ContentType = new StringSegment(resolvedContentType);

            //  Logger formatter and value of object

            Logger.FormatterSelected(OutputFormatter, outputFormatterWriterContext);
            Logger.XmlResultExecuting(result.Value);

            return(OutputFormatter.WriteAsync(outputFormatterWriterContext));
        }
Example #19
0
        public void ExecuteResult_With_ContentEncoding()
        {
            //Arrange
            var httpResponse = new FakeResponse();
            var httpContext = MockRepository.GenerateMock<HttpContextBase>();
            httpContext.Expect(x => x.Response).Return(httpResponse);
            var context = new ControllerContext(httpContext, new RouteData(), new TestController());
            var result = new XmlResult {Data = 54, ContentEncoding = Encoding.UTF32};

            //Act
            result.ExecuteResult(context);

            //Assert
            Assert.AreEqual(Encoding.UTF32, httpResponse.ContentEncoding);
        }
Example #20
0
        public void ExecuteResult_Uses_XmlSerializer()
        {
            //Arrange
            var httpResponse = new FakeResponse();
            var httpContext = MockRepository.GenerateMock<HttpContextBase>();
            httpContext.Expect(x => x.Response).Return(httpResponse);
            var context = new ControllerContext(httpContext, new RouteData(), new TestController());
            var result = new XmlResult(new NonDataContractTestSerial { Number = 54 });

            //Act
            result.ExecuteResult(context);

            //Assert
            httpResponse.OutputStream.Position = 0;
            var reader = new StreamReader(httpResponse.OutputStream);
            Assert.Contains(reader.ReadToEnd(), "<Number>54</Number>");
        }
Example #21
0
        /// <summary>
        /// Load sprites relative to the xml file
        /// </summary>
        /// <param name="xml_path">Path to the xml file, replace / by . in the string. Example : Content.character.TimXml.xml</param>
        private void LoadXml(string xml_path)
        {
            if (XmlMemo.ContainsKey(xml_path))
            {
                XmlResult res = XmlMemo[xml_path];
                rect      = res.rect;
                FrameTime = res.FrameTime;
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Load.GetStringResource(xml_path));
                XmlElement all = doc.DocumentElement;

                if (all != null)
                {
                    rect      = new RectSprite[all.ChildNodes.Count][];
                    FrameTime = new float[all.ChildNodes.Count];

                    int i = 0;
                    foreach (XmlNode child in all.ChildNodes)
                    {
                        FrameTime[i] = 0f;
                        foreach (XmlAttribute val in child.Attributes)
                        {
                            if (val.Name == "delay")
                            {
                                FrameTime[i] = Convert.ToInt32(val.Value) / 1000f;
                            }
                        }

                        rect[i] = new RectSprite[child.ChildNodes.Count];
                        int j = 0;
                        foreach (XmlNode ligne in child.ChildNodes)
                        {
                            rect[i][j] = new RectSprite(ligne.Attributes);
                            j         += 1;
                        }
                        i += 1;
                    }
                }

                XmlMemo[xml_path] = new XmlResult(rect, FrameTime);
            }
        }
Example #22
0
        private void SourceAndApplyPostcodeApiData(Org org, XElement element)
        {
            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            var result = new XmlResult();

            if (!org.LaTried)
            {
                result = _thirdPartyApiManager.RequestLaApiResponse(element);

                org.LaData = result.Result.ToString();
            }
            else
            {
                result.ResultType = ResultTypeEnum.AlreadyTried;
            }

            if (result.ResultType != ResultTypeEnum.Success)
            {
                return;
            }

            _commandManager.UpdateOrgFromLaApiResponse(org, element);

            if (org.LaCode == null)
            {
                return;
            }

            var authority = _queryManager.GetAuthority(org.LaCode);

            if (authority == null)
            {
                return;
            }

            _commandManager.UpdateAuthority(org, authority.Id);
        }
Example #23
0
        public ActionResult Backup(FormCollection collection)
        {
            ViewBag.Result = "備份成功";
            var backupFilePath = Server.MapPath(@"~/backup.xml");

            var backupModel = new BackupModel();

            backupModel.Users = this.pointsDbEntity.Users.ToList();
            backupModel.EncoderSettings = this.pointsDbEntity.EncoderSettings.ToList();
            backupModel.StreamingSettings = this.pointsDbEntity.StreamingSettings.ToList();

            Serializer.SerializeToXml<BackupModel>(backupModel, backupFilePath);
            ViewBag.BackupFilePath = backupFilePath;

            var xmlResult = new XmlResult(backupModel);

            return xmlResult;
        }
Example #24
0
        internal static DirectoryResult ParseDirectoryResult(
            XmlResult response)
        {
            if (response.HasError)
            {
                return(new DirectoryResult {
                    HasError = response.HasError,
                    ErrorDetails = response.ErrorDetails,
                });
            }

            var namespaceManager = response.NameSpaceManager;
            var issuers          = new List <Issuer>();

            foreach (XmlNode country in response
                     .ResponseDoc
                     .GetElementsByTagName("Country", IdinNamespaces.IdinNamespace)
                     )
            {
                var countryName = country.SelectSingleNode(
                    CreateXmlName("countryNames"),
                    namespaceManager).InnerText;

                foreach (
                    XmlElement issuer in country
                    .SelectNodes(CreateXmlName("Issuer"), namespaceManager)
                    )
                {
                    var issuerChilds = issuer.Cast <XmlNode>().ToArray();
                    issuers.Add(new Issuer {
                        IssuerId = issuerChilds
                                   .GetFirstOccuringValue("issuerID"),
                        IssuerName = issuerChilds
                                     .GetFirstOccuringValue("issuerName"),
                        CountryName = countryName,
                    });
                }
            }

            return(new DirectoryResult {
                Issuers = issuers,
            });
        }
        public void XmlOverrides_can_change_root_node()
        {
            var people = new System.Collections.Generic.List<Person>() {
                                            new Person(){ Id = 5, Name = "Jeremy" },
                                            new Person(){ Id = 1, Name = "Bob" }
            };

            var attributes = new XmlAttributes();
            attributes.XmlRoot = new XmlRootAttribute("People");

            var xmlAttribueOverrides = new XmlAttributeOverrides();
            xmlAttribueOverrides.Add(people.GetType(), attributes);

            var result = new XmlResult(people, xmlAttribueOverrides);
            result.ExecuteResult(_controllerContext);

            var doc = new XmlDocument();
            doc.LoadXml(_controllerContext.HttpContext.Response.Output.ToString());
            Assert.That(doc.DocumentElement.Name, Is.EqualTo("People"));
        }
Example #26
0
        public void ProcessResult_WhenCreatedWithCustomObject_ReturnsCorrectXmlRepresentation()
        {
            var response = new FakeResponseContext();
            var result = new XmlResult(new CustomType { Data = "data", Number = 50 });

            Assert.That((result.Data as CustomType).Data, Is.EqualTo("data"));
            Assert.That((result.Data as CustomType).Number, Is.EqualTo(50));

            result.ProcessResult(null, response);

            var expected = "";
            expected += "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n";
            expected += "<CustomType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n";
            expected += "  <Data>data</Data>\r\n";
            expected += "  <Number>50</Number>\r\n";
            expected += "</CustomType>";

            Assert.That(response.ContentType, Is.EqualTo("application/xml"));
            Assert.That(response.Response, Is.EqualTo(expected));
        }
        public ActionResult XmlData(Hashtable hashtable)
        {
            try
            {
                ApiResult apiresult = ApiExec.Done(hashtable);
                if (apiresult.Code > 0)
                {
                    return(Json(apiresult.msg, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    if (apiresult.ResultDataType == 4)
                    {
                        DataTable dt = apiresult.DataTable;

                        // 序列化为XML格式显示
                        XmlResult xResult = new XmlResult(dt, dt.GetType());
                        return(xResult);
                    }
                    else if (apiresult.ResultDataType == 2)
                    {
                        //DataTable dt = apiresult.DataTable;
                        // 序列化为XML格式显示
                        //XmlResult xResult = new XmlResult(dt, dt.GetType());
                        return(new XmlResult(apiresult.Data.ToString(), typeof(string)));
                    }
                    else
                    {
                        //return Json(SerializeDataTableXml(dt), JsonRequestBehavior.AllowGet);
                        return(new XmlResult("无法转换成xml输出", typeof(string)));
                    }
                }
            }
            catch (Exception exp)
            {
                return(new XmlResult(exp.Message, typeof(string)));
                //return Json(exp.Message, JsonRequestBehavior.AllowGet);
            }
        }
Example #28
0
        internal static TransactionResult ParseTransactionResult(
            XmlResult response)
        {
            if (response.HasError)
            {
                return(new TransactionResult {
                    HasError = response.HasError,
                    ErrorDetails = response.ErrorDetails,
                });
            }

            var doc = response.ResponseDoc;
            var namespaceManager = response.NameSpaceManager;

            return(new TransactionResult {
                Acquirer = new Acquirer {
                    AcquirerId = doc.GetInnerTextFromChild(
                        "Acquirer",
                        "acquirerID",
                        namespaceManager),
                },
                Issuer = new Issuer {
                    IssuerAuthenticationUrl = new Uri(doc.GetInnerTextFromChild(
                                                          "Issuer",
                                                          "issuerAuthenticationURL",
                                                          namespaceManager)),
                },
                Transaction = new Transaction {
                    TransactionId = doc.GetInnerTextFromChild(
                        "Transaction",
                        "transactionID",
                        namespaceManager),
                    TransactionCreateDateTimeStamp = doc.GetInnerTextFromChild(
                        "Transaction",
                        "transactionCreateDateTimestamp",
                        namespaceManager),
                },
            });
        }
        public XmlResult RequestLaApiResponse(XElement xElement)
        {
            var result = new XmlResult();

            if (xElement == null)
            {
                return(result);
            }

            var countained = xElement.Element("administrative");

            if (countained == null)
            {
                return(result);
            }

            result.ResultType = ResultTypeEnum.Success;

            result.Result = countained;

            return(result);
        }
Example #30
0
        public static void ToXmlRowCell <T>(this T thingToRead, XmlTextWriter writer, int rowID, GridSpec <T> gridSpec)
        {
            writer.WriteStartElement("row");
            writer.WriteAttributeString("id", rowID.ToString(CultureInfo.InvariantCulture));

            foreach (var columnSpec in gridSpec)
            {
                writer.WriteStartElement("cell");

                var cellCssClass = columnSpec.CalculateCellCssClass(thingToRead);
                var title        = columnSpec.CalculateTitle(thingToRead);

                if (!String.IsNullOrEmpty(cellCssClass))
                {
                    writer.WriteAttributeString("class", cellCssClass);
                }

                if (!String.IsNullOrEmpty(title))
                {
                    writer.WriteAttributeString("title", title);
                }

                //if (columnSpec.IsHidden)
                //{
                //    writer.WriteAttributeString("hidden", "true");
                //}

                var value      = columnSpec.CalculateStringValue(thingToRead) ?? String.Empty;
                var stripped   = XmlResult.StripInvalidCharacters(value);
                var xmlEncoded = SecurityElement.Escape(stripped);
                var translated = XmlResult.XmlEncodeCodePage1252Characters(xmlEncoded);

                writer.WriteRaw(translated);
                writer.WriteFullEndElement();
            }

            writer.WriteFullEndElement();
        }
Example #31
0
        public JobDocument[] processTicket(XmlTicket t, Record r, string workFlowName)
        {
            try
            {
                XmlResult xmlResult = clientObject.ProcessTicket(this.location, workFlowName, t);

                if (xmlResult.IsFailed)
                {
                    log.Error("Recognition failed for object: '{0}', version: '{1}', work type id: '{1}'.", new object[] { r.objectId, r.versionNum, r.workTypeId });
                    return(null);
                }
                else
                {
                    log.Info("Recognition succeed for object: '{0}', version: '{1}', work type id: '{1}'.", new object[] { r.objectId, r.versionNum, r.workTypeId });
                    return(xmlResult.JobDocuments);
                }
            }
            catch (Exception e)
            {
                log.Error(e, "Exception in method 'processTicket' while trying to recognize object: '{0}', version: '{1}', using work type with id: '{1}'.", new object[] { r.objectId, r.versionNum, r.workTypeId });
                return(null);
            }
        }
Example #32
0
        public Negotiation Negotiate(IRequest request, object model)
        {
            if (model is XDocument || model is IXPathNavigable || model is XPathNavigator) {
                return new Negotiation(Match.Exact, 1.0, this, () => new XmlResult(model));
            }

            Match match;

            var opt = request.Headers.MatchAccept(reIsXml);
            if (opt == null)
                return Negotiation.None(this);
            else if (opt.Value == "*/*")
                match = Match.Inexact;
            else
                match = Match.Exact;
            return new Negotiation(
                match, opt.Q, this,
                () => {
                    var result = new XmlResult(model);
                    if (opt.Value != "*/*") result.MimeType = opt.Value;
                    return result;
                }
            );
        }
Example #33
0
        public async Task ExecuteAsync_XmlExecutorDataContractContent()
        {
            // Arrange
            var value   = new PurchaseOrder();
            var context = GetActionContext();

            CreateServices(context.HttpContext);

            //
            var result = new XmlResult(value)
            {
                XmlSerializerType = XmlSerializerType.DataContractSerializer
            };
            var services = context.HttpContext.RequestServices;
            IXmlResultExecutor executor = null;

            executor = services.GetService <XmlDcResultExecutor>();

            // Act
            await executor.ExecuteAsync(context, result);

            // Assert
            Assert.Equal("application/xml; charset=utf-8", context.HttpContext.Response.ContentType);

            // Verify to as the new restored object
            //There may be differ DataContract style has been used
            var written  = GetWrittenBytes(context.HttpContext);
            var sWritten = Encoding.UTF8.GetString(written);

            StringReader           sreader  = new StringReader(sWritten);
            DataContractSerializer ser      = new DataContractSerializer(typeof(PurchaseOrder));
            PurchaseOrder          newValue = (PurchaseOrder)ser.ReadObject(XmlReader.Create(sreader));

            Assert.Equal(value.billTo.street, newValue.billTo.street);
            Assert.Equal(value.shipTo.street, newValue.shipTo.street);
        }
Example #34
0
        public async Task ExecuteAsync_XmlExecutorContent()
        {
            // Arrange
            var value             = new PurchaseOrder();
            var xmlWriterSettings = FormattingUtilities.GetDefaultXmlWriterSettings();

            xmlWriterSettings.CloseOutput = false;
            var textw         = new StringWriter();
            var writer        = XmlWriter.Create(textw, xmlWriterSettings);
            var xmlSerializer = new XmlSerializer(value.GetType());

            xmlSerializer.Serialize(writer, value);
            var expected = Encoding.UTF8.GetBytes(textw.ToString());
            var context  = GetActionContext();

            CreateServices(context.HttpContext);

            var services = context.HttpContext.RequestServices;
            IXmlResultExecutor executor = null;

            executor = services.GetService <XmlResultExecutor>();
            var result = new XmlResult(value);

            // Act
            await executor.ExecuteAsync(context, result);

            // Assert
            var written = GetWrittenBytes(context.HttpContext);

            var s1 = Encoding.UTF8.GetString(expected);
            var s2 = Encoding.UTF8.GetString(written);

            Assert.Equal(expected, written);
            Assert.Equal(s1, s2);
            Assert.Equal("application/xml; charset=utf-8", context.HttpContext.Response.ContentType);
        }
        // GET: MvcSitemap
        public ActionResult Index()
        {
            XmlResult result = new XmlResult(Sajtkarta.GetSajtkarta());

            return result;
        }
 public void Should_set_content_type()
 {
     var result = new XmlResult(new[] {2, 3, 4});
     result.ExecuteResult(_controllerContext);
     Assert.AreEqual("text/xml", _controllerContext.HttpContext.Response.ContentType);
 }
        private void SourceAndApplyPostcodeApiData(Org org, XElement element)
        {
            if (org == null) throw new ArgumentNullException("org");
            if (element == null) throw new ArgumentNullException("element");

            var result = new XmlResult();

            if (!org.LaTried)
            {
                result = _thirdPartyApiManager.RequestLaApiResponse(element);

                org.LaData = result.Result.ToString();
            }
            else
            {
                result.ResultType = ResultTypeEnum.AlreadyTried;
            }

            if (result.ResultType != ResultTypeEnum.Success) return;

            _commandManager.UpdateOrgFromLaApiResponse(org, element);

            if (org.LaCode == null) return;

            var authority = _queryManager.GetAuthority(org.LaCode);

            if (authority == null) return;

            _commandManager.UpdateAuthority(org, authority.Id);
        }
 public void ObjectToSerialize_should_return_the_object_to_serialize()
 {
     var result = new XmlResult(new Person {Id = 1, Name = "Bob"});
     Assert.That(result.ObjectToSerialize, Is.InstanceOf<Person>());
     Assert.That(((Person)result.ObjectToSerialize).Name, Is.EqualTo("Bob"));
 }
        private void SourceAndApplyGoogleMapsApiData(Org org, XElement element)
        {
            if (org == null) throw new ArgumentNullException("org");
            if (element == null) throw new ArgumentNullException("element");

            var result = new XmlResult();

            if (!org.Tried)
            {
                result = _thirdPartyApiManager.RequestGoogleMapsApiResponse(element);

                org.GoogleMapData = result.Result.ToString();
            }
            else
            {
                result.ResultType = ResultTypeEnum.AlreadyTried;
            }

            if (result.ResultType != ResultTypeEnum.Success) return;

            _commandManager.UpdateOrgFromGoogleResponse(org, element);
        }
Example #40
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            _SitePath = CmsRoute.GetSitePath();

            _DTSitePath = ConfigurationManager.AppSettings["DesignTimeAssetsLocation"]
                          .ToNullOrEmptyHelper()
                          .Return(_SitePath);
            _AllowTfrm = ConfigurationManager.AppSettings["EnableTFRMParameter"].ToNullHelper().Branch(
                str => str.Trim().ToLowerInvariant() == "true",
                () => true);
            _LegacyTransformation = ConfigurationManager.AppSettings["LegacyRendering"].ToNullHelper()
                                    .Branch(
                str => str.Trim().ToLowerInvariant() != "false",
                () => true);

            _UseTempStylesheetsLocation = ConfigurationManager.AppSettings["UseTempStylesheetsLocation"].ToNullHelper().Branch(str => str.Trim().ToLowerInvariant() != "false", () => true);

            _IsDesignTime = Reference.Reference.IsDesignTime(_SitePath);

            try
            {
                //page factory is a cheap object to construct, since both surl map and ssmap are cached most time
                _PageFactory = CMSPageFactoryHelper.GetPageFactory(_IsDesignTime, _SitePath, requestContext, _LegacyTransformation, out _IsDTAuthenticated) as CMSPageFactory;
            }
            catch (Ingeniux.CMS.Exceptions.LicensingException e)
            {
                if (e.Expired)
                {
                    _InvalidPageResult = new XmlResult(
                        new XElement("TrialLicenseExpired",
                                     new XAttribute("ExpirationDateUTC", e.ExpirationDate.ToIso8601DateString(true)),
                                     new XElement("IngeniuxSupport",
                                                  new XAttribute("Phone", "1.877.299.8900"),
                                                  new XAttribute("Email", "*****@*****.**"),
                                                  new XAttribute("Portal", "http://support.ingeniux.com/"))));
                }
                else
                {
                    _InvalidPageResult = new XmlResult(
                        new XElement("InvalidCMSLicense",
                                     new XElement("IngeniuxSupport",
                                                  new XAttribute("Phone", "1.877.299.8900"),
                                                  new XAttribute("Email", "*****@*****.**"),
                                                  new XAttribute("Portal", "http://support.ingeniux.com/"))));
                }
            }

            if (_InvalidPageResult == null)
            {
                if (_PageFactory.CacheSiteControls)
                {
                    // only set site control schemas when list is not empty
                    string[] siteControlSchemas = ConfigurationManager.AppSettings["SiteControlSchemas"].ToNullHelper().Branch <string[]>(
                        str => str.Split(';').Select(
                            s => s.Trim()).Where(
                            s => s != "").ToArray(),
                        () => new string[] { });

                    if (siteControlSchemas.Length > 0)
                    {
                        _PageFactory.SiteControlSchemas = siteControlSchemas;
                    }
                }

                _PageFactory.LocalExportsIncludeLinks = ConfigurationManager.AppSettings["LocalExportsIncludeLinks"].ToNullHelper().Branch <bool>(
                    str => str.Trim().ToLowerInvariant() == "true",
                    () => true);

                //move page getting to here so it can be used to OnActionExecuting
                try
                {
                    _CMSPageRoutingRequest = _PageFactory.GetPage(Request, false);
                }
                catch (DesignTimeInvalidPageIDException exp)
                {
                    //this message is exclusive to design time and need to present a special page
                    _InvalidPageResult = new XmlResult(new XElement("DynamicPreviewError", exp.Message));
                }
            }

            if (_CMSPageRoutingRequest != null && string.IsNullOrWhiteSpace(_CMSPageRoutingRequest.RemaingPath))
            {
                HttpContext.Items["PageRequest"] = _CMSPageRoutingRequest;
            }
        }
Example #41
0
        public void ExecuteResult_With_XNode()
        {
            //Arrange
            var httpResponse = new FakeResponse();
            var httpContext = MockRepository.GenerateMock<HttpContextBase>();
            httpContext.Expect(x => x.Response).Return(httpResponse);
            var context = new ControllerContext(httpContext, new RouteData(), new TestController());
            var node = new XDocument();
            node.AddFirst(" \t ");
            var result = new XmlResult {Data = node};

            //Act
            result.ExecuteResult(context);

            //Assert
            Assert.AreEqual(" \t ", httpResponse.TestString);
        }