public override void Init(INakedObjectAdapter collection, INakedObjectAdapter[] initData) { IList newCollection = CollectionUtils.CloneCollectionAndPopulate(collection.Object, initData.Select(no => no.Object)); collection.ReplacePoco(newCollection.AsQueryable()); }
/// <summary> /// Gets the choices for the currently selected category. /// </summary> protected List <WorklistClassSummary> GetWorklistClassChoicesForCategory(string category) { return(CollectionUtils.Select(_worklistClasses, delegate(WorklistClassSummary wc) { return wc.CategoryName == category; })); }
private static IList <DicomAttributeCollection> Convert <T>(IList <T> identifiers) where T : Identifier, new() { return(CollectionUtils.Map <T, DicomAttributeCollection>(identifiers, delegate(T id) { return id.ToDicomAttributeCollection(); })); }
/// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract" /> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary <,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary <,>))) { CreatedType = typeof(Dictionary <,>).MakeGenericType(keyType, valueType); } #if HAVE_READ_ONLY_COLLECTIONS IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary <,>)); #endif } #if HAVE_READ_ONLY_COLLECTIONS else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary <,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary <,>))) { CreatedType = typeof(ReadOnlyDictionary <,>).MakeGenericType(keyType, valueType); } IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary <object, object>); } } if (keyType != null && valueType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor( CreatedType, typeof(KeyValuePair <,>).MakeGenericType(keyType, valueType), typeof(IDictionary <,>).MakeGenericType(keyType, valueType)); #if HAVE_FSHARP_TYPES if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { Type tempDictioanryType; // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary <,>), out tempDictioanryType)) { ShouldCreateWrapper = true; } } #endif Type immutableCreatedType; ObjectConstructor <object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } }
public void TestXmlDeserializationFaultTolerance() { // if you encounter "unspecified errors" during compile, reformat the test data - csc has a maximum line/statement length (particularly important during pdb generation) const string testXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + "<ExternalCollection>\r\n" + " <Junk>\r\n" + " <Junk2>\r\n" + " <Junk3>\r\n" + " <Junk4 />\r\n" + " </Junk3>\r\n" + " </Junk2>\r\n" + " </Junk>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external1\" Label=\"Label1\" Enabled=\"True\" WindowStyle=\"Normal\">\r\n" + " <Data>Data1</Data>\r\n" + " </MockXmlSerializableExternal>\r\n" + " </External>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + " <badgarbled xml\"\">>>> ]]>\r\n" + " </IExternal>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external3\" Label=\"\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\">\r\n" + " </IExternal>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external4\" Label=\"\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + " <Junk>\r\n" + " <Junk2 />\r\n" + " </Junk>]]>\r\n" + " </IExternal>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external5\" Label=\"\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal\">\r\n" + " <MockBrokenExternal Name=\"bad1\" Label=\"dfdsfds\" Enabled=\"True\" WindowStyle=\"Normal\">\r\n" + " </MockBrokenExternal>\r\n" + " </External>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external6\" Label=\"\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal\" />\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal\">\r\n" + " <MockXmlSerializableExternal Name=\"external7\" Label=\"\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <External Type=\"Macro.ImageViewer.Externals.Tests.MockBrokenExternal\">\r\n" + " <MockBrokenExternal Name=\"bad1\" Label=\"dfdsfds\" Enabled=\"True\" WindowStyle=\"Normal\" />\r\n" + " </External>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.Tests.MockXmlSerializableExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + " <MockXmlSerializableExternal Name=\"external2\" Label=\"Label2\" Enabled=\"False\" WindowStyle=\"Hidden\">\r\n" + " <Data>Data2</Data>\r\n" + " </MockXmlSerializableExternal>]]>\r\n" + " </IExternal>\r\n" + "</ExternalCollection>"; var expectedExternal1 = new MockXmlSerializableExternal { Name = "external1", Label = "Label1", Enabled = true, WindowStyle = WindowStyle.Normal, Data = "Data1" }; var expectedExternal2 = new MockXmlSerializableExternal { Name = "external2", Label = "Label2", Enabled = false, WindowStyle = WindowStyle.Hidden, Data = "Data2" }; var expectedExternal3 = new MockXmlSerializableExternal { Name = "external3", Label = "" }; var expectedExternal4 = new MockXmlSerializableExternal { Name = "external4", Label = "" }; var expectedExternal5 = new MockXmlSerializableExternal { Name = "external5", Label = "" }; var expectedExternal6 = new MockXmlSerializableExternal { Name = "external6", Label = "" }; var expectedExternal7 = new MockXmlSerializableExternal { Name = "external7", Label = "" }; var collection = ExternalCollection.Deserialize(testXml); Assert.IsNotNull(collection, "Deserialization returned null"); Assert.AreEqual(7, collection.Count, "Deserialization returned collection with wrong number of entries"); var external1 = CollectionUtils.SelectFirst(collection, e => e.Name == "external1"); Assert.IsNotNull(external1, "Failed to deserialize external1"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external1, "external1: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal1, (MockXmlSerializableExternal)external1, "external1"); var external2 = CollectionUtils.SelectFirst(collection, e => e.Name == "external2"); Assert.IsNotNull(external2, "Failed to deserialize external2"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external2, "external2: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal2, (MockXmlSerializableExternal)external2, "external2"); var external3 = CollectionUtils.SelectFirst(collection, e => e.Name == "external3"); Assert.IsNotNull(external3, "Failed to deserialize external3"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external3, "external3: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal3, (MockXmlSerializableExternal)external3, "external3"); var external4 = CollectionUtils.SelectFirst(collection, e => e.Name == "external4"); Assert.IsNotNull(external4, "Failed to deserialize external4"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external4, "external4: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal4, (MockXmlSerializableExternal)external4, "external4"); var external5 = CollectionUtils.SelectFirst(collection, e => e.Name == "external5"); Assert.IsNotNull(external5, "Failed to deserialize external5"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external5, "external5: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal5, (MockXmlSerializableExternal)external5, "external5"); var external6 = CollectionUtils.SelectFirst(collection, e => e.Name == "external6"); Assert.IsNotNull(external6, "Failed to deserialize external6"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external6, "external6: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal6, (MockXmlSerializableExternal)external6, "external6"); var external7 = CollectionUtils.SelectFirst(collection, e => e.Name == "external7"); Assert.IsNotNull(external7, "Failed to deserialize external7"); Assert.IsInstanceOf(typeof(MockXmlSerializableExternal), external7, "external7: Wrong concrete implementation of IExternal"); AssertMockExternal(expectedExternal7, (MockXmlSerializableExternal)external7, "external7"); }
public override void AddChildren(ICollection <UIElement> childrenOut) { lock (Children.SyncRoot) CollectionUtils.AddAll(childrenOut, Children); }
public void AddScene(Scene scene) { CollectionUtils.Add(this.scenes, scene); }
public ITile SafeGet(string name) { return(CollectionUtils.SafeGet(cache, name)); }
private void DecodingThread(CancellationToken token) { for (; ;) { if (token.WaitHandle.WaitOne(1000)) { return; } DownloadItemInfo item = null; lock (_lockObject) { item = CollectionUtils.Unite(_volatileDownloadItemInfoManager, _downloadItemInfoManager) .Where(n => !_workingItems.Contains(n)) .Where(n => n.State == DownloadState.Decoding || n.State == DownloadState.ParityDecoding) .OrderBy(n => (n.Depth == n.Metadata.Depth) ? 0 : 1) .OrderBy(n => (n.State == DownloadState.Decoding) ? 0 : 1) .FirstOrDefault(); if (item != null) { _workingItems.Add(item); } } if (item == null) { continue; } try { if ((item.Depth == 0 && !_cacheManager.Contains(item.Metadata.Hash)) || (item.Depth > 0 && !item.Index.Groups.All(n => _existManager.GetCount(n) >= n.Hashes.Count() / 2))) { item.State = DownloadState.Downloading; } else { var hashes = new HashCollection(); var totalHashes = new HashCollection(); if (item.Depth == 0) { hashes.Add(item.Metadata.Hash); totalHashes.Add(item.Metadata.Hash); } else { try { foreach (var group in item.Index.Groups) { if (item.State == DownloadState.Error) { throw new OperationCanceledException(); } hashes.AddRange(_cacheManager.ParityDecoding(group, token).Result); } totalHashes.AddRange(item.Index.Groups.SelectMany(n => n.Hashes)); } catch (OperationCanceledException) { continue; } item.State = DownloadState.Decoding; } if (item.Depth < item.Metadata.Depth) { Index index; try { using (var stream = _cacheManager.Decoding(hashes)) using (var progressStream = new ProgressStream(stream, null, 1024 * 1024, token)) { if (item.State == DownloadState.Error) { throw new OperationCanceledException(); } if (progressStream.Length > item.MaxLength) { throw new ArgumentException(); } index = Index.Import(progressStream, _bufferManager); } } catch (OperationCanceledException) { continue; } lock (_lockObject) { if (item.Path != null) { _protectCacheInfoManager.Add(new ProtectCacheInfo(DateTime.UtcNow, totalHashes)); } this.CheckState(index); this.UncheckState(item.Index); item.Index = index; item.Depth++; item.State = DownloadState.Downloading; } } else { if (item.Path != null) { string filePath = null; try { token.ThrowIfCancellationRequested(); string targetPath; if (Path.IsPathRooted(item.Path)) { targetPath = item.Path; } else { targetPath = Path.GetFullPath(Path.Combine(_basePath, item.Path)); // ディレクトリトラバーサル対策 if (!targetPath.StartsWith(Path.GetFullPath(_basePath))) { targetPath = Path.GetFullPath(Path.Combine(_basePath, Path.GetFileName(item.Path))); } } Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); using (var inStream = _cacheManager.Decoding(hashes)) using (var outStream = DownloadManager.GetUniqueFileStream(targetPath + ".tmp")) using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 1024)) { filePath = outStream.Name; int readLength; while ((readLength = inStream.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0) { if (item.State == DownloadState.Error) { throw new OperationCanceledException(); } token.ThrowIfCancellationRequested(); outStream.Write(safeBuffer.Value, 0, readLength); } } File.Move(filePath, DownloadManager.GetUniqueFilePath(targetPath)); } catch (OperationCanceledException) { if (filePath != null) { File.Delete(filePath); } continue; } } lock (_lockObject) { if (item.Path != null) { _protectCacheInfoManager.Add(new ProtectCacheInfo(DateTime.UtcNow, totalHashes)); } item.ResultHashes.AddRange(hashes); item.State = DownloadState.Completed; } } } } catch (Exception e) { item.State = DownloadState.Error; Log.Error(e); } finally { _workingItems.Remove(item); } } }
protected object[] GetPropertyValues(object obj) { return(CollectionUtils.Map(_properties, (PropertyInfo property) => GetPropertyValue(obj, property)).ToArray()); }
private void DownloadingThread(CancellationToken token) { for (; ;) { if (token.WaitHandle.WaitOne(1000 * 10)) { return; } var items = new List <DownloadItemInfo>(); lock (_lockObject) { items.AddRange(CollectionUtils.Unite(_volatileDownloadItemInfoManager, _downloadItemInfoManager).ToArray() .Where(n => n.State == DownloadState.Downloading)); } foreach (var item in items) { try { if (!this.CheckSize(item)) { throw new ArgumentException("download size too large."); } if (item.Depth == 0) { if (!_cacheManager.Contains(item.Metadata.Hash)) { item.State = DownloadState.Downloading; _networkManager.Download(item.Metadata.Hash, DiffusionPriority.High); } else { item.State = DownloadState.Decoding; } } else { if (!item.Index.Groups.All(n => _existManager.GetCount(n) >= n.Hashes.Count() / 2)) { item.State = DownloadState.Downloading; foreach (var group in item.Index.Groups.Randomize()) { if (_existManager.GetCount(group) >= group.Hashes.Count() / 2) { continue; } foreach (var hash in _existManager.GetHashes(group, false)) { _networkManager.Download(hash, DiffusionPriority.Normal); } } } else { item.State = DownloadState.ParityDecoding; } } } catch (Exception e) { item.State = DownloadState.Error; Log.Error(e); } } } }
protected virtual void PrepareItemsOverride(bool force) { if (_panelTemplateApplied && _itemsHostPanel != null && !force) { return; } // Check properties which are necessary in each case if (ItemsPanel == null) { return; } ItemsPresenter presenter = FindItemsPresenter(); if (presenter == null) { return; } if (!_panelTemplateApplied) { _panelTemplateApplied = true; presenter.ApplyTemplate(ItemsPanel); _itemsHostPanel = null; } if (_itemsHostPanel == null) { _itemsHostPanel = presenter.ItemsHostPanel; } if (_itemsHostPanel == null) { return; } // Albert: We cannot exit the method if one of the styles is not set because the styles // might be found by the SkinEngine's automatic Style assignment (FrameworkElement.CopyDefaultStyle) //if (ItemContainerStyle == null || ItemTemplate == null) // return; IEnumerable itemsSource = ItemsSource; if (itemsSource == null) { // In this case, we must set up the items control using the Items property ItemCollection items = _items; ItemCollection preparedChildren = new ItemCollection(); bool setItems = false; if (items == null) { // Restore items from "ItemsSource mode" where they have been set to null items = new ItemCollection(); setItems = true; } foreach (object item in items) { object itemCopy = MpfCopyManager.DeepCopyWithFixedObject(item, this); // Keep this object as LogicalParent FrameworkElement element = itemCopy as FrameworkElement ?? PrepareItemContainer(itemCopy); if (element.Style == null && element is ContentControl) { element.Style = ItemContainerStyle; } element.LogicalParent = this; preparedChildren.Add(element); } presenter.SetDataStrings(BuildDataStrings(items)); SetPreparedItems(setItems, setItems ? items : null, true, preparedChildren); } else { IList <object> l = new List <object>(); ISynchronizable sync = itemsSource as ISynchronizable; if (sync != null) { lock (sync.SyncRoot) CollectionUtils.AddAll(l, itemsSource); } else { CollectionUtils.AddAll(l, itemsSource); } presenter.SetDataStrings(BuildDataStrings(l)); var vsp = _itemsHostPanel as IVirtualizingPanel; if (vsp != null) { // In this case, the VSP will generate its items by itself ListViewItemGenerator lvig = new ListViewItemGenerator(); lvig.Initialize(this, l, ItemContainerStyle, ItemTemplate, GroupingValueProvider, GroupingBindingWrapper == null ? null : GroupingBindingWrapper.Binding, GroupHeaderContainerStyle, GroupHeaderTemplate); SimplePropertyDataDescriptor dd; if (SimplePropertyDataDescriptor.CreateSimplePropertyDataDescriptor(this, "IsEmpty", out dd)) { SetValueInRenderThread(dd, l.Count == 0); } vsp.SetItemProvider(lvig); SetPreparedItems(true, null, false, null); } else { ItemCollection preparedItems = new ItemCollection(); preparedItems.AddAll(l.Select(PrepareItemContainer)); SetPreparedItems(true, null, true, preparedItems); } } }
/// <summary> /// Creates a new practitioner that is the result of merging the two specified practitioners. /// </summary> /// <param name="right"></param> /// <param name="left"></param> /// <param name="name"></param> /// <param name="licenseNumber"></param> /// <param name="billingNumber"></param> /// <param name="extendedProperties"></param> /// <param name="defaultContactPoint"></param> /// <param name="deactivatedContactPoints"></param> /// <param name="contactPointReplacements"></param> /// <returns></returns> public static ExternalPractitioner MergePractitioners( ExternalPractitioner right, ExternalPractitioner left, PersonName name, string licenseNumber, string billingNumber, IDictionary <string, string> extendedProperties, ExternalPractitionerContactPoint defaultContactPoint, ICollection <ExternalPractitionerContactPoint> deactivatedContactPoints, IDictionary <ExternalPractitionerContactPoint, ExternalPractitionerContactPoint> contactPointReplacements) { // sanity check if (Equals(right, left)) { throw new WorkflowException("Cannot merge a practitioner with itself."); } if (right.Deactivated || left.Deactivated) { throw new WorkflowException("Cannot merge a practitioner that is de-activated."); } if (right.IsMerged || left.IsMerged) { throw new WorkflowException("Cannot merge a practitioner that has already been merged."); } if (defaultContactPoint != null && defaultContactPoint.IsMerged) { throw new WorkflowException("Cannot assigned a merged contact point as default"); } // update properties on result record var result = new ExternalPractitioner { Name = name, LicenseNumber = licenseNumber, BillingNumber = billingNumber }; ExtendedPropertyUtils.Update(result.ExtendedProperties, extendedProperties); // construct the set of retained contact points var retainedContactPoints = new HashedSet <ExternalPractitionerContactPoint>(); retainedContactPoints.AddAll(contactPointReplacements.Values); // some of the replacement contact points are merged. This should not be allowed. if (CollectionUtils.Contains(contactPointReplacements.Values, cp => cp.IsMerged)) { throw new WorkflowException("Cannot replace a contact point with another that has already been merged."); } // add any existing contact point that was not in the replacement list (because it is implicitly being retained) foreach (var contactPoint in CollectionUtils.Concat(right.ContactPoints, left.ContactPoints)) { // No need to retain a merged contact point. Because its replacement would already be retained. if (!contactPointReplacements.ContainsKey(contactPoint) && !contactPoint.IsMerged) { retainedContactPoints.Add(contactPoint); } } // for all retained contact points, create a copy attached to the result practitioner, // and mark the original as having been merged into the copy foreach (var original in retainedContactPoints) { var copy = original.CreateCopy(result); result.ContactPoints.Add(copy); copy.IsDefaultContactPoint = original.Equals(defaultContactPoint); copy.MarkDeactivated(original.Deactivated || deactivatedContactPoints.Contains(original)); original.SetMergedInto(copy); } // for all replaced contact points, mark the original as being merged into the // copy of the replacement foreach (var kvp in contactPointReplacements) { kvp.Key.SetMergedInto(kvp.Value.MergedInto); } // mark both left and right as edited and merged foreach (var practitioner in new[] { right, left }) { practitioner.MarkEdited(); practitioner.SetMergedInto(result); } // mark the result as being edited result.MarkEdited(); return(result); }
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceURI == "http://www.w3.org/2000/xmlns/") { string prefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; manager.AddNamespace(prefix, attribute.Value); } } if (writePropertyName) { writer.WritePropertyName(GetPropertyName(node, manager)); } if (ValueAttributes(node.Attributes).Count() == 0 && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { // empty element writer.WriteNull(); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } } break; case XmlNodeType.Comment: if (writePropertyName) { writer.WriteComment(node.Value); } break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceURI == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) { return; } if (node.NamespaceURI == JsonNamespaceUri) { if (node.LocalName == "Array") { return; } } if (writePropertyName) { writer.WritePropertyName(GetPropertyName(node, manager)); } writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } }
public Scene RemoveScene(int index) { return((Scene)CollectionUtils.RemoveAt(this.scenes, index)); }
protected override bool IsCollectionField(string fieldName) { return(CollectionUtils.CollectionContainsIgnoringCase(OrganizationStructureStateDtoWrapper._collectionFieldNames, fieldName)); }
public static List <MappingAttribute> GetMappingAttributesForType(Type type) { return(CollectionUtils.ToList <MappingAttribute, object>(type.GetCustomAttributes(typeof(MappingAttribute), true))); }
public void TestLegacyXmlDeserialization() { // if you encounter "unspecified errors" during compile, reformat the test data - csc has a maximum line/statement length (particularly important during pdb generation) const string testXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + "<ExternalCollection>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.General.CommandLineExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + "<CommandLineExternal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n" + " <Name>external1</Name>\r\n" + " <Label>Label1</Label>\r\n" + " <Enabled>true</Enabled>\r\n" + " <WindowStyle>Normal</WindowStyle>\r\n" + " <Command>C:\\Temp\\CommandA.cmd</Command>\r\n" + " <WorkingDirectory>$DIRECTORY$</WorkingDirectory>\r\n" + " <Arguments />\r\n" + " <Username />\r\n" + " <Domain />\r\n" + " <AllowMultiValueFields>false</AllowMultiValueFields>\r\n" + "</CommandLineExternal>]]></IExternal>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.General.CommandLineExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + "<CommandLineExternal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n" + " <Name>external2</Name>\r\n" + " <Label>Label2</Label>\r\n" + " <Enabled>false</Enabled>\r\n" + " <WindowStyle>Hidden</WindowStyle>\r\n" + " <Command>\\ComputerA\\ShareB\\CommandC.cmd</Command>\r\n" + " <WorkingDirectory>$DIRECTORY$</WorkingDirectory>" + " <Arguments>\"$FILENAMEONLY$\"</Arguments>" + " <Username>\u5305\u9752\u5929</Username>" + " <Domain>\u958B\u5C01\u5E9C</Domain>" + " <AllowMultiValueFields>true</AllowMultiValueFields>\r\n" + " <MultiValueFieldSeparator>\" \"</MultiValueFieldSeparator>\r\n" + "</CommandLineExternal>]]></IExternal>\r\n" + " <IExternal Concrete-Type=\"Macro.ImageViewer.Externals.General.CommandLineExternal, Macro.ImageViewer.Externals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"><![CDATA[<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n" + "<CommandLineExternal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n" + " <Name>external3</Name>\r\n" + "</CommandLineExternal>]]></IExternal>\r\n" + "</ExternalCollection>"; var expectedExternal1 = new CommandLineExternal { Name = "external1", Label = "Label1", Enabled = true, WindowStyle = WindowStyle.Normal, Command = @"C:\Temp\CommandA.cmd", WorkingDirectory = "$DIRECTORY$", Arguments = "", Username = "", Domain = "", AllowMultiValueFields = false }; var expectedExternal2 = new CommandLineExternal { Name = "external2", Label = "Label2", Enabled = false, WindowStyle = WindowStyle.Hidden, Command = @"\ComputerA\ShareB\CommandC.cmd", WorkingDirectory = "$DIRECTORY$", Arguments = "\"$FILENAMEONLY$\"", Username = "******", Domain = "\u958B\u5C01\u5E9C", AllowMultiValueFields = true, MultiValueFieldSeparator = "\" \"" }; var expectedExternal3 = new CommandLineExternal { Name = "external3" }; var collection = ExternalCollection.Deserialize(testXml); Assert.IsNotNull(collection, "Deserialization returned null"); Assert.AreEqual(3, collection.Count, "Deserialization returned collection with wrong number of entries"); var external1 = CollectionUtils.SelectFirst(collection, e => e.Name == "external1"); Assert.IsNotNull(external1, "Failed to deserialize external1"); Assert.IsInstanceOf(typeof(CommandLineExternal), external1, "external1: Wrong concrete implementation of IExternal"); AssertCommandLineExternal(expectedExternal1, (CommandLineExternal)external1, "external1"); var external2 = CollectionUtils.SelectFirst(collection, e => e.Name == "external2"); Assert.IsNotNull(external2, "Failed to deserialize external2"); Assert.IsInstanceOf(typeof(CommandLineExternal), external2, "external2: Wrong concrete implementation of IExternal"); AssertCommandLineExternal(expectedExternal2, (CommandLineExternal)external2, "external2"); var external3 = CollectionUtils.SelectFirst(collection, e => e.Name == "external3"); Assert.IsNotNull(external3, "Failed to deserialize external3"); Assert.IsInstanceOf(typeof(CommandLineExternal), external3, "external3: Wrong concrete implementation of IExternal"); AssertCommandLineExternal(expectedExternal3, (CommandLineExternal)external3, "external3"); }
public static List <MappingAttribute> GetMappingAttributesForMember(MemberInfo member) { return(CollectionUtils.ToList <MappingAttribute, object>(member.GetCustomAttributes(typeof(MappingAttribute), true))); }
/// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract" /> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = IsArray && UnderlyingType.GetArrayRank() > 1; } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection <>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } else { CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); } if (underlyingType == typeof(IList)) { CreatedType = typeof(List <object>); } if (CollectionItemType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); } IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection <>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection <>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection <>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList <>))) { CreatedType = typeof(List <>).MakeGenericType(CollectionItemType); } #if HAVE_ISET if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet <>))) { CreatedType = typeof(HashSet <>).MakeGenericType(CollectionItemType); } #endif _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if HAVE_READ_ONLY_COLLECTIONS else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection <>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection <>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList <>))) { CreatedType = typeof(ReadOnlyCollection <>).MakeGenericType(CollectionItemType); } _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType); _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); #if HAVE_FSHARP_TYPES StoreFSharpListCreatorIfNecessary(underlyingType); #endif IsReadOnlyOrFixedSize = true; canDeserialize = HasParameterizedCreatorInternal; } #endif else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable <>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable <>))) { CreatedType = typeof(List <>).MakeGenericType(CollectionItemType); } _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); #if HAVE_FSHARP_TYPES StoreFSharpListCreatorIfNecessary(underlyingType); #endif if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParameterizedCreatorInternal; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; #if (NET20 || NET35) if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List <>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } #endif Type immutableCreatedType; ObjectConstructor <object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } }
protected override bool IsCollectionField(string fieldName) { return(CollectionUtils.CollectionContainsIgnoringCase(WarehouseStateDtoWrapper._collectionFieldNames, fieldName)); }
private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._typeNameAssemblyFormat != null) { serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; } if (settings._preserveReferencesHandling != null) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling != null) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling != null) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling != null) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling != null) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling != null) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling != null) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context != null) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent != null) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolver != null) { serializer.ReferenceResolver = settings.ReferenceResolver; } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.Binder != null) { serializer.Binder = settings.Binder; } // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling != null) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling != null) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling != null) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling != null) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling != null) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } if (settings._maxWritingDepthSet) { serializer._maxWritingDepth = settings._maxWritingDepth; serializer._maxWritingDepthSet = settings._maxWritingDepthSet; } serializer._isAutoCreateMemberValue = settings._isAutoCreateMemberValue; }
public void EmptyEnum() { IList <string> list = new List <string>(); Assert.That(CollectionUtils.ToString(list), Is.EqualTo("")); }
/// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary <,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary <,>))) { CreatedType = typeof(Dictionary <,>).MakeGenericType(keyType, valueType); } #if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary <,>)); #endif } #if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary <,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary <,>))) { CreatedType = typeof(ReadOnlyDictionary <,>).MakeGenericType(keyType, valueType); } IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary <object, object>); } } if (keyType != null && valueType != null) { ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(CreatedType, typeof(KeyValuePair <,>).MakeGenericType(keyType, valueType)); } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; if (DictionaryValueType != null) { _isDictionaryValueTypeNullableType = ReflectionUtils.IsNullableType(DictionaryValueType); } #if (NET20 || NET35) Type tempDictioanryType; // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (_isDictionaryValueTypeNullableType && (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary <,>), out tempDictioanryType))) { ShouldCreateWrapper = true; } #endif }
/// <summary> /// Threading function that takes care of loading. /// </summary> private static void LoadContent(object ThreadObject) { var loadingList = new List <ContentPreload>(); /** UI Textures **/ loadingList.AddRange( CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>( Enum.GetValues(typeof(FileIDs.UIFileIDs)), x => new ContentPreload { ID = (ulong)((long)x), Type = ContentPreloadType.Other } ) ); ///** Sim textures for CAS **/ loadingList.AddRange( CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>( Enum.GetValues(typeof(FileIDs.OutfitsFileIDs)), x => new ContentPreload { ID = (ulong)((long)x), Type = ContentPreloadType.Other } ) ); loadingList.AddRange( CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>( Enum.GetValues(typeof(FileIDs.AppearancesFileIDs)), x => new ContentPreload { ID = (ulong)((long)x), Type = ContentPreloadType.Other } ) ); loadingList.AddRange( CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>( Enum.GetValues(typeof(FileIDs.PurchasablesFileIDs)), x => new ContentPreload { ID = (ulong)((long)x), Type = ContentPreloadType.Other } ) ); loadingList.AddRange( CollectionUtils.Select <FileIDs.UIFileIDs, ContentPreload>( Enum.GetValues(typeof(FileIDs.ThumbnailsFileIDs)), x => new ContentPreload { ID = (ulong)((long)x), Type = ContentPreloadType.Other } ) ); var startTime = DateTime.Now; var totalItems = (float)loadingList.Count; loadingList.Shuffle(); var loadingListLength = loadingList.Count; for (var i = 0; i < loadingListLength; i++) { var item = loadingList[i]; try { ContentResource contentItem = null; contentItem = ContentManager.GetResourceInfo(item.ID); switch (item.Type) { case ContentPreloadType.UITexture: /** Apply alpha channel masking & load into GD **/ UIElement.StoreTexture(item.ID, contentItem, true, true); break; case ContentPreloadType.UITexture_NoMask: UIElement.StoreTexture(item.ID, contentItem, false, true); break; case ContentPreloadType.Other: ContentManager.TryToStoreResource(item.ID, contentItem); break; } } catch (Exception) { } PreloadProgress = i / totalItems; } var endTime = DateTime.Now; System.Diagnostics.Debug.WriteLine("Content took " + new TimeSpan(endTime.Ticks - startTime.Ticks).ToString() + " to load"); PreloadProgress = 1.0f; }
// because Sets don't implement IEnumerable<> private static bool IsGenericCollection(Type type) { return(CollectionUtils.IsGenericType(type, typeof(IEnumerable <>)) || CollectionUtils.IsGenericType(type, typeof(ISet <>))); }
protected virtual bool DoXmlLoad(out string submitFilePath) { submitFilePath = null; Type mappingAttributesType = typeof(Windsor.Node2008.WNOSPlugin.ICISNPDES_50.MappingAttributes); IDictionary <string, DbAppendSelectWhereClause> selectClauses = Windsor.Node2008.WNOSPlugin.ICISNPDES_50.PayloadData.GetDefaultSelectClauses(_stagingDao); List <Windsor.Node2008.WNOSPlugin.ICISNPDES_50.PayloadData> payloads = _objectsFromDatabase.LoadFromDatabase <Windsor.Node2008.WNOSPlugin.ICISNPDES_50.PayloadData>(_stagingDao, selectClauses, mappingAttributesType); // Remove payloads that don't contain any data if (payloads != null) { for (int i = payloads.Count - 1; i >= 0; i--) { if (CollectionUtils.IsNullOrEmpty(payloads[i].Items)) { // TSM: Is this log really necessary? //AppendAuditLogEvent(string.Format("The payload with operation \"{0}\" will not be included in the submission because it does not contain any data", payloads[i].Operation.ToString())); payloads.RemoveAt(i); } } } if (CollectionUtils.IsNullOrEmpty(payloads)) { _submissionTrackingDataType.WorkflowStatus = TransactionStatusCode.Completed; _submissionTrackingDataType.WorkflowStatusMessage = "The staging database does not contain any payloads to submit"; AppendAuditLogEvent(_submissionTrackingDataType.WorkflowStatusMessage + ", exiting plugin ..."); SubmissionTrackingTableHelper.Update(_stagingDao, _submissionTrackingDataTypePK, _submissionTrackingDataType); return(false); } AppendAuditLogEvent("The following ICIS payload(s) were loaded from the database: {0}", GetPayloadsDescription(payloads)); Windsor.Node2008.WNOSPlugin.ICISNPDES_50.Document document = new Document(); document.Payload = payloads.ToArray(); document.Header = CreateHeader(); string tempFolder = _settingsProvider.CreateNewTempFolderPath(); string tempXmlPath = Path.Combine(tempFolder, ICIS_SUBMISSION_XML_FILENAME); string tempZipPath = Path.Combine(tempFolder, ICIS_SUBMISSION_ZIP_FILENAME); try { AppendAuditLogEvent("Serializing ICIS payload(s) to xml ..."); _serializationHelper.Serialize(document, tempXmlPath); if (_validateXml) { ValidateXmlFileAndAttachErrorsAndFileToTransaction(tempXmlPath, "xml_schema.xml_schema.zip", null, _dataRequest.TransactionId); } _compressionHelper.CompressFile(tempXmlPath, tempZipPath); _documentManager.AddDocument(_dataRequest.TransactionId, CommonTransactionStatusCode.Completed, null, tempZipPath); } catch (Exception) { FileUtils.SafeDeleteFile(tempZipPath); throw; } finally { FileUtils.SafeDeleteFile(tempXmlPath); } submitFilePath = tempZipPath; return(true); }
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); _serializeStack.Add(values); bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, CollectionUtils.ArrayEmpty <int>()); if (hasWrittenMetadataObject) { writer.WriteEndObject(); } _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, values); }
protected override bool IsCollectionField(string fieldName) { return(CollectionUtils.CollectionContainsIgnoringCase(_collectionFieldNames, fieldName)); }
// Calls the block on every attachment dictionary. The block can return a different dictionary, // which will be replaced in the rev's properties. If it returns nil, the operation aborts. // Returns YES if any changes were made. public virtual bool MutateAttachments(CollectionUtils.Functor<IDictionary<string, object>, IDictionary<string, object>> functor) { { IDictionary<string, object> properties = GetProperties(); IDictionary<string, object> editedProperties = null; IDictionary<string, object> attachments = (IDictionary<string, object>)properties .Get("_attachments"); IDictionary<string, object> editedAttachments = null; foreach (string name in attachments.Keys) { IDictionary<string, object> attachment = (IDictionary<string, object>)attachments .Get(name); IDictionary<string, object> editedAttachment = functor.Invoke(attachment); if (editedAttachment == null) { return false; } // block canceled if (editedAttachment != attachment) { if (editedProperties == null) { // Make the document properties and _attachments dictionary mutable: editedProperties = new Dictionary<string, object>(properties); editedAttachments = new Dictionary<string, object>(attachments); editedProperties.Put("_attachments", editedAttachments); } editedAttachments.Put(name, editedAttachment); } } if (editedProperties != null) { SetProperties(editedProperties); return true; } return false; } }
internal string Execute(DateTime changeDate, string flowName, string targetXmlPath, ISerializationHelper serializationHelper, ICompressionHelper compressionHelper, IObjectsFromDatabase objectsFromDatabase, IAppendAuditLogEvent appendAuditLogEvent) { appendAuditLogEvent.AppendAuditLogEvent("Querying FACID data ..."); Dictionary <string, DbAppendSelectWhereClause> selectClauses = new Dictionary <string, DbAppendSelectWhereClause>(); string facIdQuery = string.Format("SELECT ST_FAC_IND FROM CHANGED_FACILITIES WHERE IS_DELETED = 0 AND UPPER(FLOW_TYPE) = UPPER('{0}') AND UPDATE_DATE >= '{1}'", flowName, changeDate.ToString("dd-MMM-yyyy").ToUpper()); string whereQuery = string.Format("FAC_SITE_IDEN_VAL IN ({0})", facIdQuery); selectClauses.Add("FACID_FAC", new DbAppendSelectWhereClause(whereQuery, null)); string affiliateTableClause = string.Format( "AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_FAC_FAC_AFFL WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0}) UNION " + "SELECT AFFL_IDEN FROM FACID_ENVR_INTR_FAC_AFFL WHERE ENVR_INTR_ID IN (SELECT ENVR_INTR_ID FROM FACID_ENVR_INTR WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0})))", whereQuery); //string affiliateTableClause = string.Format("(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_FAC_FAC_AFFL WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0}))) OR " + // "(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_ENVR_INTR_FAC_AFFL WHERE ENVR_INTR_ID IN (SELECT ENVR_INTR_ID FROM FACID_ENVR_INTR WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0}))))", // whereQuery); //string affiliateTableClause = string.Format("(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_FAC_FAC_AFFL WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0})))", // whereQuery); //string affiliateTableClause = string.Format("(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_ENVR_INTR_FAC_AFFL WHERE ENVR_INTR_ID IN (SELECT ENVR_INTR_ID FROM FACID_ENVR_INTR WHERE FAC_ID IN (SELECT FAC_ID FROM FACID_FAC WHERE {0}))))", // whereQuery); //string affiliateTableClause = string.Format("(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_FAC_FAC_AFFL WHERE FAC_ID IN ({0}))) OR " + // "(AFFL_IDEN IN (SELECT AFFL_IDEN FROM FACID_ENVR_INTR_FAC_AFFL WHERE ENVR_INTR_ID IN (SELECT ENVR_INTR_ID FROM FACID_ENVR_INTR WHERE FAC_ID IN ({0}))))", // facIdQuery); selectClauses.Add("FACID_AFFL", new DbAppendSelectWhereClause(affiliateTableClause, null)); List <FacilityDetailsDataType> dataList = objectsFromDatabase.LoadFromDatabase <FacilityDetailsDataType>(_baseDao, selectClauses); FacilityDetailsDataType data = FacIdHelper.CombineFacilityDetailsQueryResults(dataList); #if DEBUG { } #endif // DEBUG if (CollectionUtils.IsNullOrEmpty(data.FacilityList)) { appendAuditLogEvent.AppendAuditLogEvent("Did not find any FACID data in database."); return(null); } else { appendAuditLogEvent.AppendAuditLogEvent("Found {0} facilities and {1} affiliates.", data.FacilityList.Length, (data.AffiliateList != null) ? data.AffiliateList.Length : 0); } appendAuditLogEvent.AppendAuditLogEvent( "Serializing transformed results to file (File = {0}).", targetXmlPath); serializationHelper.Serialize(data, targetXmlPath); return(compressionHelper.CompressFile(targetXmlPath)); }