/// <summary> /// Returns a list of metadata property names that should not appear, given the filtering settings. /// </summary> /// <param name="c"></param> /// <param name="test"></param> /// <param name="arg"></param> /// <param name="cds"></param> /// <param name="stats"></param> /// <returns>a list of violating property names</returns> public static IList TestFiltering(IUPnPMedia checkThis, ArrayList filterSettings) { ArrayList v = new ArrayList(); foreach (string propertyName in checkThis.Properties.PropertyNames) { // if the property in the media object is not in the list, then it is a violation if (filterSettings.Contains(propertyName) == false) { v.Add(propertyName); } } return v; }
/// <summary> /// Default implementation to use when printing media object desc nodes. /// </summary> /// <param name="mo"></param> /// <param name="data"></param> /// <param name="xmlWriter"></param> public static void WriteInnerXmlDescNodes(IUPnPMedia mo, ToXmlData data, XmlTextWriter xmlWriter) { foreach (string descNode in mo.MergedDescNodes) { // do nothing for custom metadata for now if ( (data.DesiredProperties.Count == 0) || (data.DesiredProperties.Contains(Tags.GetInstance()[_DIDL.Desc]) == true) ) { // desc nodes are simply strings that // conform to CDS-compliant desc node elements xmlWriter.WriteRaw(descNode); } } }
/// <summary> /// This removes a container or item object from /// the child list. It is used by other /// RemoveXXX methods defined in this class /// and implements the portion that allows /// proper media server eventing. /// <para> /// Method properly tells items to notify all other /// items that reference it that it will be deleted. /// </para> /// <para> /// Method properly tells containers to recursively /// remove their child objects, so that descendent /// reference items are properly removed. /// </para> /// </summary> /// <param name="removeThis"></param> public override void RemoveObject(IUPnPMedia removeThis) { IDvMedia dv = removeThis as IDvMedia; IDvItem item = removeThis as IDvItem; IDvContainer container = removeThis as IDvContainer; // Before we go about doing any removal operations, // we fire the event to indicate this object is // about to be removed. ArrayList removeThese = new ArrayList(1); removeThese.Add(removeThis); if (this.OnChildrenToRemove != null) { this.OnChildrenToRemove(this, removeThese); } if (item != null) { // Notify any and all referring items that // this object is about to be removed // from its parent. item.NotifyPendingDelete(); } else if (container != null) { // Instruct all child containers to // remove their own children. IList children = container.CompleteList; foreach (IDvMedia child in children) { container.RemoveObject(child); } } // go ahead and remove this object base.RemoveObject(removeThis); // Notify that the child has formerly been // removed. if (this.OnChildrenRemoved != null) { this.OnChildrenRemoved(this, removeThese); } this.NotifyRootOfChange(); }
/// <summary> /// Default implementation to use when printing media object resources. /// </summary> /// <param name="mo"></param> /// <param name="shouldPrintResources"></param> /// <param name="formatter"></param> /// <param name="data"></param> /// <param name="xmlWriter"></param> public static void WriteInnerXmlResources(IUPnPMedia mo, DelegateShouldPrintResources shouldPrintResources, ToXmlFormatter formatter, ToXmlData data, XmlTextWriter xmlWriter) { if (shouldPrintResources(data.DesiredProperties)) { // Set up the resource formatter to use the // default StartElement, EndElement, WriteInnerXml, and WriteValue // implementations. This stuff has no effect // if the WriteResource field has been assigned. ToXmlFormatter resFormatter = formatter; resFormatter.StartElement = null; resFormatter.EndElement = null; resFormatter.WriteInnerXml = null; resFormatter.WriteValue = null; // print the resources foreach (IMediaResource res in mo.MergedResources) { res.ToXml(resFormatter, data, xmlWriter); } } }
public static void WriteInnerXmlResources(IUPnPMedia mo, InnerXmlWriter.DelegateShouldPrintResources shouldPrintResources, ToXmlFormatter formatter, ToXmlData data, XmlTextWriter xmlWriter) { IDvMedia dvm = (IDvMedia)mo; ToXmlDataDv txdv = (ToXmlDataDv)data; if (shouldPrintResources(txdv.DesiredProperties)) { if (txdv.BaseUris == null) { txdv.BaseUris = new ArrayList(); } if (txdv.BaseUris.Count == 0) { txdv.BaseUris.Add(txdv.BaseUri); } ToXmlFormatter resFormatter = formatter; resFormatter.StartElement = null; resFormatter.EndElement = null; resFormatter.WriteInnerXml = null; resFormatter.WriteValue = null; // Code is unfinished - intended to allow a media object to // print duplicate resource elements so that each resource // is printed once for every available network interface. foreach (string baseUri in txdv.BaseUris) { txdv.BaseUri = baseUri; foreach (IMediaResource res in dvm.MergedResources) { // Set up the resource formatter to use the // default StartElement, EndElement, WriteInnerXml, and WriteValue // implementations. This stuff has no effect // if the WriteResource field has been assigned. res.ToXml(resFormatter, txdv, xmlWriter); } } } }
/// <summary> /// Tests filters for metadata. /// </summary> /// <param name="testThis"></param> /// <param name="test"></param> /// <param name="arg"></param> /// <param name="cds"></param> /// <param name="stats"></param> /// <returns></returns> public static CdsBrowseSearchResults TestFiltersBrowseMetadata(IUPnPMedia testThis, CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag browseFlag, Cds_BrowseFilter test, CdsSubTestArgument arg, CpContentDirectory cds, CdsResult_BrowseFilter stats) { CdsBrowseSearchResults r = new CdsBrowseSearchResults(); try { BrowseInput input = new BrowseInput(); input.BrowseFlag = browseFlag; if (input.BrowseFlag == CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA) { input.ObjectID = testThis.ID; } else { input.ObjectID = testThis.ParentID; } input.SortCriteria = ""; input.StartingIndex = 0; input.RequestedCount = 0; //assume the test will pass, but worsen the result when we find errors r.SetError(UPnPTestStates.Pass); ArrayList propNames = new ArrayList((ICollection)testThis.Properties.PropertyNames); // add property names related to resources propNames.Add(T[_DIDL.Res]); foreach (string str in MediaResource.GetPossibleAttributes()) { propNames.Add(T[_DIDL.Res] + "@" + str); propNames.Add("@" + str); } propNames.Add(T[_DIDL.Desc]); if (propNames.Count != stats.NumberOfProperties) { throw new TestException("Number of calculated metadata properties (" + propNames.Count + ") doesn't match number of actual metadata properties (" + propNames.Count + ") for testing.", stats); } test._Details.Filters = propNames; int inc = propNames.Count / 4; if (inc == 0) { inc = 1; } for (int numProps = 0; numProps < propNames.Count; numProps++) { for (int iProp = 0; iProp < propNames.Count; iProp += inc) { IList filterSettings = GetFilterSettings(propNames, numProps, iProp, iProp); input.Filter = GetCSVString(filterSettings); CdsBrowseSearchResults br; arg.ActiveTests.UpdateTimeAndProgress(90 * stats.TotalBrowseRequests); br = Cds_BrowseAll.Browse(input, test, arg, cds, stats); if (br.WorstError >= UPnPTestStates.Failed) { StringBuilder teMsg = new StringBuilder(); teMsg.AppendFormat("\"{0}\" is terminating early because {1} returned with an error or had problems with the DIDL-Lite.", test.Name, input.PrintBrowseParams()); if (br.Result != "") { teMsg.AppendFormat(" Returned DIDL=\"{0}\".", br.Result); } throw new TerminateEarly(teMsg.ToString()); } // if (br.InvokeError != null) // { // throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " +input.PrintBrowseParams()+ " returned with an error" + br.InvokeError.Message, br.InvokeError); // } if (input.BrowseFlag == CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA) { if (br.MediaObjects.Count != 1) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " did not return with exactly one media object in its DIDL-Lite response. DIDL-Lite => " + br.Result); } IUPnPMedia mo = (IUPnPMedia)br.MediaObjects[0]; CheckReturnedMetadata(mo, testThis, input, filterSettings, br, test); arg.TestGroup.AddEvent(LogImportance.Remark, test.Name, "\"" + test.Name + "\" did a " + input.PrintBrowseParams() + " and encountered no errors in the results."); } else { IList childList = testThis.Parent.CompleteList; foreach (IUPnPMedia gotChild in br.MediaObjects) { IUPnPMedia testAgainstChild = null; foreach (IUPnPMedia child in childList) { if (child.ID == gotChild.ID) { testAgainstChild = child; break; } } if (testAgainstChild == null) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned media object with ID=\"" + gotChild.ID + "\", which was not a child object of containerID=\"" + input.ObjectID + "\" during a prerequisite test."); } CheckReturnedMetadata(gotChild, testAgainstChild, input, filterSettings, br, test); arg.TestGroup.AddEvent(LogImportance.Remark, test.Name, "\"" + test.Name + "\" did a " + input.PrintBrowseParams() + " and encountered no errors in the results."); } } } } } catch (TerminateEarly te) { string reason = "\"" + test.Name + "\" terminating early. Reason => " + te.Message; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, reason); r.SetError(UPnPTestStates.Failed); return(r); } if (r.WorstError > UPnPTestStates.Warn) { throw new TestException("\"" + test.Name + "\" should not reach this code if the result is worse than " + UPnPTestStates.Warn.ToString() + ".", null); } return(r); }
private void classTypePictureBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (m_Copy != null) { IUPnPMedia[] items = new IUPnPMedia[1]; items[0] = m_Copy; classTypePictureBox.DoDragDrop(items, DragDropEffects.Copy | DragDropEffects.Move); } }
public static CdsBrowseSearchResults CheckMetadata(IUPnPMedia checkAgainstThis, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details) { // // Save a reference to the media object with the most filterable properties int numProperties = 0; if (details.MostMetadata != null) { numProperties = details.MostMetadata.Properties.Count; if (details.MostMetadata.DescNodes.Count > 0) { numProperties++; } } int checkValue = 0; if (checkAgainstThis.ID != "0") { if (checkAgainstThis.Resources.Length > 0) { checkValue = checkAgainstThis.Properties.Count; if (checkAgainstThis.DescNodes.Count > 0) { checkValue++; } } } if (checkValue > numProperties) { details.MostMetadata = checkAgainstThis; } // do a browsemetadata on the media object and determine if the metadata matche. BrowseInput input = new BrowseInput(); input.ObjectID = checkAgainstThis.ID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; input.Filter = "*"; input.StartingIndex = 0; input.RequestedCount = 0; input.SortCriteria = ""; IUPnPMedia metadata = null; CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress((details.TotalBrowseRequests) * 30); if (results.WorstError <= UPnPTestStates.Warn) { if (results.NumberReturned != 1) { results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" + results.NumberReturned + " when it should logically be 1. This output parameter is not really useful for BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); } if (results.TotalMatches != 1) { results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" + results.TotalMatches + " when it should logically be 1. This output parameter is not really useful BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { metadata = results.MediaObjects[0] as IUPnPMedia; if (metadata == null) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the object's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } if (metadata.ID != input.ObjectID) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with ID=\"" + metadata.ID + "\" when it should be \"" + input.ObjectID + "\" as indicated by the input parameter."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } if (metadata.ParentID != checkAgainstThis.ParentID) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with parentID=\"" + metadata.ParentID + "\" when it should be \"" + checkAgainstThis.ParentID + "\"."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } string original; string received; try { original = checkAgainstThis.ToDidl(); received = metadata.ToDidl(); } catch { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " encountered errors with the DIDL-Lite."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); return(results); } if (string.Compare(original, received) == 0) { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " successfully returned a DIDL-Lite media object that succesfully matches with previously seen metadata."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } else { System.Xml.XmlDocument doc1 = new XmlDocument(); XmlDocument doc2 = new XmlDocument(); doc1.LoadXml(original); doc2.LoadXml(received); bool isMatch = true; foreach (XmlElement el1 in doc1.GetElementsByTagName("*")) { bool foundElement = false; foreach (XmlElement el2 in doc2.GetElementsByTagName("*")) { if ( (el1.Name != "item") && (el1.Name != "container") && (el1.OuterXml == el2.OuterXml) ) { foundElement = true; break; } else if ( ( (el1.Name == "DIDL-Lite") || (el1.Name == "item") || (el1.Name == "container") ) && (el1.Name == el2.Name) ) { foundElement = true; break; } } if (foundElement == false) { isMatch = false; break; } } if (isMatch == false) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object that failed to match with previously seen metadata."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, test.Name + ": Original=\"" + original + "\" Received=\"" + received + "\""); } } } else { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " + results.MediaObjects.Count + " media objects."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } } else { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } return(results); }
/// <summary> /// Returns true if the media object is of interest to the spider. /// </summary> /// <param name="mediaObj"></param> /// <returns></returns> internal bool IsMatch(IUPnPMedia mediaObj) { if (this.m_Comparer != null) { return this.m_Comparer.IsMatch(mediaObj); } return false; }
private void ResultImportResource2Sink(System.Uri importFromThis, IUPnPMedia owner, IMediaResource importToThis, IResourceTransfer transferObject, object Tag, UPnPInvokeException error) { //MessageBox.Show(this,"Transfering...","Object Import",MessageBoxButtons.OK,MessageBoxIcon.Information); object[] args = new object[6]; args[0] = importFromThis; args[1] = owner; args[2] = importToThis; args[3] = transferObject; args[4] = Tag; args[5] = error; this.BeginInvoke(new OpenSource.UPnP.AV.MediaServer.CP.CpMediaDelegates.Delegate_ResultImportResource2(ResultImportResource2SinkEx),args); }
/// <summary> /// Indicates vendor specific UPNP error code of 803. /// </summary> /// <param name="obj">The offending IUPnPMedia that was sent to the container for insertion.</param> public Error_DuplicateIdException (IUPnPMedia obj) : base(803, "The media object (@id=\""+obj.ID+"\") conflicts with another media object with the same ID.") { MediaObj = obj; }
public void AddObject(IUPnPMedia newObject, bool overWrite) { }
public void UpdateObject(IUPnPMedia obj) { }
/// <summary> /// Given an <see cref="IUPnPMedia"/> the returned values /// are a list (or null) of all values associated with the supplied /// metadata property. /// </summary> /// <param name="media">the <see cref="IUPnPMedia"/> to interrogage</param> /// <returns>a list of values associated with metadata</returns> public IList Extract(IUPnPMedia media) { ArrayList results = new ArrayList(); // Obtain the values of the appropriate property. // if (this.m_SearchDesc == false) { if (this.m_SearchContainer || this.m_SearchItem) { //grab attributes of item and container if (this.m_Attrib != "") { // Compare element attribute // if (string.Compare(this.m_Attrib, T[_ATTRIB.id], true) == 0) { results.Add(media.ID); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.parentID], true) == 0) { results.Add(media.ParentID); } else if ( (string.Compare(this.m_Attrib, T[_ATTRIB.refID], true) == 0) || (string.Compare(this.m_Attrib, T[_ATTRIB.childCount], true) == 0) ) { IMediaContainer container = media as IMediaContainer; if (container != null) { results.Add(container.ChildCount); } else { IMediaItem mi = media as IMediaItem; if (mi != null) { if (mi.IsReference) { results.Add(mi.RefID); } } } } else if (string.Compare(this.m_Attrib, T[_ATTRIB.restricted], true) == 0) { // Regardless of 0/1 or false/true, a standard of string comparison will do. // results.Add(media.IsRestricted); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.searchable], true) == 0) { IMediaContainer container = media as IMediaContainer; if (container != null) { results.Add(container.IsSearchable); } } } else { // Grab the innerText value of an item or container object // because that's really the value of an item or container. // results.Add(this.GrabInnerText(media)); } } else if (this.m_SearchRes) { foreach (IMediaResource res in media.MergedResources) { if (this.m_Attrib != "") { IList resAttribs = res.ValidAttributes; if (resAttribs.Contains(this.m_Attrib)) { if (string.Compare(this.m_Attrib, T[_ATTRIB.bitrate], true) == 0) { results.Add(res.Bitrate); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.bitsPerSample], true) == 0) { results.Add(res.BitsPerSample); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.colorDepth], true) == 0) { results.Add(res.ColorDepth); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.duration], true) == 0) { results.Add(res.Duration); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.importUri], true) == 0) { results.Add(res.ImportUri); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.nrAudioChannels], true) == 0) { results.Add(res.nrAudioChannels); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.protection], true) == 0) { results.Add(res.Protection); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.protocolInfo], true) == 0) { results.Add(res.ProtocolInfo.ToString()); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.resolution], true) == 0) { results.Add(res[_RESATTRIB.resolution]); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.sampleFrequency], true) == 0) { results.Add(res.SampleFrequency); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.size], true) == 0) { results.Add(res.Size); } } } else { Type resType = res.GetType(); PropertyInfo pi = resType.GetProperty("RelativeContentUri"); if (pi == null) { results.Add(res.ContentUri); } else { string relativeUri = (string)pi.GetValue(res, null); if ((relativeUri != null) && (relativeUri != "")) { results.Add(relativeUri); } else { throw new ApplicationException("res.RelativeContentUri is null or empty."); } } } } //end for } else if (string.Compare(this.m_Tag, _DC.title.ToString(), true) == 0) { string title = media.Title; results.Add(title); } else { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}:{1}", this.m_Ns, this.m_Tag); IList values = null; IList propValues = media.MergedProperties[sb.ToString()]; if (propValues != null) { foreach (ICdsElement propertyValue in propValues) { if (values == null) { values = new ArrayList(); } object val = null; if (this.m_Attrib != "") { val = propertyValue.ExtractAttribute(this.m_Attrib); } else { val = propertyValue.ComparableValue; } if (val != null) { values.Add(val); } } if (values != null) { results.AddRange(values); } } } } else { // Limit our searches to the "desc" elements. // throw new UPnPCustomException(709, "Extraction, sorting, or comparison of <desc> elements or child elements in <desc> nodes is not implemented yet."); } return(results); }
public override UPnPTestStates Run(ICollection otherSubTests, CdsSubTestArgument arg) { CpContentDirectory CDS = this.GetCDS(arg._Device); _Details = new CdsResult_BrowseFilterRangeSort(); this._TestState = UPnPTestStates.Running; arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, "\"" + this.Name + "\" started."); // get the results from the prerequisite tests CdsResult_BrowseFilter FILTER_RESULTS = null; CdsResult_BrowseRange RANGE_RESULTS = null; CdsResult_BrowseSortCriteria SORT_RESULTS = null; try { foreach (ISubTest preTest in otherSubTests) { if (preTest.Name == this.PRE_FILTER.Name) { FILTER_RESULTS = preTest.Details as CdsResult_BrowseFilter; } else if (preTest.Name == this.PRE_RANGE.Name) { RANGE_RESULTS = preTest.Details as CdsResult_BrowseRange; } else if (preTest.Name == this.PRE_SORT.Name) { SORT_RESULTS = preTest.Details as CdsResult_BrowseSortCriteria; } } if (FILTER_RESULTS == null) { throw new TestException(this._Name + " requires that the \"" + this.PRE_FILTER.Name + "\" test be run as a prerequisite. The results from that test cannot be obtained.", otherSubTests); } if (RANGE_RESULTS == null) { throw new TestException(this._Name + " requires that the \"" + this.PRE_RANGE.Name + "\" test be run as a prerequisite. The results from that test cannot be obtained.", otherSubTests); } if (SORT_RESULTS == null) { throw new TestException(this._Name + " requires that the \"" + this.PRE_SORT.Name + "\" test be run as a prerequisite. The results from that test cannot be obtained.", otherSubTests); } } catch (Exception e) { throw new TestException(this._Name + " requires that the \"" + this.PRE_FILTER.Name + "\" and \"" + this.PRE_RANGE + "\" and \"" + this.PRE_SORT + "\" tests be run before. An error occurred when attempting to obtain the results of those prerequisites.", otherSubTests, e); } UPnPTestStates state = this._TestState; CdsResult_BrowseAll BROWSE_ALL = FILTER_RESULTS.BrowseAllResults; if (BROWSE_ALL.LargestContainer == null) { throw new TestException(new Cds_BrowseAll().Name + " failed to find the container with the most child objects. " + this._Name + " requires this value.", BROWSE_ALL); } if (BROWSE_ALL.MostMetadata == null) { throw new TestException(new Cds_BrowseAll().Name + " failed to find the media object with the most metadata. " + this._Name + " requires this value.", BROWSE_ALL); } if (SORT_RESULTS.SortFields == null) { throw new TestException(new Cds_BrowseAll().Name + " failed to find the sortable fields. " + this._Name + " requires this value.", SORT_RESULTS); } int max = Math.Max(FILTER_RESULTS.Filters.Count, BROWSE_ALL.LargestContainer.ChildCount); max = Math.Max(max, SORT_RESULTS.SortFields.Count); this._Details.ExpectedTotalBrowseRequests = max + 1; this._Details.TotalBrowseRequests = 0; this._ExpectedTestingTime = this._Details.ExpectedTotalBrowseRequests * 900; arg.ActiveTests.UpdateTimeAndProgress(this._Details.TotalBrowseRequests * 900); state = UPnPTestStates.Pass; for (int i = 0; i <= max; i++) { ArrayList filterList = new ArrayList(); for (int j = 0; j < i; j++) { if (j < FILTER_RESULTS.Filters.Count) { filterList.Add(FILTER_RESULTS.Filters[j]); } else { break; } } string filterSettings = Cds_BrowseTest.GetCSVString(filterList); uint range = (uint)i; if (range > BROWSE_ALL.LargestContainer.ChildCount) { range = (uint)BROWSE_ALL.LargestContainer.ChildCount; } ArrayList sortList = new ArrayList(); for (int j = 0; j < i; j++) { if (j < SORT_RESULTS.SortFields.Count) { sortList.Add(SORT_RESULTS.SortFields[j]); } else { break; } } BrowseInput input = new BrowseInput(); input.ObjectID = BROWSE_ALL.LargestContainer.ID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; input.Filter = filterSettings; input.RequestedCount = range; input.SortCriteria = Cds_BrowseSortCriteria.GetSortCriteriaString(sortList, i); input.StartingIndex = 0; this._ExpectedTestingTime = (max) * 900; arg.ActiveTests.UpdateTimeAndProgress(this._Details.TotalBrowseRequests * 900); CdsBrowseSearchResults br = Cds_BrowseTest.Browse(input, this, arg, CDS, _Details); MediaContainer original = (MediaContainer)BROWSE_ALL.LargestContainer; uint ignored; IList expectedResults; expectedResults = original.BrowseSorted(0, input.RequestedCount, new MediaSorter(true, input.SortCriteria), out ignored); try { if (br.WorstError <= UPnPTestStates.Warn) { if (br.MediaObjects.Count != expectedResults.Count) { throw new TerminateEarly(input.PrintBrowseParams() + " returned DIDL-Lite that declared " + br.MediaObjects.Count + " media objects but test expected " + expectedResults.Count.ToString() + " media objects as found in a prerequisite test."); } bool warnOrder = false; for (int ri = 0; ri < br.MediaObjects.Count; ri++) { IUPnPMedia resultObj = (IUPnPMedia)br.MediaObjects[ri]; IUPnPMedia originalObj = (IUPnPMedia)expectedResults[ri]; if (resultObj.ID != originalObj.ID) { warnOrder = true; } foreach (string propName in resultObj.Properties.PropertyNames) { if (filterList.Contains(propName) == false) { if ( (propName != T[_DC.title]) && (propName != T[_UPNP.Class]) ) { StringBuilder msg = new StringBuilder(); msg.AppendFormat("\"" + this.Name + "\" is terminating early because {0} returned DIDL-Lite with \"{1}\" metadata when it should not have done so.", input.PrintBrowseParams(), propName); throw new TerminateEarly(msg.ToString()); } } } } int expectedCount = i; if ((i == 0) || (i > BROWSE_ALL.LargestContainer.ChildCount)) { expectedCount = BROWSE_ALL.LargestContainer.ChildCount; } if (br.MediaObjects.Count != expectedCount) { StringBuilder msg = new StringBuilder(); msg.AppendFormat("\"{0}\" did a {1} and the DIDL-Lite result only has {2} media objects when {3} media objects were expected.", this.Name, input.PrintBrowseParams(), br.MediaObjects.Count, expectedCount); msg.AppendFormat(".\r\nDIDL-Lite ==> {0}", br.Result); throw new TerminateEarly(msg.ToString()); } if (warnOrder) { /* * ArrayList missingResults = new ArrayList(); * * foreach (IUPnPMedia em in expectedResults) * { * bool found = false; * foreach (IUPnPMedia fm in br.MediaObjects) * { * if (em.ID == fm.ID) * { * found = true; * break; * } * } * * if (found == false) * { * missingResults.Add(em); * } * } * * if (missingResults.Count > 0) * { * state = UPnPTestStates.Failed; * StringBuilder msg = new StringBuilder(); * msg.AppendFormat("\"{0}\" did a {1} and the result is missing media objects.", this.Name, input.PrintBrowseParams()); * msg.Append("\r\nExpected order of IDs: "); * int z = 0; * foreach (IUPnPMedia em in expectedResults) * { * if (z > 0) * { * msg.Append(","); * } * msg.AppendFormat("\"{0}\"", em.ID); * z++; * } * msg.Append("\r\nDIDL-Lite result's order of IDs: "); * z = 0; * foreach (IUPnPMedia em in br.MediaObjects) * { * if (z > 0) * { * msg.Append(","); * } * msg.AppendFormat("\"{0}\"", em.ID); * z++; * } * msg.AppendFormat(".\r\nDIDL-Lite ==> {0}", br.Result); * throw new TerminateEarly(msg.ToString()); * } * else */ { StringBuilder msg = new StringBuilder(); msg.AppendFormat("WARNING: \"{0}\" did a {1} and got items in a different order. Target CDS either has an error in its sorting logic, or sorting logic intentionally deviates from test.", this.Name, input.PrintBrowseParams()); msg.Append("\r\nExpected order of IDs: "); int z = 0; foreach (IUPnPMedia em in expectedResults) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.Append("\r\nDIDL-Lite result's order of IDs: "); z = 0; foreach (IUPnPMedia em in br.MediaObjects) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.AppendFormat(".\r\nDIDL-Lite ==> {0}", br.Result); arg._TestGroup.AddEvent(LogImportance.Medium, this.Name, msg.ToString()); state = UPnPTestStates.Warn; } } } else { throw new TerminateEarly("\"" + this.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned with an error or had problems with the DIDL-Lite."); } } catch (TerminateEarly te) { arg._TestGroup.AddEvent(LogImportance.Critical, this.Name, "\"" + this.Name + "\" terminating early. Reason ==> " + te.Message); state = UPnPTestStates.Failed; break; } } // finish up logging this._TestState = state; StringBuilder sb = new StringBuilder(); sb.AppendFormat("\"{0}\" completed", this.Name); if (this._TestState <= UPnPTestStates.Running) { throw new TestException("\"" + this.Name + "\" must have a pass/warn/fail result.", this._TestState); } switch (this._TestState) { case UPnPTestStates.Pass: sb.Append(" successfully."); break; case UPnPTestStates.Warn: sb.Append(" with warnings."); break; case UPnPTestStates.Failed: sb.Append(" with a failed result."); break; } arg._TestGroup.AddResult(sb.ToString()); if (this._TestState <= UPnPTestStates.Warn) { if (_Details.TotalBrowseRequests != _Details.ExpectedTotalBrowseRequests) { throw new TestException("TotalBrowseRequests=" + _Details.TotalBrowseRequests.ToString() + " ExpectedTotal=" + _Details.ExpectedTotalBrowseRequests.ToString(), _Details); } } arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, this.Name + " finished."); return(this._TestState); }
/// <summary> /// The ability to modify objects directly to a container/item is not available /// for a public programmer. Each CpMediaItem object is responsible /// for maintaining its own state. /// </summary> /// <param name="newObj"></param> public override void UpdateObject(IUPnPMedia newObj) { this.CheckRuntimeBindings(new StackTrace()); base.UpdateObject(newObj); }
public static CdsBrowseSearchResults GetContainerMetadataAndValidate(string containerID, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details, out IUPnPMedia metadata) { BrowseInput input = new BrowseInput(); input.ObjectID = containerID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; input.Filter = "*"; input.StartingIndex = 0; input.RequestedCount = 0; input.SortCriteria = ""; metadata = null; test.SetExpectedTestingTime((++details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress(details.TotalBrowseRequests * 30); CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress((details.TotalBrowseRequests) * 30); if (results.InvokeError == null) { if (results.NumberReturned != 1) { //results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" + results.NumberReturned + " when it should logically be 1. This output parameter is not really useful for BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; //arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); results.ResultErrors.Add(new Exception(msg)); } if (results.TotalMatches != 1) { //results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" + results.TotalMatches + " when it should logically be 1. This output parameter is not really useful BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; //arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); results.ResultErrors.Add(new Exception(msg)); } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { metadata = results.MediaObjects[0] as IUPnPMedia; if (metadata == null) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the container's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } IMediaContainer imc = metadata as IMediaContainer; // // check metadata // if (imc == null) { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object but it was not declared with a \"container\" element."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add(new Exception(msg)); } else { } if (metadata.ID != containerID) { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with ID=\"" + metadata.ID + "\" when it should be \"" + containerID + "\" as indicated by the input parameter."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add(new Exception(msg)); } if (containerID == "0") { if (metadata.ParentID != "-1") { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with parentID=\"" + metadata.ID + "\" when it must be \"-1\" because the container is the root container."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add(new Exception(msg)); } // no need to check parentID values for other containers because // they get checked when getting the children for this container. } if (results.WorstError < UPnPTestStates.Failed) { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " succeeded."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } } else { //results.SetError(UPnPTestStates.Failed); //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " +results.MediaObjects.Count+ " media objects."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } } else { //throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } if ((results.InvokeError != null) || (results.ResultErrors.Count > 0)) { StringBuilder msg = new StringBuilder(); results.SetError(UPnPTestStates.Failed); msg.AppendFormat("\"{0}\": {1} did not yield exactly one CDS-compliant media object in its result. Instantiated a total of {2} media objects.", test.Name, input.PrintBrowseParams(), results.MediaObjects.Count); msg.AppendFormat("\r\nAdditional Information:"); if (results.InvokeError != null) { msg.AppendFormat("\r\n{0}", results.InvokeError.Message); } foreach (Exception e in results.ResultErrors) { msg.AppendFormat("\r\n{0}", e.Message); } arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg.ToString()); } return(results); }
public override void CalculateExpectedTestingTime(ICollection otherSubTests, ISubTestArgument arg) { // get the results from the BrowseAll test CdsResult_BrowseAll PRE = null; foreach (ISubTest preTest in otherSubTests) { if (preTest.Name == this.PRE_BROWSEALL.Name) { if (preTest.TestState >= UPnPTestStates.Pass) { PRE = preTest.Details as CdsResult_BrowseAll; break; } } } if (PRE == null) { return; } if (PRE.MostMetadata == null) { return; } if (PRE.MostMetadata.Properties.Count != PRE.MostMetadata.Properties.PropertyNames.Count) { return; } IUPnPMedia MM = PRE.MostMetadata; if (MM == null) { return; } IMediaContainer MC = PRE.MostMetadata.Parent; if (MC == null) { return; } int numProps = MM.Properties.Count; int numChildren = MC.ChildCount; // we browse for "res" and each possible res@attribute numProps += (2 * MediaResource.GetPossibleAttributes().Count) + 2; int expectedBrowses = 0; int inc = numProps / 4; if (inc == 0) { inc = 1; } for (int nProps = 0; nProps < numProps; nProps++) { for (int iProp = 0; iProp < numProps; iProp += inc) { expectedBrowses++; } } expectedBrowses *= 2; int maxTime = 90 * expectedBrowses; this._ExpectedTestingTime = maxTime; }
/// <summary> /// Takes the contents of an <see cref="IUPnPMedia"/> object /// casts the data into its XML string form and returns it. /// </summary> /// <param name="entry">the object to extract</param> /// <returns>everything under the item or container element</returns> private string GrabInnerText(IUPnPMedia entry) { StringBuilder sb = new StringBuilder(1000); StringWriter sw = new StringWriter(sb); XmlTextWriter xmlWriter = new XmlTextWriter(sw); // set up the ToXml() method to only provide the InnerText of the element entry.ToXml(ToXmlFormatter.DefaultFormatter, MediaObject.ToXmlData_AllInnerTextOnly, xmlWriter); xmlWriter.Flush(); string result = xmlWriter.ToString(); xmlWriter.Close(); return result; }
public void RemoveObject(IUPnPMedia removeThis) { }
/// <summary> /// Indicates vendor specific UPNP error code of 810. /// </summary> /// <param name="obj"></param> public Error_ObjectIsContainerAndItem(IUPnPMedia obj) : base (810, "Cannot create an object that is both an item and a container.") { this.BadObject = obj; }
/// <summary> /// Returns true if the media object is a container. /// </summary> /// <param name="mediaObject"></param> /// <returns></returns> public bool IsMatch(IUPnPMedia mediaObject) { return(mediaObject.IsReference == true); }
/// <summary> /// This indicates if the /// <see cref="IUPnPMedia"/> /// object matches the Boolean expression. /// </summary> /// <param name="entry">the media object that should be compared against the expression</param> /// <returns>true, indicates a match against the expression</returns> public virtual bool IsMatch(IUPnPMedia entry) { return(this.EvaluateMedia(entry)); }
/// <summary> /// Always returns true. /// </summary> /// <param name="mediaObject"></param> /// <returns></returns> public bool IsMatch(IUPnPMedia mediaObject) { return(true); }
/// <summary> /// Changes the target media object's parent to a different parent. /// </summary> /// <param name="target">target object</param> /// <param name="np">new parent</param> /// <exception cref="InvalidCastException"> /// Thrown when the target's current parent is not a <see cref="DvMediaContainer"/>. /// </exception> internal static void ChangeParent2(IDvMedia target, DvMediaContainer np) { Exception error = null; IUPnPMedia errorDuplicate = null; IDvMedia[] removeThese = new IDvMedia[1]; removeThese[0] = target; DvMediaContainer dvp = (DvMediaContainer)target.Parent; // fire about to remove event if (dvp.OnChildrenToRemove != null) { dvp.OnChildrenToRemove(dvp, removeThese); } // acquire locks dvp.m_LockListing.AcquireWriterLock(-1); np.m_LockListing.AcquireWriterLock(-1); try { // remove target from current parent int i = dvp.HashingMethod.Get(dvp.m_Listing, target); dvp.m_Listing.RemoveAt(i); target.Parent = null; if (dvp.m_Listing.Count == 0) { dvp.m_Listing = null; } // add target to new parent if (np.m_Listing == null) { np.m_Listing = new ArrayList(); } try { np.HashingMethod.Set(np.m_Listing, target, true); target.Parent = np; } catch (KeyCollisionException) { errorDuplicate = target; } } catch (Exception e) { error = e; } // release locks np.m_LockListing.ReleaseWriterLock(); dvp.m_LockListing.ReleaseWriterLock(); // throw exceptions if appropriate if (error != null) { throw new Exception("Unexpected rrror in DvMediaContainer.ChangeParent2", error); } if (errorDuplicate != null) { throw new Error_DuplicateIdException(errorDuplicate); } // fire children removed event if (dvp.OnChildrenRemoved != null) { dvp.OnChildrenRemoved(dvp, removeThese); } // notify upnp network that two containers changed. dvp.NotifyRootOfChange(); np.NotifyRootOfChange(); }
/// <summary> /// Returns true if the media object is a container. /// </summary> /// <param name="mediaObject"></param> /// <returns></returns> public bool IsMatch(IUPnPMedia mediaObject) { return(mediaObject.IsContainer == true); }
/// <summary> /// Default implementation to use when printing media object properties. /// </summary> /// <param name="mo"></param> /// <param name="data"></param> /// <param name="xmlWriter"></param> public static void WriteInnerXmlProperties(IUPnPMedia mo, ToXmlData data, XmlTextWriter xmlWriter) { mo.MergedProperties.ToXml(data, xmlWriter); }
/// <summary> /// Returns true if the media object is a container. /// </summary> /// <param name="mediaObject"></param> /// <returns></returns> public bool IsMatch(IUPnPMedia mediaObject) { return(mediaObject.IsItem == true); }
private static void OnResult_RequestForUpdateObject(ICpMedia attemptChangeOnThis, IUPnPMedia usedThisMetadata, object Tag, UPnPInvokeException error) { MediaPropertyForm form = null; lock (MediaPropertyForm.MetadataRequests.SyncRoot) { form = (MediaPropertyForm)MediaPropertyForm.MetadataRequests[Tag]; MediaPropertyForm.MetadataRequests.Remove(Tag); } if (error != null) { MessageBox.Show(error.UPNP.Message, "An error occurred while trying to update an object."); } if (form != null) { } }
public override UPnPTestStates Run(ICollection otherSubTests, CdsSubTestArgument arg) { CpContentDirectory CDS = this.GetCDS(arg._Device); _Details = new CdsResult_BrowseFilter(); this._TestState = UPnPTestStates.Running; arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, "\"" + this.Name + "\" started."); // get the results from the BrowseAll test CdsResult_BrowseAll PRE = null; try { foreach (ISubTest preTest in otherSubTests) { if (preTest.Name == this.PRE_BROWSEALL.Name) { PRE = preTest.Details as CdsResult_BrowseAll; break; } } if (PRE == null) { throw new TestException(this._Name + " requires that the \"" + this.PRE_BROWSEALL.Name + "\" test be run as a prerequisite. The results from that test cannot be obtained.", otherSubTests); } } catch (Exception e) { throw new TestException(this._Name + " requires that the \"" + this.PRE_BROWSEALL.Name + "\" test be run before. An error occurred when attempting to obtain the results of a prerequisite.", otherSubTests, e); } _Details.BrowseAllResults = PRE; if (PRE.MostMetadata == null) { throw new TestException(this.PRE_BROWSEALL.Name + " failed to find a media object with the most metadata. " + this._Name + " requires this value.", PRE); } if (PRE.MostMetadata.Properties.Count != PRE.MostMetadata.Properties.PropertyNames.Count) { throw new TestException(this.Name + " has conflicting reports for the number of metadata properties. " + PRE.MostMetadata.Properties.Count + "/" + PRE.MostMetadata.Properties.PropertyNames.Count, PRE.MostMetadata.Properties); } IUPnPMedia MM = PRE.MostMetadata; if (MM == null) { string skippedMsg = "\"" + this.Name + "\" skipped because the tested content hierarchy does not have a media object with at least one resource and has an ID!=\"0\""; arg.TestGroup.AddEvent(LogImportance.Critical, this.Name, skippedMsg); arg.TestGroup.AddResult(skippedMsg); return(UPnPTestStates.Ready); } IMediaContainer MC = PRE.MostMetadata.Parent; if (MC == null) { throw new TestException(this.Name + " has MostMetadata.Parent == null", PRE.MostMetadata); } int numProps = MM.Properties.Count; int numChildren = MC.ChildCount; // we browse for "res" and each possible res@attribute numProps += (2 * MediaResource.GetPossibleAttributes().Count) + 2; _Details.NumberOfProperties = numProps; _Details.ExpectedTotalBrowseRequests = 0; int inc = numProps / 4; if (inc == 0) { inc = 1; } for (int nProps = 0; nProps < numProps; nProps++) { for (int iProp = 0; iProp < numProps; iProp += inc) { _Details.ExpectedTotalBrowseRequests++; } } _Details.ExpectedTotalBrowseRequests *= 2; int maxTime = 90 * _Details.ExpectedTotalBrowseRequests; this._ExpectedTestingTime = maxTime; // browse metadata with various filter settings // browsedirectchildren with various filter settings UPnPTestStates state = this._TestState; CdsBrowseSearchResults test1 = TestFiltersBrowseMetadata(MM, CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA, this, arg, CDS, _Details); if (test1.WorstError > state) { state = test1.WorstError; } CdsBrowseSearchResults test2 = TestFiltersBrowseMetadata(MM, CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN, this, arg, CDS, _Details); if (test2.WorstError > state) { state = test2.WorstError; } // finish up logging this._TestState = state; StringBuilder sb = new StringBuilder(); sb.AppendFormat("\"{0}\" completed", this.Name); if (this._TestState <= UPnPTestStates.Running) { throw new TestException("\"" + this.Name + "\" must have a pass/warn/fail result.", this._TestState); } switch (this._TestState) { case UPnPTestStates.Pass: sb.Append(" successfully."); break; case UPnPTestStates.Warn: sb.Append(" with warnings."); break; case UPnPTestStates.Failed: sb.Append(" with a failed result."); break; } arg._TestGroup.AddResult(sb.ToString()); if (this._TestState <= UPnPTestStates.Warn) { if (_Details.TotalBrowseRequests != _Details.ExpectedTotalBrowseRequests) { throw new TestException("TotalBrowseRequests=" + _Details.TotalBrowseRequests.ToString() + " ExpectedTotal=" + _Details.ExpectedTotalBrowseRequests.ToString(), _Details); } } arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, sb.ToString()); return(this._TestState); }
public void UpdateObject(IUPnPMedia obj) {}
private static void CheckReturnedMetadata(IUPnPMedia mo, IUPnPMedia testThis, BrowseInput input, IList filterSettings, CdsBrowseSearchResults br, CdsSubTest test) { // check non-resource metadata string filters = input.Filter; foreach (string moPropName in mo.Properties.PropertyNames) { if (filterSettings.Contains(moPropName) == false) { if (moPropName == T[_DC.title]) { } else if (moPropName == T[_UPNP.Class]) { } else { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " included a \"" + moPropName + "\" metadata property in its DIDL-Lite response. DIDL-Lite ==> " + br.Result); } } } // check resource metadata IList resources = mo.Resources; int expectedResCount = 0; foreach (IMediaResource res in testThis.Resources) { foreach (string filter in filterSettings) { if ((filter.StartsWith(T[_DIDL.Res])) || (filter.StartsWith("@"))) { if (res.ValidAttributes.Contains(filter.Substring(filter.IndexOf("@") + 1))) { expectedResCount++; break; } } } } if (resources.Count < expectedResCount) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned a media object (ID='" + mo.ID + "') with no resources DIDL-Lite when it should have returned at least " + expectedResCount + " " + T[_DIDL.Res] + " objects. DIDL-Lite ==> " + br.Result); } else { int iRes = 0; foreach (IMediaResource res in mo.Resources) { iRes++; if (res.ValidAttributes.Contains(T[_RESATTRIB.protocolInfo])) { foreach (string attrib in res.ValidAttributes) { if (attrib == T[_RESATTRIB.protocolInfo]) { } else if ((filterSettings.Contains("@" + attrib)) || (filterSettings.Contains(T[_DIDL.Res] + "@" + attrib))) { } else { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned resource #" + iRes + " with the \"" + attrib + "\" attribute. DIDL-Lite ==> " + br.Result); } } } else { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned resource #" + iRes + " without a \"protocolInfo\" attribute. DIDL-Lite ==> " + br.Result); } } } // check desc nodes if (filterSettings.Contains(T[_DIDL.Desc])) { if (mo.DescNodes.Count != testThis.DescNodes.Count) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned " + mo.DescNodes.Count + " " + T[_DIDL.Desc] + " nodes when it expected to find " + testThis.DescNodes.Count + " such nodes, as found in a prerequisite test."); } } else { if (mo.DescNodes.Count > 0) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned " + mo.DescNodes.Count + " " + T[_DIDL.Desc] + " nodes when it expected to find none."); } } int found = 0; foreach (string f in filterSettings) { foreach (string p in mo.Properties.PropertyNames) { if (p == f) { found++; } } } bool allStandardFound = false; if (found == testThis.Properties.Count) { allStandardFound = true; } if (allStandardFound) { if (mo.Properties.Count != testThis.Properties.Count) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned " + mo.Properties.Count + " metadata non-resource & non-vendor-specific metadata properties when it expected to find " + testThis.Properties.Count + " such metadata properties, as found in a prerequisite test."); } } }
public void AddObject(IUPnPMedia newObject, bool overWrite){}
/// <summary> /// Given an <see cref="IUPnPMedia"/> the returned values /// are a list (or null) of all values associated with the supplied /// metadata property. /// </summary> /// <param name="media">the <see cref="IUPnPMedia"/> to interrogage</param> /// <returns>a list of values associated with metadata</returns> public IList Extract(IUPnPMedia media) { ArrayList results = new ArrayList(); // Obtain the values of the appropriate property. // if (this.m_SearchDesc == false) { if (this.m_SearchContainer || this.m_SearchItem) { //grab attributes of item and container if (this.m_Attrib != "") { // Compare element attribute // if (string.Compare(this.m_Attrib, T[_ATTRIB.id], true) == 0) { results.Add(media.ID); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.parentID], true) == 0) { results.Add(media.ParentID); } else if ( (string.Compare(this.m_Attrib, T[_ATTRIB.refID], true) == 0) || (string.Compare(this.m_Attrib, T[_ATTRIB.childCount], true) == 0) ) { IMediaContainer container = media as IMediaContainer; if (container != null) { results.Add(container.ChildCount); } else { IMediaItem mi = media as IMediaItem; if (mi != null) { if (mi.IsReference) { results.Add(mi.RefID); } } } } else if (string.Compare(this.m_Attrib, T[_ATTRIB.restricted], true) == 0) { // Regardless of 0/1 or false/true, a standard of string comparison will do. // results.Add(media.IsRestricted); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.searchable], true) == 0) { IMediaContainer container = media as IMediaContainer; if (container != null) { results.Add(container.IsSearchable); } } } else { // Grab the innerText value of an item or container object // because that's really the value of an item or container. // results.Add(this.GrabInnerText(media)); } } else if (this.m_SearchRes) { foreach (IMediaResource res in media.MergedResources) { if (this.m_Attrib != "") { IList resAttribs= res.ValidAttributes; if (resAttribs.Contains(this.m_Attrib)) { if (string.Compare(this.m_Attrib, T[_ATTRIB.bitrate], true) == 0) { results.Add(res.Bitrate); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.bitsPerSample], true) == 0) { results.Add(res.BitsPerSample); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.colorDepth], true) == 0) { results.Add(res.ColorDepth); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.duration], true) == 0) { results.Add(res.Duration); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.importUri], true) == 0) { results.Add(res.ImportUri); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.nrAudioChannels], true) == 0) { results.Add(res.nrAudioChannels); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.protection], true) == 0) { results.Add(res.Protection); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.protocolInfo], true) == 0) { results.Add(res.ProtocolInfo.ToString()); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.resolution], true) == 0) { results.Add(res[_RESATTRIB.resolution]); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.sampleFrequency], true) == 0) { results.Add(res.SampleFrequency); } else if (string.Compare(this.m_Attrib, T[_ATTRIB.size], true) == 0) { results.Add(res.Size); } } } else { Type resType = res.GetType(); PropertyInfo pi = resType.GetProperty("RelativeContentUri"); if (pi == null) { results.Add(res.ContentUri); } else { string relativeUri = (string) pi.GetValue(res, null); if ((relativeUri != null) && (relativeUri != "")) { results.Add(relativeUri); } else { throw new ApplicationException("res.RelativeContentUri is null or empty."); } } } } //end for } else if (string.Compare(this.m_Tag, _DC.title.ToString(), true) == 0) { string title = media.Title; results.Add(title); } else { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}:{1}", this.m_Ns, this.m_Tag); IList values = null; IList propValues = media.MergedProperties[sb.ToString()]; if (propValues != null) { foreach (ICdsElement propertyValue in propValues) { if (values == null) { values = new ArrayList(); } object val = null; if (this.m_Attrib != "") { val = propertyValue.ExtractAttribute(this.m_Attrib); } else { val = propertyValue.ComparableValue; } if (val != null) { values.Add(val); } } if (values != null) { results.AddRange(values); } } } } else { // Limit our searches to the "desc" elements. // throw new UPnPCustomException(709, "Extraction, sorting, or comparison of <desc> elements or child elements in <desc> nodes is not implemented yet."); } return results; }
public void RemoveObject (IUPnPMedia removeThis){}
/// <summary> /// Indicates vendor specific UPNP error code of 802. /// </summary> /// <param name="obj">The IUPnPMedia instance that already has a parent.</param> public Error_MediaObjectHasParent(IUPnPMedia obj) : base(802, "The media object (@id=\""+obj.ID+"\") already has a parent (@parentID=\""+obj.ParentID+"\").") { MediaObj = obj; }
/// <summary> /// Not implemented. /// </summary> /// <param name="ignored"></param> public void UpdateObject(IUPnPMedia ignored) { }
/// <summary> /// Indicates vendor specific UPNP error code of 804. /// </summary> /// <param name="obj1">The object that was getting updated.</param> /// <param name="obj2">The object with the new metadata and resources.</param> public Error_BaseClassMisMatch (IUPnPMedia obj1, IUPnPMedia obj2) : base (804, "Cannot update a media object with class \"" +obj1.Class.ToString()+ "\" with metadata from a class \"" +obj2.Class.ToString()+ "\".") { MediaObj = obj1; UpdateWithThis = obj2; }
/// <summary> /// Recursively checks a media object and all of its descendents, applying the /// <see cref="MediaBuilder.ValidateMediaObject"/> as the criteria. /// </summary> /// <param name="obj"></param> /// <param name="hasParentID"></param> /// <param name="throwException"></param> /// <returns></returns> public static bool RecursiveValidationOfMediaObject (IUPnPMedia obj, bool hasParentID, bool throwException) { bool result = true; IMediaContainer mc = obj as IMediaContainer; if (mc != null) { foreach (IUPnPMedia child in mc.CompleteList) { result = RecursiveValidationOfMediaObject(child, hasParentID, throwException); if (result == false) { return result; } } } return ValidateMediaObject(obj, hasParentID, throwException); }
private void ResultCreateObjectSink(ICpContainer parent, IUPnPMedia newObject, string newObjectID, string ResultXml, IUPnPMedia returnedObject, object Tag, UPnPInvokeException error, Exception xmlToObjectError) { if (error != null) { MessageBox.Show(this,xmlToObjectError.ToString(),"Create Object Server Error",MessageBoxButtons.OK,MessageBoxIcon.Error); return; } if (xmlToObjectError != null) { MessageBox.Show(this,xmlToObjectError.ToString(),"Create Object Response Error",MessageBoxButtons.OK,MessageBoxIcon.Error); return; } IUPnPMedia original = (IUPnPMedia) Tag; for (int i=0; i < original.Resources.Length; i++) { parent.RequestImportResource2(new Uri(((IMediaResource)original.Resources[i]).ContentUri), (IMediaResource) returnedObject.Resources[i], null, new OpenSource.UPnP.AV.MediaServer.CP.CpMediaDelegates.Delegate_ResultImportResource2(ResultImportResource2Sink)); } //newObject // foreach (IMediaResource resource in returnedObject.Resources) // { // parent.RequestImportResource2(new Uri(((IMediaResource)original.Resources[0]).ContentUri), resource, null, new OpenSource.UPnP.AV.MediaServer.CP.CpMediaDelegates.Delegate_ResultImportResource2(ResultImportResource2Sink)); // } }
/// <summary> /// Validates an <see cref="IUPnPMedia"/> object for basic schema compliance. /// </summary> /// <param name="obj"></param> /// <param name="hasParentID">If true, then "obj" should have proper parentID information.</param> /// <param name="throwException">If true, then any error will cause an exception to be thrown.</param> /// <returns>True, if the media object is valid.</returns> public static bool ValidateMediaObject (IUPnPMedia obj, bool hasParentID, bool throwException) { if (obj.ID == null) { if (throwException) { throw new Error_BadMetadata("ObjectID is null."); } return false; } else if (obj.ID == "") { if (throwException) { throw new Error_BadMetadata("Object ID is an empty string."); } return false; } else if (obj.Title == null) { if (throwException) { throw new Error_BadMetadata("Title is null for ObjectID='" + obj.ID+ "'."); } return false; } else if (obj.Title.Trim() == "") { if (throwException) { throw new Error_BadMetadata("Title contains only white-space characters for ObjectID='" + obj.ID+ "'."); } return false; } else if (obj.Class == null) { if (throwException) { throw new Error_BadMetadata("Media class is null for ObjectID='" + obj.ID+ "'."); } return false; } else if (obj.Class == MediaClass.NullMediaClass) { if (throwException) { throw new Error_BadMetadata("Media class is NullMediaClass for ObjectID='" + obj.ID+ "'."); } return false; } else if (obj.Class.FullClassName == null) { if (throwException) { throw new Error_BadMetadata("Media class FullClassName is null for ObjectID='" + obj.ID+ "'."); } return false; } else if (! ((obj.Class.FullClassName.StartsWith("object.item")) || (obj.Class.FullClassName.StartsWith("object.container")))) { if (throwException) { throw new Error_BadMetadata("Media class " +obj.Class.FullClassName+ " does not begin with object.item or object.container."); } return false; } else if (obj.IsContainer != obj.Class.IsContainer) { if (throwException) { throw new ApplicationException("IUPnPMedia.IsContainer != IUPnPMedia.Class.IsContainer"); } return false; } else if (obj.IsItem != obj.Class.IsItem) { if (throwException) { throw new ApplicationException("IUPnPMedia.IsItem != IUPnPMedia.Class.IsItem"); } return false; } else if (obj.IsContainer == obj.Class.IsItem) { if (throwException) { throw new ApplicationException("IUPnPMedia.IsContainer == IUPnPMedia.Class.IsItem"); } return false; } else if ((obj.IsContainer) && ((obj is IMediaContainer) == false)) { if (throwException) { throw new ApplicationException("ObjectID='" +obj.ID+ "' has IsContainer=true, but it does not implement IMediaContainer."); } return false; } else if ((obj.IsItem) && ((obj is IMediaItem) == false)) { if (throwException) { throw new ApplicationException("ObjectID='" +obj.ID+ "' has IsItem=true, but it does not implement IMediaItem."); } return false; } else if ((hasParentID) && (obj.ParentID == null)) { if (throwException) { throw new Error_BadMetadata("ParentID is null when it should be non-null."); } return false; } else if ((hasParentID) && (obj.ParentID.Trim() == "")) { if (throwException) { throw new Error_BadMetadata("ParentID contains only white-space characters."); } return false; } return true; }
private void ResultImportResource2SinkEx(System.Uri importFromThis, IUPnPMedia owner, IMediaResource importToThis, IResourceTransfer transferObject, object Tag, UPnPInvokeException error) { new TransferForm(transferObject).Show(); }
/// <summary> /// Updates the metadata and resources of this instance to match /// the information of the provided /// <see cref="IDvMedia"/> instance. /// </summary> /// <param name="newObj">the object contain</param> /// <exception cref="InvalidCastException"> /// Throws an exception if the provided object's /// resources include non-<see cref="IDvResource"/> objects. /// </exception> public override void UpdateObject(IUPnPMedia newObj) { foreach (IDvResource res in newObj.Resources); base.UpdateObject(newObj); this.NotifyRootOfChange(); }
/// <summary> /// Evaluates a subexpression of a whole expression. /// </summary> /// <param name="media">the media object with the metadata</param> /// <param name="prop">the property/attribute metadata to examine</param> /// <param name="op">the operator to use for examination</param> /// <param name="val">the value to compare against in string form</param> /// <returns></returns> /// <exception cref="OpenSource.UPnP.AV.CdsMetadata.Error_MalformedSearchCriteria"> /// Thrown when the expression provided at constructor time could not /// be used to evaluate the media because of syntax errors in /// the expression. /// </exception> private bool Evaluate(IUPnPMedia media, string prop, OperatorTokens op, string val) { bool result = false; TagExtractor te = (TagExtractor)this.m_PE[prop]; IList values = te.Extract(media); if (op == OperatorTokens.Exists) { bool testVal = (string.Compare(val, "true", true) == 0); result = ( ((values.Count > 0) && (testVal)) || ((values.Count == 0) && (testVal == false)) ); } else { foreach (object testVal in values) { int opCode = (int)op; if ((opCode >= (int)OperatorTokens.Equal) && (opCode <= (int)OperatorTokens.GreaterThanEqualTo)) { // Compare using a relational operator // try { int relResult = MetadataValueComparer.CompareTagValues(testVal, val, this.IgnoreCase); if (relResult == 0) { result = true; break; } } catch //(Exception e) { string opString = Enum.GetName(typeof(OperatorTokens), opCode); throw new Error_MalformedSearchCriteria("(" + val + ") " + opString + " " + testVal.ToString() + ") could not occur."); } } else if (op == OperatorTokens.Contains) { string tv = testVal.ToString(); int pos = tv.IndexOf(val); result = (pos >= 0); } else if (op == OperatorTokens.DoesNotContain) { string tv = testVal.ToString(); int pos = tv.IndexOf(val); result = (pos < 0); } else if (op == OperatorTokens.DerivedFrom) { string tv = testVal.ToString(); result = tv.StartsWith(val); } } } return(result); }
private void Sink_OnBrowse(CpMediaServer server, System.String ObjectID, OpenSource.UPnP.AV.CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, UPnPInvokeException e, Exception parseError, object _Tag, IUPnPMedia[] Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID) { IMediaContainer[] tagC, ec; bool ok = true; bool nomore = false; // ensure we're processing results for the current context lock (this) { tagC = (IMediaContainer[]) _Tag; ec = this.CurrentContext.EntireContext; for (int i=0; i < ec.Length; i++) { if (ec[i] != tagC[i]) { ok = false; break; } } } if (ok) { // results are for current context, merge metadata results // with existing child list if ((e == null) && (parseError == null)) { lock (this) { // add to our media object this.m_Children.AddRange(Result); this.CurrentContext.ContainerContext.AddObjects(Result, true); if ( ((this.m_Children.Count < TotalMatches) && (NumberReturned > 0)) || ((TotalMatches == 0) && (NumberReturned > 0)) ) { // more items to come this.m_CurrentIndex = NumberReturned; } else { // no more items, prune children from m_Container ArrayList remove = new ArrayList(); foreach (IUPnPMedia m1 in this.CurrentContext.ContainerContext.CompleteList) { bool found = false; foreach (IUPnPMedia m2 in this.m_Children) { if (m1 == m2) { found = true; break; } } if (found == false) { remove.Add(m1); } } this.CurrentContext.ContainerContext.RemoveObjects(remove); nomore = true; } } if (this.OnIncrementalUpdate != null) { this.OnIncrementalUpdate(this, Result); } if (nomore) { if (this.OnRefreshComplete != null) { IUPnPMedia[] list = (IUPnPMedia[]) this.m_Children.ToArray(typeof(IUPnPMedia)); this.OnRefreshComplete(this, list); } } } else { // error occurred with the results... // how should we report this? } } }
internal bool IsMatch(IUPnPMedia mediaObj, bool returnFalseIfMatchedAlready) { if (returnFalseIfMatchedAlready) { if (this.m_Matches.Contains(mediaObj)) { return false; } } return this.IsMatch(mediaObj); }
private void Sink_OnBrowse(CpMediaServer server, System.String ObjectID, OpenSource.UPnP.AV.CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, UPnPInvokeException e, Exception parseError, object _Tag, IUPnPMedia[] Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID) { if (server == this.m_Server) { if (ObjectID == this.m_Context) { if (_Tag == this.m_Container) { if ((e != null) || (parseError != null)) { //error encountered } else { // add children this.m_Children.AddRange(Result); this.m_Container.AddObjects(Result, true); if (this.OnIncrementalUpdate != null) { this.OnIncrementalUpdate(this, Result); } if ( ((this.m_Children.Count == TotalMatches) && (NumberReturned > 0)) || ((TotalMatches == 0) && (NumberReturned > 0)) ) { // more items to come this.m_CurrentIndex = NumberReturned; DoNextBrowse(); } else { lock (this) { // no more items, prune children from m_Container ArrayList remove = new ArrayList(); foreach (IUPnPMedia m1 in this.m_Container.CompleteList) { bool found = false; foreach (IUPnPMedia m2 in this.m_Children) { if (m1 == m2) { found = true; break; } } if (found == false) { remove.Add(m1); } } this.m_Container.RemoveObjects(remove); } if (this.OnRefreshComplete != null) { IUPnPMedia[] list = (IUPnPMedia[]) this.m_Children.ToArray(typeof(IUPnPMedia)); this.OnRefreshComplete(this, list); } } } } } } }
public void CompareResultsAgainstExpected(CdsBrowseSearchResults br, IList expectedResults, ref UPnPTestStates state, CdsSubTestArgument arg, BrowseInput input, bool strictOrder) { if (br.WorstError >= UPnPTestStates.Failed) { throw new TerminateEarly("\"" + this.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned with an error or had problems with the DIDL-Lite."); } else { if (br.MediaObjects.Count != expectedResults.Count) { throw new TerminateEarly("\"" + this.Name + "\" did a " + input.PrintBrowseParams() + " and it should have returned " + expectedResults.Count + " media objects. DIDL-Lite contained " + br.MediaObjects.Count + " media objects. DIDL-Lite => " + br.Result); } bool warnResults = false; for (int i = 0; i < br.MediaObjects.Count; i++) { IUPnPMedia gotThis = (IUPnPMedia)br.MediaObjects[i]; IUPnPMedia expectedMedia = (IUPnPMedia)expectedResults[i]; if (gotThis.ID == expectedMedia.ID) { //arg.TestGroup.AddEvent(LogImportance.Remark, this.Name, "\""+this.Name+"\" did a " +input.PrintBrowseParams()+ " and encountered no errors in the results."); } else { bool failed = false; if ((input.SortCriteria == null) || (input.SortCriteria == "")) { failed = true; } else { // Use this sorter to test for value-equality in situations where the expected order didn't match. // We need to do this because two media objects may be value-equivalent according to a sorting // algorithm, in which case there's no way to really distinguish what order they should be in. IMediaSorter sorter2 = new MediaSorter(false, input.SortCriteria); int cmp = sorter2.Compare(gotThis, expectedMedia); if (cmp != 0) { arg.TestGroup.AddEvent(LogImportance.Medium, this.Name, "\"" + this.Name + "\" found media object ID=\"" + gotThis.ID + "\" when it expected to find \"" + expectedMedia.ID + "\" and they are not equal in their sorted order."); warnResults = true; } else { if (strictOrder == false) { arg.TestGroup.AddEvent(LogImportance.Low, this.Name, "\"" + this.Name + "\" found media object ID=\"" + gotThis.ID + "\" when it expected to find \"" + expectedMedia.ID + "\" but since they are effectively value-equivalent, the ordering is OK."); } else { failed = true; } } } if (failed) { StringBuilder msg = new StringBuilder(); msg.AppendFormat("\"{0}\" did a {1} and the order of object ID's in the result conflicts with previous browse requests."); msg.AppendFormat("\r\n\r\nReceived objects in order by ID: "); int z = 0; foreach (IUPnPMedia em in br.MediaObjects) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.Append("\r\n\r\nThe expected order by ID is: "); z = 0; foreach (IUPnPMedia em in expectedResults) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.AppendFormat(".\r\n\r\nDIDL-Lite ==> {0}", br.Result); throw new TerminateEarly(msg.ToString()); } } } if (warnResults == false) { arg.TestGroup.AddEvent(LogImportance.Remark, this.Name, "\"" + this.Name + "\" did a " + input.PrintBrowseParams() + " and encountered no errors or warnings in the results."); } else { StringBuilder msg = new StringBuilder(); msg.AppendFormat("WARNING: \"{0}\" did a {1} and \r\nreceived results in the following order by ID: ", this.Name, input.PrintBrowseParams()); int z = 0; foreach (IUPnPMedia em in br.MediaObjects) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.Append("\r\n\r\nThe expected order by ID is: "); z = 0; foreach (IUPnPMedia em in expectedResults) { if (z > 0) { msg.Append(","); } msg.AppendFormat("\"{0}\"", em.ID); z++; } msg.AppendFormat(".\r\n\r\nDIDL-Lite ==> {0}", br.Result); // warn state = UPnPTestStates.Warn; arg._TestGroup.AddEvent(LogImportance.Medium, this.Name, msg.ToString()); } } }
/// <summary> /// Indicates vendor specific UPNP error code of 802. /// </summary> /// <param name="obj">The IUPnPMedia instance that already has a parent.</param> public Error_MediaObjectHasParent(IUPnPMedia obj) : base(802, "The media object (@id=\"" + obj.ID + "\") already has a parent (@parentID=\"" + obj.ParentID + "\").") { MediaObj = obj; }
/// <summary> /// /// </summary> /// <param name="mo"></param> /// <param name="writeProperties"></param> /// <param name="shouldPrintResources"></param> /// <param name="writeResources"></param> /// <param name="writeDescNodes"></param> /// <param name="formatter"></param> /// <param name="data"></param> /// <param name="xmlWriter"></param> public static void WriteInnerXml ( IUPnPMedia mo, DelegateWriteProperties writeProperties, DelegateShouldPrintResources shouldPrintResources, DelegateWriteResources writeResources, DelegateWriteDescNodes writeDescNodes, ToXmlFormatter formatter, ToXmlData data, XmlTextWriter xmlWriter ) { // When serializing the properties, resources, and desc nodes, // we must always write the inner xml, the value, and the element // declaration. Save the original values, print these portions // of the DIDL-Lite and then revert back. ToXmlData d2 = data; data.IncludeElementDeclaration = true; data.IncludeInnerXml = true; data.IncludeValue = true; if (writeProperties != null) { writeProperties(mo, data, xmlWriter); } if (writeResources != null) { writeResources(mo, shouldPrintResources, formatter, data, xmlWriter); } if (writeDescNodes != null) { writeDescNodes(mo, data, xmlWriter); } data.IncludeElementDeclaration = d2.IncludeElementDeclaration; data.IncludeInnerXml = d2.IncludeInnerXml; data.IncludeValue = d2.IncludeValue; IMediaContainer mc = mo as IMediaContainer; if (mc != null) { if (data.IsRecursive) { foreach (IUPnPMedia child in mc.CompleteList) { ToXmlFormatter f2 = formatter; f2.StartElement = null; f2.EndElement = null; f2.WriteInnerXml = null; f2.WriteValue = null; child.ToXml(f2, data, xmlWriter); } } } }
/// <summary> /// Indicates vendor specific UPNP error code of 804. /// </summary> /// <param name="obj1">The object that was getting updated.</param> /// <param name="obj2">The object with the new metadata and resources.</param> public Error_BaseClassMisMatch(IUPnPMedia obj1, IUPnPMedia obj2) : base(804, "Cannot update a media object with class \"" + obj1.Class.ToString() + "\" with metadata from a class \"" + obj2.Class.ToString() + "\".") { MediaObj = obj1; UpdateWithThis = obj2; }
/// <summary> /// Returns true, if the specified media object is a child of the container. /// </summary> /// <param name="obj">IUPnPMedia object</param> /// <returns>True, if the "obj" is a child.</returns> protected bool HasChild(IUPnPMedia obj) { bool result = false; this.m_LockListing.AcquireReaderLock(-1); if (this.m_Listing != null) { foreach (IUPnPMedia child in this.m_Listing) { if (child == obj) { result = true; break; } } } this.m_LockListing.ReleaseReaderLock(); return result; }
/// <summary> /// /// </summary> /// <param name="parent"></param> /// <param name="cds"></param> /// <param name="test"></param> /// <param name="arg"></param> /// <param name="details"></param> /// <param name="C"></param> /// <returns></returns> /// <exception cref="TerminateEarly"> /// </exception> public static ArrayList GetContainerChildrenAndValidate(IMediaContainer parent, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details, Queue C) { uint totalExpected = uint.MaxValue; uint currentChild = 0; ArrayList children = new ArrayList(); while (currentChild < totalExpected) { BrowseInput input = new BrowseInput(); input.ObjectID = parent.ID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; input.Filter = "*"; input.StartingIndex = currentChild; input.RequestedCount = 1; input.SortCriteria = ""; string containerID = parent.ID; if (currentChild == 0) { test.SetExpectedTestingTime((++details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress(details.TotalBrowseRequests * 30); } CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress((details.TotalBrowseRequests) * 30); if (results.WorstError >= UPnPTestStates.Failed) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " + input.PrintBrowseParams() + " returned with an error or had problems with the DIDL-Lite."); } else { if (results.NumberReturned != 1) { if (currentChild != 0) { results.SetError(UPnPTestStates.Failed); arg._TestGroup.AddEvent(LogImportance.Low, test.Name, "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" + results.NumberReturned + " when it should logically be 1."); } } if (results.TotalMatches != totalExpected) { if (currentChild != 0) { results.SetError(UPnPTestStates.Failed); arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" + results.TotalMatches + " when it should logically be " + totalExpected + " as reported in an earlier Browse request. This portion of the test requires that a MediaServer device not be in a state where its content hierarchy will change."); } else { totalExpected = results.TotalMatches; if (totalExpected > 0) { details.ExpectedTotalBrowseRequests += ((int)results.TotalMatches * 2) - 1; test.SetExpectedTestingTime((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress(details.TotalBrowseRequests * 30); } } } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { IUPnPMedia child = results.MediaObjects[0] as IUPnPMedia; if (child == null) { throw new TestException("\"" + test.Name + "\"" + " has a TEST LOGIC ERROR. Browse returned without errors but the child object's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } // ensure no duplicates in object ID foreach (IUPnPMedia previousChild in details.AllObjects) { if (previousChild.ID == child.ID) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned an object with ID=\"" + child.ID + "\" which conflicts with a previously seen media object in ParentContainerID=\"" + previousChild.ParentID + "\"."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } // ensure updateID is the same between BrowseDirectChildren and earlier BrowseMetadata. try { uint previousUpdateID = (uint)parent.Tag; if (results.UpdateID != previousUpdateID) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned an UpdateID=" + results.UpdateID + " whilst an UpdateID=" + previousUpdateID + " was obtained in a previous call for ContainerID=\"" + parent.ID + "\" with BrowseMetadata."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } catch (TerminateEarly te) { throw te; } catch (Exception e) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Error comparing UpdateID values", parent, e); } // add the child to lists: C, parent's child list, and Allobjects try { parent.AddObject(child, false); } catch (Exception e) { AddObjectError aoe = new AddObjectError(); aoe.Parent = parent; aoe.Child = child; throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the child object could not be added to its parent.", aoe, e); } details.AllObjects.Add(child); children.Add(child); if (child.IsContainer) { C.Enqueue(child); details.TotalContainers++; } else { details.TotalItems++; } // // Do a BrowseMetadata and check to see if the XML values are the same. // CdsBrowseSearchResults compareResults = CheckMetadata(child, cds, test, arg, details); if (compareResults.InvokeError != null) { arg._TestGroup.AddEvent(LogImportance.High, test.Name, test.Name + ": Browse(BrowseDirectChildren,StartingIndex=" + currentChild + ",RequestedCount=0) on ContainerID=[" + containerID + "] succeeded with warnings because a BrowseMetadata request was rejected by the CDS."); } else if (compareResults.ResultErrors.Count > 0) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " failed because a BrowseMetadata request succeeded but the DIDL-Lite could not be represented in object form. Invalid DIDL-Lite is most likely the cause."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } else if (compareResults.WorstError >= UPnPTestStates.Failed) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " failed because one or more child object's failed a comparison of results between BrowseDirectChildren and BrowseMetadata or encountered some other critical error in that process."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } else { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " succeeded."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } // // Track the metadata properties found so far // as we may use them in Browse SortCriteria // // standard top-level attributes Tags T = Tags.GetInstance(); AddTo(details.PropertyNames, "@" + T[_ATTRIB.id]); AddTo(details.PropertyNames, "@" + T[_ATTRIB.parentID]); AddTo(details.PropertyNames, "@" + T[_ATTRIB.restricted]); if (child.IsContainer) { if (child.IsSearchable) { AddTo(details.PropertyNames, "@" + T[_ATTRIB.searchable]); AddTo(details.PropertyNames, T[_DIDL.Container] + "@" + T[_ATTRIB.searchable]); } AddTo(details.PropertyNames, T[_DIDL.Container] + "@" + T[_ATTRIB.id]); AddTo(details.PropertyNames, T[_DIDL.Container] + "@" + T[_ATTRIB.parentID]); AddTo(details.PropertyNames, T[_DIDL.Container] + "@" + T[_ATTRIB.restricted]); } else if (child.IsItem) { if (child.IsReference) { AddTo(details.PropertyNames, "@" + T[_ATTRIB.refID]); AddTo(details.PropertyNames, T[_DIDL.Item] + "@" + T[_ATTRIB.refID]); } AddTo(details.PropertyNames, T[_DIDL.Item] + "@" + T[_ATTRIB.id]); AddTo(details.PropertyNames, T[_DIDL.Item] + "@" + T[_ATTRIB.parentID]); AddTo(details.PropertyNames, T[_DIDL.Item] + "@" + T[_ATTRIB.restricted]); } // standard metadata IMediaProperties properties = child.MergedProperties; IList propertyNames = properties.PropertyNames; foreach (string propertyName in propertyNames) { if (details.PropertyNames.Contains(propertyName) == false) { details.PropertyNames.Add(propertyName); // add attributes if they are not added IList propertyValues = properties[propertyName]; foreach (ICdsElement val in propertyValues) { ICollection attributes = val.ValidAttributes; foreach (string attribName in attributes) { StringBuilder sbpn = new StringBuilder(); sbpn.AppendFormat("{0}@{1}", propertyName, attribName); string fullAttribName = sbpn.ToString(); AddTo(details.PropertyNames, fullAttribName); } } } // resources IList resources = child.MergedResources; foreach (IMediaResource res in resources) { ICollection attributes = res.ValidAttributes; foreach (string attribName in attributes) { string name1 = "res@" + attribName; string name2 = "@" + attribName; AddTo(details.PropertyNames, name1); AddTo(details.PropertyNames, name2); } } if (resources.Count > 0) { AddTo(details.PropertyNames, T[_DIDL.Res]); } } } else { if (results.TotalMatches > 0) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " + results.MediaObjects.Count + " media objects."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } } else { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } currentChild++; } return(children); }
/// <summary> /// Indicates vendor specific UPNP error code of 803. /// </summary> /// <param name="obj">The offending IUPnPMedia that was sent to the container for insertion.</param> public Error_DuplicateIdException(IUPnPMedia obj) : base(803, "The media object (@id=\"" + obj.ID + "\") conflicts with another media object with the same ID.") { MediaObj = obj; }
/// <summary> /// This method adds an <see cref="IUPnPMedia"/> (container or item) as a child /// of this container. /// </summary> /// <param name="newObject">the new container or item that should be added</param> /// <param name="overWrite">if true, the method will overwrite a current child if it has the same ID</param> /// <exception cref="Error_DuplicateIdException"> /// Thrown if the object being added has the same ID as an existing child. /// </exception> /// <exception cref="Error_MediaObjectHasParent"> /// Thrown if the object being added already is a child of another container. /// </exception> public virtual void AddObject(IUPnPMedia newObject, bool overWrite) { IUPnPMedia errorParent = null; IUPnPMedia errorDuplicate = null; try { this.m_LockListing.AcquireWriterLock(-1); if (this.m_Listing == null) { this.m_Listing = new ArrayList(); } if (newObject.Parent != null) { if (newObject.Parent != this) { errorParent = newObject; } } try { HashingMethod.Set(this.m_Listing, newObject, overWrite); if (newObject != null) { newObject.Parent = this; } } catch (KeyCollisionException) { errorDuplicate = newObject; } } finally { this.m_LockListing.ReleaseWriterLock(); } if (errorParent != null) { throw new Error_MediaObjectHasParent(errorParent); } else if (errorDuplicate != null) { throw new Error_DuplicateIdException(errorDuplicate); } }
/// <summary> /// Indicates vendor specific UPNP error code of 810. /// </summary> /// <param name="obj"></param> public Error_ObjectIsContainerAndItem(IUPnPMedia obj) : base(810, "Cannot create an object that is both an item and a container.") { this.BadObject = obj; }
/// <summary> /// Removes an object from the child list. /// </summary> /// <param name="removeThis">Mediaobject to remove</param> public virtual void RemoveObject (IUPnPMedia removeThis) { try { this.m_LockListing.AcquireWriterLock(-1); if (this.m_Listing != null) { int i = HashingMethod.Get(this.m_Listing, removeThis); if (i >= 0) { IUPnPMedia obj = (IUPnPMedia) this.m_Listing[i]; obj.Parent = null; this.m_Listing.RemoveAt(i); } if (this.m_Listing.Count == 0) { this.m_Listing = null; } } } finally { this.m_LockListing.ReleaseWriterLock(); } }