public IEnumerable<IResponse> HelloWorldXml() { var res = new XmlResponse(); res.Initialize(new Person(), "application/xml", Encoding.UTF8); yield return res; }
public override void Execute(object parameter) { _isEnable = false; RaiseCanExecuteChanged(); PasswordBox passwordBox = (parameter is PasswordBox) ? (PasswordBox)parameter : null; _viewModel.FilterNameAllMailBox = ""; _viewModel.PasswordBox = passwordBox; _password = passwordBox.Password; _userName = _viewModel.UserNameForMailServer; _host = _viewModel.MailServer; XmlGetDomainListReq request = new XmlGetDomainListReq(); string result = ApiClient.Request(_host, _userName, _password, request.ToString()); if (result == String.Empty) { _isEnable = true; RaiseCanExecuteChanged(); return; } AppConfig.WriteHost(_host); AppConfig.WriteUser(_userName); _viewModel.ServerName = XmlResponse.GetServerName(result); _viewModel.ServerVersion = XmlResponse.GetServerVersion(result); _viewModel.ServerUptime = XmlResponse.GetServerUptime(result); _viewModel.DomainList = XmlResponse.GetDomainList(result, _viewModel); if (_viewModel.DomainList.Count > 0) { _viewModel.SelectedDomain = _viewModel.DomainList[0]; } GetAllMailBoxAsync(); }
private async void WorkAsync(object parameter) { await Task.Run(() => { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => RaiseCanExecuteChanged())); PasswordBox passwordBox = (parameter is PasswordBox) ? (PasswordBox)parameter : null; string password = passwordBox.Password; string userName = _viewModel.UserNameForMailServer; string host = _viewModel.MailServer; foreach (MailBox mailBox in _viewModel.NewMails) { XmlGetUserInfoReq request = new XmlGetUserInfoReq(mailBox.Domain, mailBox.Name); string result = ApiClient.Request(host, userName, password, request.ToString()); if (!XmlResponse.IsUserExist(result)) { XmlCreateUserReq user = new XmlCreateUserReq(mailBox); mailBox.IsOk(); mailBox.IsEdit = false; ApiClient.Request(host, userName, password, user.ToString()); _viewModel.Logging($"добавлен {mailBox.Name}@{mailBox.Domain}"); } else { mailBox.NoOk(); _viewModel.Logging($"{mailBox.Name}@{mailBox.Domain} уже существует"); } } _canExecute = true; App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => RaiseCanExecuteChanged())); }); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { // Given var environment = new DefaultNancyEnvironment(); environment.AddValue(XmlConfiguration.Default); environment.Tracing( enabled: true, displayErrorTraces: true); var response = new XmlResponse <Model>(new Model() { Dummy = "Data" }, new DefaultXmlSerializer(environment), environment); var context = new NancyContext() { Response = response }; // When var result = context.XmlBody <Model>(); // Then result.Dummy.ShouldEqual("Data"); }
protected ActionResult Xml(XmlResponse response) { var stream = new MemoryStream(); response.WriteXml(stream); stream.Position = 0; return(Xml(stream)); }
private static FetchException CreateException(string operation, XmlResponse xml) { return(new FetchException(FetchException.FailureReason.RespondedWithError, string.Format(CultureInfo.InvariantCulture, "Failed to {0} (error: {1})", operation, xml.Status))); }
public void TestXmlResponse() { XmlResponse response1 = XmlResponse.CreateFrom(Response1); XmlResponse response2 = XmlResponse.CreateFrom(Response2); XmlResponse response3 = XmlResponse.CreateFrom(Response3); XmlResponse response4 = XmlResponse.CreateFrom("Úplná kravina beze smyslu <což jest pravda< !"); XmlResponse response5 = XmlResponse.CreateFrom(""); XmlResponse response6 = XmlResponse.CreateFrom(null); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { var response = new XmlResponse<Model>(new Model() { Dummy = "Data" }, "text/xml"); var context = new NancyContext() { Response = response }; var result = context.XmlBody<Model>(); result.Dummy.ShouldEqual("Data"); }
private XmlResponse<T> ToResponse<T>(T response, DateTime requestStart, DateTime lastByteStamp, long latency,Exception Error,bool HasError) { XmlResponse<T> r = new XmlResponse<T>(); r.Error = Error; r.HasError = HasError; r.Result = response; r.LastByte = lastByteStamp; r.RequestStart = requestStart; return r; }
public Response AsXml <TModel>(TModel model, HttpStatusCode statusCode = HttpStatusCode.OK) { var serializer = _xmlSerializer ?? (_xmlSerializer = this.Serializers.FirstOrDefault(s => s.CanSerialize("application/xml"))); var response = new XmlResponse <TModel>(model, serializer); response.StatusCode = statusCode; return(response); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { // Given var response = new XmlResponse<Model>(new Model() { Dummy = "Data" }, new DefaultXmlSerializer()); var context = new NancyContext() { Response = response }; // When var result = context.XmlBody<Model>(); // Then result.Dummy.ShouldEqual("Data"); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { // Given var environment = new DefaultNancyEnvironment(); environment.AddValue(XmlConfiguration.Default); var response = new XmlResponse<Model>(new Model() { Dummy = "Data" }, new DefaultXmlSerializer(environment), environment); var context = new NancyContext() { Response = response }; // When var result = context.XmlBody<Model>(); // Then result.Dummy.ShouldEqual("Data"); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { var response = new XmlResponse <Model>(new Model() { Dummy = "Data" }, "text/xml"); var context = new NancyContext() { Response = response }; var result = context.XmlBody <Model>(); result.Dummy.ShouldEqual("Data"); }
public static bool ResponseIsValid(XmlResponse response, SamlIdentity identity) { XmlNamespaceManager manager = new XmlNamespaceManager(response.Document.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = response.Document.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(response.Document); if (nodeList == null || nodeList.Count == 0) { return(false); } signedXml.LoadXml((XmlElement)nodeList[0]); CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); return(CheckSignature(signedXml, LoadX509Certificate(identity.Certificate))); }
public void Should_create_new_wrapper_from_xml_response_if_not_already_present() { // Given var response = new XmlResponse <Model>(new Model() { Dummy = "Data" }, "text/xml", new DefaultXmlSerializer()); var context = new NancyContext() { Response = response }; // When var result = context.XmlBody <Model>(); // Then result.Dummy.ShouldEqual("Data"); }
internal static XmlResponse Post(RestClient rest, string endpoint, string deviceId, DateTime timestamp, Dictionary <string, object> parameters, string username = null, byte[] token = null) { var headers = new Dictionary <string, string> { ["Accept"] = "application/xml", ["Date"] = timestamp.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", EnUs), ["User-Agent"] = GetUserAgent(deviceId), }; if (!username.IsNullOrEmpty()) { headers["Authorization"] = GetAuthorizationHeader(username, token); } var response = rest.PostForm(endpoint, parameters, headers); if (response.IsSuccessful) { return(XmlResponse.Parse(response.Content)); } if (response.IsNetworkError) { throw new NetworkErrorException("Network error has occurred", response.Error); } // Special handling for 401. There's no other way to tell if the password is correct. // TODO: Write a test for this path. Now it should be easy once we transitioned away // from HttpWebResponse. if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new BadCredentialsException("The password is incorrect"); } throw new InternalErrorException( $"HTTP request to '{response.RequestUri}' failed with status {response.StatusCode}"); }
public PlexResponse Index(PlexRequest request) { XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("MediaContainer"); root.SetAttribute("size", "1"); root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags"); root.SetAttribute("mediaTagVersion", "1283229604"); root.SetAttribute("art", "/resources/library-art.png"); root.SetAttribute("title1", "WinPlex Library"); root.SetAttribute("identify", "com.plexapp.plugins.library"); xml.AppendChild(root); XmlElement directory = xml.CreateElement("Directory"); directory.SetAttribute("key", "sections"); directory.SetAttribute("title", "Library Sections"); root.AppendChild(directory); XmlResponse xmlResponse = new XmlResponse(); xmlResponse.XmlDoc = xml; return xmlResponse; }
public ActionResult Consume(string issuer) { var response = new XmlResponse(Request.Form[SamlResponse]); var identity = SamlIdentityService.Get(issuer); if (identity == null) { return new ContentResult { Content = string.Concat(@"SSO failed. \n Issuer ", issuer, " is invalid.") } } ; if (SamlService.ResponseIsValid(response, identity)) { var userId = response.GetSubject(); if (userId == null) { return(Redirect(identity.IssuerLogoutUrl)); } var token = SamlService.SetSsoToken(userId); if (token == null) { return new ContentResult { Content = string.Concat(@"SSO failed. \n User ", userId, " is invalid.") } } ; return(Redirect(string.Concat(identity.AuthenticatedRedirectUrl, "?SSOtoken=", token, "&SamlIssuer=", identity.Issuer))); } return(new ContentResult { Content = @"SSO failed. \n Certificate is invalid." }); }
private static XmlResponse HandlePostResponse(Func <string> post) { try { return(XmlResponse.Parse(post())); } catch (WebException e) { // Special handling for 401. There's no other way to tell if the password is correct. // TODO: Write a test for this path. It's not trivial to mock HttpWebResponse // if at all possible. var r = e.Response as HttpWebResponse; if (r != null && r.StatusCode == HttpStatusCode.Unauthorized) { throw new FetchException(FetchException.FailureReason.IncorrectPassword, "Incorrect password", e); } throw new FetchException(FetchException.FailureReason.NetworkError, "Network request failed", e); } }
private async void GetAllMailBoxAsync() { _viewModel.SelectedDomainInfoUser = "******"; await Task.Run(() => { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => _viewModel.AllMailBox.Clear())); foreach (string domainName in _viewModel.DomainList) { XmlGetDomainInfoReq request = new XmlGetDomainInfoReq(domainName); string result = ApiClient.Request(_host, _userName, _password, request.ToString()); foreach (var mailBox in XmlResponse.GetUserList(result, domainName)) { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => _viewModel.AllMailBox.Add(mailBox))); } } _isEnable = true; //App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => RaiseCanExecuteChanged() )); }); _viewModel.TotalDomains = _viewModel.DomainList.Count; _viewModel.TotalMailBoxes = _viewModel.AllMailBox.Count; _isEnable = true; RaiseCanExecuteChanged(); }
private static string GetS3TokenItem(XmlResponse xml, string name) { return(xml.Get("/SpcResponse/GetS3TokenResponse/" + name)); }
// // Private // private static InternalErrorException CreateException(string operation, XmlResponse xml) { return(new InternalErrorException($"Failed to {operation} (error: {xml.Status})")); }
/// <summary> /// Parse and return the main parts of a raw notification /// </summary> /// <param name="stream">The raw payload stream</param> /// <param name="tileUri">The background tile image Uri returned</param> /// <param name="title">The tile image title returned</param> /// <param name="count">The tile image count returned</param> /// <param name="text1">The toast Text1 returned</param> /// <param name="text2">The toast Text2 returned</param> /// <returns>True on successful parse</returns> private bool ParseRAWPayload(Stream stream, out Uri tileUri, out string title, out int count, out string text1, out string text2) { tileUri = null; title = null; count = 0; text1 = null; text2 = null; XElement XmlResponse; using (var reader = new StreamReader(stream)) { string payload = reader.ReadToEnd().Replace('\0', ' '); XmlResponse = XElement.Parse(payload); } if (XmlResponse == null) { return(false); } // // Raw payload format: // // <TileService> // <BackgroundImage><background image path></BackgroundImage> // <Count>3</Count> // <Title>5 Northgate<Title> // <Text1>5 Northgate<Text1> // <Text2>3 Minutes Late<Text2> // <stopId>1_590</stopId> // <tripId>1_15437426</tripId> // <status> // <serviceDate>1271401200000</serviceDate> // <position> [if predicted] // <lat>47.66166765182482</lat> [if predicted] // <lon>-122.34439975182481</lon> [if predicted] // </position> [if predicted] // <predicted>true</predicted> // <scheduleDeviation>13</scheduleDeviation> // <vehicleId>1_4207</vehicleId> [if predicted] // <closestStop>1_29530</closestStop> [if predicted] // <closestStopTimeOffset>-10</closestStopTimeOffset> [if predicted] // </status> // </TileService> if (XmlResponse.Name.LocalName == "TileService") { string Tile; Tile = (string)XmlResponse.Element("BackgroundImage"); if (Tile != null) { tileUri = new Uri(Tile); } count = (int?)XmlResponse.Element("Count") ?? 0; title = (string)XmlResponse.Element("Title"); text1 = (string)XmlResponse.Element("Text1"); text2 = (string)XmlResponse.Element("Text2"); // // If nothing parsed then we fail // if (Tile == null && count == 0 && title == null && text1 == null && text2 == null) { return(false); } return(true); } return(false); }
public void SendMessage() { string clearXmlRequest = XmlRequest; int serverConnectTimeout = 5000; // 5 Seconds //DevelopmentLicence myForm = new DevelopmentLicence(); // myForm.ShowDialog(); // used new methods // string base64String = Convert.ToBase64String(Encoding.Default.GetBytes(XmlRequest)); //XmlRequest = base64String; _myStatusForm = new StatusForm(); _myStatusForm.Show(); _myStatusForm.BringToFront(); _myStatusForm.Refresh(); try { string[] serveripandport; serveripandport = ServerUrl.Split(':'); string ip = serveripandport[0]; int port = System.Convert.ToInt32(serveripandport[1]); //TcpClient client = new TcpClient(ip, port); connectDone.Reset(); TcpClient client = new TcpClient(); try { OnStatusMessage(STR_Connecting); client.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), client); // here the clients starts to connect asynchronously (because it is asynchronous it doesn't have a timeout only events are triggered) // immediately after calling beginconnect the control is returned to the method, now we need to wait for the event or connection timeout connectDone.WaitOne(serverConnectTimeout, false); // now application waits here for either an connection event (fi. connection accepted) or the timeout specified by connectionTimeout (in milliseconds) if (!client.Connected) { throw new SocketException(10061); } /*10061 = Could not connect to server */ client.SendTimeout = timeout; client.ReceiveTimeout = timeout; // client.NoDelay = true; client.ReceiveBufferSize = 32768; // First 20 bytes = length in Ascii. //string messageSize = "00000000000000000000" + XmlRequest.Length; //messageSize = messageSize.Substring(messageSize.Length - 20); //XmlRequest = messageSize + XmlRequest; XmlRequest = encodeXmlMessage(XmlRequest, true); OnStatusMessage(STR_Sending); Byte[] request = Encoding.Default.GetBytes(XmlRequest); client.GetStream().Write(request, 0, request.Length); client.GetStream().Flush(); byte[] xmlLength; string messageLength; int lenbytesRead; bool messageLoop = false; bool statusLoop = true; do { // Big Status Loop. do { // Inner Ack Loop, maybe we can get rid off. xmlLength = new byte[20]; messageLength = ""; lenbytesRead = client.GetStream().Read(xmlLength, 0, 20);//s.Receive(incomingBuffer); messageLength = Encoding.Default.GetString(xmlLength); // Log("Message size is " + messageLength); switch (messageLength) { case STR_ACK00000000000000000: OnStatusMessage(STR_AckReceived); messageLoop = true; break; default: OnStatusMessage(STR_Reading); messageLoop = false; break; } } while (messageLoop && client.Connected); int xmlMessageSize = Convert.ToInt32(messageLength); List <byte> dataBuffer = new List <byte>(); int bytesReadSoFar = 0; do { Byte[] response = new Byte[client.ReceiveBufferSize]; int bytesRead = client.GetStream().Read(response, 0, client.ReceiveBufferSize); bytesReadSoFar += bytesRead; byte[] resultArray = new byte[bytesRead]; Array.Copy(response, resultArray, bytesRead); dataBuffer.AddRange(resultArray); } while (bytesReadSoFar < xmlMessageSize); XmlResponse = Encoding.Default.GetString(dataBuffer.ToArray(), 0, dataBuffer.Count).Trim(); //Log("Received response: " + XmlResponse); if (XmlResponse.IndexOf('<') < 0) { // Log("Message was encrypted"); XmlResponse = XmlResponse.Replace("\0", ""); XmlResponse = decodeXmlMessage(XmlResponse, true); } if (XmlResponse.IndexOf("<StatusResponse") > 0) { //Do something with the status message.... try { XmlSerializer serializer = new XmlSerializer(typeof(HicapsConnectControl.StatusResponse)); MemoryStream myResultMS = new MemoryStream(Encoding.Default.GetBytes(XmlResponse)); HicapsConnectControl.StatusResponse myResult = (HicapsConnectControl.StatusResponse)serializer.Deserialize(myResultMS); OnStatusMessage(myResult.ResponseText); statusLoop = true; } catch (Exception ex) { statusLoop = false; } } else { statusLoop = false; } } while (client.Connected && statusLoop); client.Close(); } catch (SocketException) { string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest); XmlResponse = returnNetworkErrorXml("ED", String.Format(STR_DestinationErrorCouldNotConnectToServer, ServerUrl), className); } catch (TimeoutException) { string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest); XmlResponse = returnNetworkErrorXml("EN", String.Format(STR_NetworkRequestTimedOut, ServerUrl), className); } catch (Exception) { string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest); XmlResponse = returnNetworkErrorXml("EN", STR_NetworkError, className); } client.Close(); //Console.ReadLine(); //client.Close(); } catch (Exception ex) { //lock (ignoreServerList) //{ // if (!ignoreServerList.Contains(server)) // { // ignoreServerList.Add(server); // } //} } if (XmlResponse.Length == 0 || XmlResponse == "Que ? Go away") { string className = HicapsConnectControl.BaseMessage.extractClassName(clearXmlRequest); XmlResponse = returnNetworkErrorXml("EN", "Network Error", className); } OnStatusMessage("Waiting"); OnCompletedMessage(); return; }
private PlexResponse CollectionsList() { List<VideoCollection> Collections = DataAccess.GetVideoCollections(); XmlDocument Doc = new XmlDocument(); XmlElement CollectionsElement = Doc.CreateElement("Collections"); Doc.AppendChild(CollectionsElement); foreach (VideoCollection Collection in Collections) { XmlElement CollectionElement = Doc.CreateElement("Collection"); CollectionElement.SetAttribute("title", Collection.Title); CollectionElement.SetAttribute("collectionId", Collection.Id.ToString()); CollectionElement.SetAttribute("type", Collection.Type.ToString()); CollectionElement.SetAttribute("art", String.Format("/resources/{0}/art", Collection.Id)); foreach (string Location in Collection.Locations) { XmlElement LocationElement = Doc.CreateElement("Location"); LocationElement.SetAttribute("path", Location); CollectionElement.AppendChild(LocationElement); } CollectionsElement.AppendChild(CollectionElement); } XmlResponse Response = new XmlResponse(); Response.XmlDoc = Doc; return Response; }
public PlexResponse SectionListing(int sectionId, PlexRequest request) { VideoCollection collection = DataAccess.GetVideoCollection(sectionId); List<Filter> filters = Filter.GetTVFilterList(); XmlDocument xml = new XmlDocument(); XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "UTF-8", null); xml.AppendChild(dec); XmlElement root = xml.CreateElement("MediaContainer"); //size="11" root.SetAttribute("size", filters.Count.ToString()); //content="secondary" root.SetAttribute("content", "secondary"); //mediaTagPrefix="/system/bundle/media/flags/" root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags/"); //mediaTagVersion="1283229604" root.SetAttribute("mediaTagVersion", "1283229604"); //nocache="1" root.SetAttribute("nocache", "1"); //viewGroup="secondary" root.SetAttribute("viewGroup", "secondary"); //viewMode="65592" root.SetAttribute("viewMode", "65592"); //art="/:/resources/show-fanart.jpg" root.SetAttribute("art", String.Format("/resources/{0}/art", collection.Id)); //identifier="com.plexapp.plugins.library" root.SetAttribute("identifier", "com.plexapps.plugins.library"); //title1="TV Shows" root.SetAttribute("title1", collection.Title); xml.AppendChild(root); foreach (Filter filter in filters) { XmlElement directory = xml.CreateElement("Directory"); directory.SetAttribute("key", filter.Key); directory.SetAttribute("title", filter.Name); root.AppendChild(directory); } XmlResponse xmlResponse = new XmlResponse(); xmlResponse.XmlDoc = xml; return xmlResponse; }
private PlexResponse GetShowMetaDataChildren(int id) { TVShow show = DataAccess.GetTVShow(id); List<TVSeason> seasons = DataAccess.GetTVSeasons(show); VideoCollection collection = DataAccess.GetVideoCollection(show.Collection); XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("MediaContainer"); root.SetAttribute("size", seasons.Count.ToString()); root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags/"); root.SetAttribute("mediaTagVersion", "1283229604"); root.SetAttribute("nocache", "1"); // Unsure about this one. Possibly position in order from previous level. root.SetAttribute("parentIndex", "1"); root.SetAttribute("parentTitle", show.Title); root.SetAttribute("parentYear", show.Year.ToString()); root.SetAttribute("summary", show.Summary); root.SetAttribute("thumb", show.Thumb); root.SetAttribute("viewGroup", "seasons"); root.SetAttribute("viewMode", "65593"); root.SetAttribute("key", show.Id.ToString()); root.SetAttribute("art", String.Format("/resources/{0}/art", show.Id)); root.SetAttribute("title1", collection.Title); root.SetAttribute("title2", show.Title); root.SetAttribute("identifier", "com.plexapp.plugins.library"); doc.AppendChild(root); foreach (TVSeason Season in seasons) { XmlElement el = doc.CreateElement("Directory"); el.SetAttribute("ratingKey", Season.Id.ToString()); el.SetAttribute("key", String.Format("/library/metadata/{0}/children", Season.Id)); el.SetAttribute("type", "season"); el.SetAttribute("title", Season.Title); el.SetAttribute("summary", ""); el.SetAttribute("index", "1"); el.SetAttribute("thumb", String.Format("/resources/{0}/thumb", Season.Id)); el.SetAttribute("leafCount", "0"); el.SetAttribute("viewedLeafCount", "0"); root.AppendChild(el); } XmlResponse resp = new XmlResponse(); resp.XmlDoc = doc; return resp; }
private PlexResponse GetSeasonMetaDataChildren(int SeasonId) { TVSeason Season = DataAccess.GetTVSeason(SeasonId); TVShow Show = DataAccess.GetTVShow(Season.ShowId); List<TVEpisode> Episodes = DataAccess.GetTVEpisodes(Season); XmlDocument doc = new XmlDocument(); XmlElement MediaContainerElement = doc.CreateElement("MediaContainer"); MediaContainerElement.SetAttribute("size", Episodes.Count.ToString()); MediaContainerElement.SetAttribute("grandparentContentRating", Show.ContentRating); MediaContainerElement.SetAttribute("grandparentStudio", Show.Studio); MediaContainerElement.SetAttribute("grandparentTitle", Show.Title); MediaContainerElement.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags/"); // TODO: Currently static MediaContainerElement.SetAttribute("mediaTagVersion", "1283229604"); MediaContainerElement.SetAttribute("nocache", "1"); // TODO: Unsure about this one. Possibly position in order from previous level. MediaContainerElement.SetAttribute("parentIndex", "1"); MediaContainerElement.SetAttribute("parentTitle", ""); MediaContainerElement.SetAttribute("thumb", String.Format("/resources/{0}/thumb", Show.Id)); MediaContainerElement.SetAttribute("viewGroup", "episode"); // TODO: Currently static MediaContainerElement.SetAttribute("viewMode", "65592"); MediaContainerElement.SetAttribute("key", Season.Id.ToString()); MediaContainerElement.SetAttribute("banner", String.Format("/resources/{0}/banner", Show.Id)); MediaContainerElement.SetAttribute("art", String.Format("/resources/{0}/art", Show.Id)); // TODO: Fetch theme; MediaContainerElement.SetAttribute("theme", ""); MediaContainerElement.SetAttribute("title1", Show.Title); MediaContainerElement.SetAttribute("title2", Season.Title); MediaContainerElement.SetAttribute("identifier", "com.plexapp.plugins.library"); doc.AppendChild(MediaContainerElement); foreach (TVEpisode Episode in Episodes) { XmlElement VideoElement = doc.CreateElement("Video"); VideoElement.SetAttribute("ratingKey", Episode.Id.ToString()); VideoElement.SetAttribute("key", String.Format("/library/metadata/{0}", Episode.Id)); VideoElement.SetAttribute("type", Episode.Type); VideoElement.SetAttribute("title", Episode.Title); VideoElement.SetAttribute("summary", Episode.Summary); VideoElement.SetAttribute("index", Episode.EpisodeNumber.ToString()); VideoElement.SetAttribute("rating", Episode.Rating.ToString("F1")); VideoElement.SetAttribute("thumb", String.Format("/resources/{0}/thumb/{1}", Episode.Id, Episode.LastUpdated)); VideoElement.SetAttribute("duration", Episode.Duration.ToString()); VideoElement.SetAttribute("originallyAvailableAt", Episode.AirDate.ToString("yyyy-MM-dd")); // TODO Add Media / Writer / Director tags. List<VideoFileInfo> VideoFiles = DataAccess.GetVideoFilesForEpisode(Episode.Id); foreach (VideoFileInfo VideoFile in VideoFiles) { XmlElement MediaElement = doc.CreateElement("Media"); MediaElement.SetAttribute("id", VideoFile.Id.ToString()); MediaElement.SetAttribute("duration", VideoFile.Duration.ToString()); MediaElement.SetAttribute("bitrate", VideoFile.Bitrate.ToString()); MediaElement.SetAttribute("aspectRatio", VideoFile.AspectRatio.ToString()); MediaElement.SetAttribute("audioChannels", VideoFile.AudioChannels.ToString()); MediaElement.SetAttribute("audioCodec", VideoFile.AudioCodec); MediaElement.SetAttribute("videoCodec", VideoFile.VideoCodec); MediaElement.SetAttribute("videoResolution", String.Format("{0}x{1}", VideoFile.PictureWidth, VideoFile.PictureHeight)); MediaElement.SetAttribute("videoFrameRate", VideoFile.FrameRate.ToString()); XmlElement PartElement = doc.CreateElement("Part"); PartElement.SetAttribute("key", String.Format("/library/parts/{0}", VideoFile.Id)); PartElement.SetAttribute("file", VideoFile.Path); PartElement.SetAttribute("size", VideoFile.Size.ToString()); MediaElement.AppendChild(PartElement); VideoElement.AppendChild(MediaElement); } MediaContainerElement.AppendChild(VideoElement); } XmlResponse resp = new XmlResponse(); resp.XmlDoc = doc; return resp; }
private PlexResponse FilteredSection(int collectionId, string filterKey) { VideoCollection currentCollection = DataAccess.GetVideoCollection(collectionId); if (currentCollection.Type == VideoCollectionType.show) { Filter currentFilter = Filter.GetTVFilter(filterKey); List<TVShow> shows = DataAccess.GetTVShows(collectionId, currentFilter); XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("MediaContainer"); //size="1" root.SetAttribute("size", shows.Count.ToString()); //mediaTagPrefix="/system/bundle/media/flags/" root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags/"); //mediaTagVersion="1283229604" root.SetAttribute("mediaTagVersion", "1283229604"); //nocache="1" root.SetAttribute("nocache", "1"); //viewGroup="show" root.SetAttribute("viewGroup", "show"); //viewMode="65592" root.SetAttribute("viewMode", "65592"); //art="/:/resources/show-fanart.jpg" root.SetAttribute("art", "/resources/show-fanart.jpg"); //title1="TV Shows" root.SetAttribute("title1", "TV Shows"); //identifier="com.plexapp.plugins.library" root.SetAttribute("identifier", "com.plexapp.plugins.library"); xml.AppendChild(root); foreach (TVShow show in shows) { XmlElement el = xml.CreateElement("Directory"); el.SetAttribute("ratingKey", show.Id.ToString()); el.SetAttribute("key", String.Format("/library/metadata/{0}/children", show.Id)); el.SetAttribute("studio", show.Studio); el.SetAttribute("type", show.Type); el.SetAttribute("title", show.Title); el.SetAttribute("contentRating", show.ContentRating); el.SetAttribute("summary", show.Summary); el.SetAttribute("rating", show.Rating.ToString()); el.SetAttribute("year", show.Year.ToString()); el.SetAttribute("thumb", String.Format("/resources/{0}/thumb/{1}", show.Id, show.LastUpdated)); el.SetAttribute("art", String.Format("/resources/{0}/art/{1}", show.Id, show.LastUpdated)); el.SetAttribute("banner", String.Format("/resources/{0}/banner/{1}", show.Id, show.LastUpdated)); el.SetAttribute("duration", show.Duration.ToString()); el.SetAttribute("originallyAvailableAt", show.AirDate.ToShortDateString()); el.SetAttribute("leafCount", show.LeafCount.ToString()); el.SetAttribute("viewedLeafCount", show.ViewedLeafCount.ToString()); root.AppendChild(el); } XmlResponse resp = new XmlResponse(); resp.XmlDoc = xml; return resp; } else { return new XmlResponse(); } }
public PlexResponse SectionsIndex(PlexRequest request) { XmlDocument xml = new XmlDocument(); XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "UTF-8", null); xml.AppendChild(dec); XmlElement root = xml.CreateElement("MediaContainer"); List<VideoCollection> collections = DataAccess.GetVideoCollections(); root.SetAttribute("size", collections.Count.ToString()); xml.AppendChild(root); foreach (VideoCollection collection in collections) { XmlElement directory = xml.CreateElement("Directory"); directory.SetAttribute("key", collection.Id.ToString()); directory.SetAttribute("type", collection.Type.ToString()); directory.SetAttribute("title", collection.Title); directory.SetAttribute("art", String.Format("/resources/{0}/art", collection.Id)); root.AppendChild(directory); } XmlResponse xmlResponse = new XmlResponse(); xmlResponse.XmlDoc = xml; return xmlResponse; }
public bool ValidateResponse() { string failedParam = string.Empty; try { failedParam = "EbNo"; var a = EbNo; failedParam = "Lat"; var b = Lat; failedParam = "Lon"; var c = Lon; failedParam = "Hdg"; var d = Hdg; failedParam = "Rel"; var e = Rel; failedParam = "SatLon"; var f = SatLon; failedParam = "Azimuth"; var g = Azimuth; failedParam = "Elevation"; var h = Elevation; failedParam = "CrossPol"; var i = CrossPol; failedParam = "SigStrength"; var j = SigStrength; failedParam = "SatName"; var k = SatName; failedParam = "ConStatus"; var l = ConStatus; return(true); } catch { Program.LogError(GetType().Name, "KVH CommBox", "Error while parsing response from CommBox: " + failedParam, "Received response: " + XmlResponse.ToString()); return(false); } }
/// <summary> /// Vrátí XmlResponse z daného stringu /// </summary> /// <param name="xmlResponse"></param> /// <returns></returns> public static XmlResponse CreateFrom(string xmlResponse) { XmlResponse result = new XmlResponse(xmlResponse); return(result); }