Beispiel #1
0
        public void Personnel_Returns_ValidViewModel()
        {
            var models = MongoPersonnel.Personnel;

            var viewModel = models.Select(Personnel.ToViewModel).First();

            var expectedViewModel = new PersonnelViewModel
            {
                Id       = "5a8417f68317338c8e080a62",
                Name     = "999 Call Handler",
                ImageUrl = "....",
                Context  = new List <ContentView>()
                {
                    new ContentView
                    {
                        Title   = "Title Text",
                        Content = new List <string> {
                            "Content Text"
                        },
                        CssClass = "CssClass Text",
                        Order    = 1
                    }
                },
                UsesNrls            = true,
                ActorOrganisationId = "5a82f9ffcb969daa58d33377",
                CModule             = "CModule-Type",
                SystemIds           = new List <string> {
                    "5a8417338317338c8e0809e5"
                },
                Benefits = new List <string> {
                    "benefitid"
                }
            };

            Assert.Equal(expectedViewModel, viewModel, Comparers.ModelComparer <PersonnelViewModel>());
        }
Beispiel #2
0
        public void TestRemove()
        {
            var pq = new PriorityQueue <int> {
                1, 2, 3, 4, 5, 6
            };

            pq.Remove(3).ShouldEqual(true);
            pq.Count.ShouldEqual(5);
            pq.Remove(3).ShouldEqual(false);
            pq.Count.ShouldEqual(5);
            pq.Remove(0).ShouldEqual(false);
            pq.Dequeue().ShouldEqual(1);
            pq.Remove(2).ShouldEqual(true);
            pq.Dequeue().ShouldEqual(4);
            pq.Remove(6).ShouldEqual(true);
            pq.Dequeue().ShouldEqual(5);
            pq.Count.ShouldEqual(0);

            var absoluteQueue = new PriorityQueue <int>(Comparers.Create <int, int>(Math.Abs));

            absoluteQueue.Remove(2).ShouldEqual(false);
            absoluteQueue.Enqueue(2);
            absoluteQueue.Remove(-2).ShouldEqual(true);
        }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class.
 /// </summary>
 /// <param name="comparers">The comparers.</param>
 private ImmutableDictionary(Comparers?comparers = null)
 {
     _comparers = comparers ?? Comparers.Get(EqualityComparer <TKey> .Default, EqualityComparer <TValue> .Default);
     _root      = SortedInt32KeyNode <HashBucket> .EmptyNode;
 }
Beispiel #4
0
            internal override NodeBase Update(object owner, int shift, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result)
            {
                if (comparers.KeyComparer.Equals(this.Key, key))
                {
                    switch (behavior)
                    {
                    case KeyCollisionBehavior.SetValue:
                        result = OperationResult.AppliedWithoutSizeChange;
                        return(SetValue(owner, key, value));

                    case KeyCollisionBehavior.SetIfValueDifferent:
                        if (comparers.ValueComparer.Equals(this.Value, value))
                        {
                            result = OperationResult.NoChangeRequired;
                            return(this);
                        }
                        else
                        {
                            result = OperationResult.AppliedWithoutSizeChange;
                            return(SetValue(owner, key, value));
                        }

                    case KeyCollisionBehavior.Skip:
                        result = OperationResult.NoChangeRequired;
                        return(this);

                    case KeyCollisionBehavior.ThrowIfValueDifferent:
                        if (!comparers.ValueComparer.Equals(this.Value, value))
                        {
                            throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key));
                        }

                        result = OperationResult.NoChangeRequired;
                        return(this);

                    case KeyCollisionBehavior.ThrowAlways:
                        throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key));

                    default:
                        throw new InvalidOperationException();     // unreachable
                    }
                }

                result = OperationResult.SizeChanged;
                return(MergeIntoNode(owner, shift, this, comparers.KeyComparer.GetHashCode(this.Key), hash, key, value));
            }
Beispiel #5
0
            internal override NodeBase Remove(object owner, int shift, int hash, TKey key, Comparers comparers, out OperationResult result)
            {
                int idx = IndexOf(key, comparers);

                if (idx == -1)
                {
                    // no found, no-op
                    result = OperationResult.NoChangeRequired;
                    return(this);
                }

                result = OperationResult.SizeChanged;
                if (_count == 1)
                {
                    return(null);
                }                                 // one count left, return null
                if (_count == 2)
                {
                    return(_values[0]);
                }                                       // return the value node.

                if (IsEditable(owner))
                {
                    _values[idx]        = _values[_count - 1];
                    _values[_count - 1] = null;
                    _count--;
                    return(this);
                }
                else
                {
                    ValueNode[] newValues = new ValueNode[_count - 1];
                    Array.Copy(_values, newValues, newValues.Length);
                    if (idx < newValues.Length)
                    {
                        newValues[idx] = _values[_count - 1];
                    }

                    return(SetNode(owner, _count - 1, newValues));
                }
            }
Beispiel #6
0
            private HashArrayMapNode ExpandToArrayMap(object owner, int shift, int count, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result)
            {
                NodeBase[] nodes = new NodeBase[WIDTH];
                int        index = Mask(hash, shift);

                nodes[index] = Empty.Update(owner, shift + BITS, hash, key, value, comparers, behavior, out result);

                int j = 0;

                for (int i = 0; i < nodes.Length; i++)
                {
                    if (((_bitmap >> i) & 1) != 0)
                    {
                        nodes[i] = _nodes[j++];
                    }
                }

                return(new HashArrayMapNode(owner, count + 1, nodes));
            }
Beispiel #7
0
 internal abstract NodeBase Remove(object owner, int shift, int hash, TKey key, Comparers comparers, out OperationResult result);
Beispiel #8
0
            internal override NodeBase Remove(object owner, int shift, int hash, TKey key, Comparers comparers, out OperationResult result)
            {
                int bit = 1 << Mask(hash, shift);

                if ((_bitmap & bit) == 0)
                {
                    // Not found noop
                    result = OperationResult.NoChangeRequired;
                    return(this);
                }

                int      idx = GetIndex(bit);
                NodeBase n   = _nodes[idx].Remove(owner, shift + BITS, hash, key, comparers, out result);

                if (n == _nodes[idx])
                {
                    return(this);
                }
                if (n != null)
                {
                    var newNode = EnsureEditable(owner);
                    newNode._nodes[idx] = n;
                    return(newNode);
                }

                if (_bitmap == bit)
                {
                    return(null);
                }

                // removed, so resize
                BitmapIndexedNode editable = EnsureEditable(owner);

                editable._bitmap ^= bit;
                Array.Copy(editable._nodes, idx + 1, editable._nodes, idx, editable._nodes.Length - (idx + 1));
                editable._nodes[editable._nodes.Length - 1] = null;
                return(editable);
            }
Beispiel #9
0
            internal override NodeBase Remove(object owner, int shift, int hash, TKey key, Comparers comparers, out OperationResult result)
            {
                int      idx  = Mask(hash, shift);
                NodeBase node = _array[idx];

                if (node == null)
                {
                    result = OperationResult.NoChangeRequired;
                    return(this);
                }

                NodeBase newSubNode = node.Remove(owner, shift + BITS, hash, key, comparers, out result);

                if (newSubNode == null) // the sub-node is removed.
                {
                    return((_count <= MIN_HASH_ARRAY_MAP_SIZE)
                           // Compress it to BitmapIndexedNode
                      ? PackNodes(owner, idx)
                           // just set null if the current count is not small enough to pack
                      : SetNode(owner, _count - 1, idx, null));
                }

                return(newSubNode == node ? this : SetNode(owner, _count, idx, newSubNode));
            }
 /// <summary>
 /// Initializes a new instance of the <see cref="ImmutableTrieDictionary{TKey, TValue}"/> class/
 /// </summary>
 /// <param name="count">The number of elements stored.</param>
 /// <param name="root">The root node.</param>
 /// <param name="compares">The comparers.</param>
 internal ImmutableTrieDictionary(int count, NodeBase root, Comparers compares = null)
 {
     _count     = count;
     _root      = root;
     _comparers = compares ?? Comparers.Default;
 }
Beispiel #11
0
        public void FhirResponse_ValidDocumentReferenceResources()
        {
            var documentReferenceModels = MongoDocumentReferences.DocumentReferences.ToList();
            var documentReferenceBundle = FhirBundle.GetBundle <DocumentReference>(documentReferenceModels);

            var actual = new FhirResponse();

            actual.Resource = documentReferenceBundle;

            Assert.Equal(documentReferenceModels, actual.GetResources <DocumentReference>(), Comparers.ModelComparer <DocumentReference>());
        }
        public async void PointerService_Returns_ValidPointerList()
        {
            var patientModels           = MongoPatients.Patients.ToList();
            var organizationModels      = MongoOrganizations.Organizations.ToList();
            var documentReferenceModels = MongoDocumentReferences.DocumentReferences_3656987882;

            var testNhsNumber = "3656987882";
            var testAsid      = "200000000116";
            var testOrgCode   = "AMS01";

            var _docRefService = new Mock <IDocumentReferenceServices>();

            _docRefService.Setup(m => m.GetPointersBundle(It.IsAny <NrlsPointerRequest>())).Returns(SystemTasks.Task.Run(() => FhirBundle.GetBundle <DocumentReference>(documentReferenceModels) as Resource)).Verifiable();

            var _patientService = new Mock <IPatientServices>();

            _patientService.Setup(m => m.GetPatients()).Returns(SystemTasks.Task.Run(() => patientModels)).Verifiable();

            var _organisationServices = new Mock <IOrganisationServices>();

            _organisationServices.Setup(m => m.GetOrganisations()).Returns(SystemTasks.Task.Run(() => organizationModels)).Verifiable();

            var pointerCache = new PatientPointers
            {
                Pointers = MongoPointerViewModels.PointerViewModels_3656987882
            };

            var cacheMock = MemoryCacheStub.MockMemoryCacheService.GetMemoryCache(pointerCache);

            var pdfBinaryId       = "TestBinaryPdf1";
            var _documentServices = new Mock <IDocumentsServices>();

            _documentServices.Setup(m => m.GetPointerDocument(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(SystemTasks.Task.Run(() => MongoBinaries.Binaries.FirstOrDefault(x => x.Id == pdfBinaryId) as Resource)).Verifiable();


            var opts = new ApiSetting
            {
                BaseUrl               = "://localhost",
                DefaultPort           = "55448",
                Secure                = false,
                SecureOnly            = false,
                SecurePort            = "55443",
                SupportedContentTypes = new List <string> {
                    "application/fhir+json"
                }
            };

            var _apiSettings = new Mock <IOptions <ApiSetting> >();

            _apiSettings.Setup(op => op.Value).Returns(opts);

            var pointerService = new PointerService(_apiSettings.Object, _docRefService.Object, _patientService.Object, _organisationServices.Object, cacheMock, _documentServices.Object);

            var request = RequestViewModel.Create(testNhsNumber);

            request.Asid    = testAsid;
            request.OrgCode = testOrgCode;

            var actual = await pointerService.GetPointers(request);

            var pointers = MongoPointerViewModels.PointerViewModels_3656987882;
            var patient  = MongoPatientViewModels.PatientViewModel_3656987882;
            var org      = MongoOrganizationViewModels.OrganizationViewModel_00003X;

            var expected = new List <PointerViewModel>();

            foreach (var exp in pointers)
            {
                exp.SubjectViewModel   = patient;
                exp.AuthorViewModel    = org;
                exp.CustodianViewModel = org;
                expected.Add(exp);
            }

            _docRefService.Verify();
            _patientService.Verify();
            _organisationServices.Verify();

            Assert.Equal(expected, actual, Comparers.ModelComparer <PointerViewModel>());
        }
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImmutableDictionary&lt;TKey, TValue&gt;.MutationInput"/> struct.
 /// </summary>
 /// <param name="map">The map.</param>
 internal MutationInput(ImmutableDictionary <TKey, TValue> map)
 {
     this.root      = map.root;
     this.comparers = map.comparers;
     this.count     = map.count;
 }
        public void NrlsConformance_Valid()
        {
            var expected = new CapabilityStatement
            {
                Url       = "https://fhir.nhs.uk/STU3/CapabilityStatement/NRL-CapabilityStatement-1",
                Version   = ModelInfo.Version,
                Name      = "NRL-CapabilityStatement-1",
                Status    = PublicationStatus.Draft,
                Date      = "2017-10-11T10:20:38+00:00",
                Publisher = "NHS Digital",
                Contact   = new List <ContactDetail>
                {
                    new ContactDetail
                    {
                        Name    = "Interoperability Team",
                        Telecom = new List <ContactPoint>
                        {
                            new ContactPoint
                            {
                                System = ContactPoint.ContactPointSystem.Email,
                                Use    = ContactPoint.ContactPointUse.Work,
                                Value  = "*****@*****.**"
                            }
                        }
                    }
                },
                Description   = new Markdown("This profile defines the expected capabilities of the NRL STU3 FHIR server when conforming to the NRL API IG. The Capability Statement resource includes a complete list of actual profiles, RESTful operations, and search parameters that are expected to be supported by NRL STU3 FHIR Server."),
                Copyright     = new Markdown("Copyright © 2017 NHS Digital"),
                Kind          = CapabilityStatement.CapabilityStatementKind.Requirements,
                FhirVersion   = "3.0.1",
                AcceptUnknown = CapabilityStatement.UnknownContentCode.No,
                Format        = new List <string>
                {
                    "application/fhir+xml",
                    "application/fhir+json"
                },
                Rest = new List <CapabilityStatement.RestComponent>
                {
                    new CapabilityStatement.RestComponent
                    {
                        Mode     = CapabilityStatement.RestfulCapabilityMode.Server,
                        Security = new CapabilityStatement.SecurityComponent
                        {
                            Cors = true
                        },
                        Resource = new List <CapabilityStatement.ResourceComponent>
                        {
                            new CapabilityStatement.ResourceComponent
                            {
                                Extension = new List <Extension>
                                {
                                    new Extension
                                    {
                                        Url       = "http://hl7.org/fhir/StructureDefinition/conformance-search-parameter-combination",
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("_id")
                                            }
                                        }
                                    },
                                    new Extension
                                    {
                                        Url       = "http://hl7.org/fhir/StructureDefinition/conformance-search-parameter-combination",
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("subject")
                                            },
                                            new Extension
                                            {
                                                Url   = "optional",
                                                Value = new FhirString("custodian")
                                            },
                                            new Extension
                                            {
                                                Url   = "optional",
                                                Value = new FhirString("type")
                                            }
                                        }
                                    },
                                    new Extension
                                    {
                                        Url       = "http://hl7.org/fhir/StructureDefinition/conformance-search-parameter-combination",
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("subject")
                                            },
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("_summary")
                                            }
                                        }
                                    },
                                    new Extension
                                    {
                                        Url       = "http://hl7.org/fhir/StructureDefinition/conformance-search-parameter-combination",
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("subject")
                                            },
                                            new Extension
                                            {
                                                Url   = "required",
                                                Value = new FhirString("identifier")
                                            }
                                        },
                                        FhirComments = new List <string>
                                        {
                                            "This combination can only be used for Supersede, Patch, and Delete interactions."
                                        }
                                    }
                                },
                                Type    = ResourceType.DocumentReference,
                                Profile = new ResourceReference
                                {
                                    Reference = "https://fhir.hl7.org.uk/StructureDefinition/NRL-DocumentReference-1"
                                },
                                Interaction = new List <CapabilityStatement.ResourceInteractionComponent>
                                {
                                    new CapabilityStatement.ResourceInteractionComponent
                                    {
                                        Code          = CapabilityStatement.TypeRestfulInteraction.SearchType,
                                        Documentation = "Allows discovery of existing NRL document reference resources using different search criteria"
                                    },
                                    new CapabilityStatement.ResourceInteractionComponent
                                    {
                                        Code          = CapabilityStatement.TypeRestfulInteraction.Read,
                                        Documentation = "Allows retrieval of specific NRL document references by id"
                                    },
                                    new CapabilityStatement.ResourceInteractionComponent
                                    {
                                        Code          = CapabilityStatement.TypeRestfulInteraction.Patch,
                                        Documentation = "Allows update of specific NRL document references by id"
                                    },
                                    new CapabilityStatement.ResourceInteractionComponent
                                    {
                                        Code          = CapabilityStatement.TypeRestfulInteraction.Delete,
                                        Documentation = "Allows deletion of specific NRL document references by id"
                                    },
                                    new CapabilityStatement.ResourceInteractionComponent
                                    {
                                        Code          = CapabilityStatement.TypeRestfulInteraction.Create,
                                        Documentation = "Allows creation of NRL document references"
                                    }
                                },
                                SearchParam = new List <CapabilityStatement.SearchParamComponent>
                                {
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("SHOULD")
                                            }
                                        },
                                        Name          = "subject",
                                        Definition    = "http://hl7.org/fhir/SearchParameter/DocumentReference.subject",
                                        Type          = SearchParamType.Reference,
                                        Documentation = "The Patient the DocumentReference relates to. This is MUST when searching by patient."
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("MAY")
                                            }
                                        },
                                        Name          = "custodian",
                                        Definition    = "http://hl7.org/fhir/SearchParameter/DocumentReference.custodian",
                                        Type          = SearchParamType.Reference,
                                        Documentation = "The owner of the DocumentReference"
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("SHOULD")
                                            }
                                        },
                                        Name          = "_id",
                                        Definition    = "http://hl7.org/fhir/search",
                                        Type          = SearchParamType.String,
                                        Documentation = "Logical id of the DocumentReference. This is MUST when searching by _id"
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("MAY")
                                            }
                                        },
                                        Name          = "type",
                                        Definition    = "http://hl7.org/fhir/search",
                                        Type          = SearchParamType.Token,
                                        Documentation = "Clinical type the DocumentReference refers too"
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("MAY")
                                            }
                                        },
                                        Name          = "_summary",
                                        Definition    = "http://hl7.org/fhir/search",
                                        Type          = SearchParamType.String,
                                        Documentation = "Type of summary to return"
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("MAY")
                                            }
                                        },
                                        Name          = "identifier",
                                        Definition    = "http://hl7.org/fhir/search",
                                        Type          = SearchParamType.Token,
                                        Documentation = "The MasterIdentifer associated to the DocumentReference. Used in Supersede, Patch, and Delete interactions."
                                    },
                                    new CapabilityStatement.SearchParamComponent
                                    {
                                        Extension = new List <Extension>
                                        {
                                            new Extension
                                            {
                                                Url   = "https://fhir.nhs.uk/STU3/StructureDefinition/Extension-CapabilityStatementExpectation-1",
                                                Value = new FhirString("MAY")
                                            }
                                        },
                                        Name          = "_format",
                                        Definition    = "http://hl7.org/fhir/search",
                                        Type          = SearchParamType.String,
                                        Documentation = "Content Type of returned result"
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var actual = new NrlsConformance().GetConformance();

            Assert.Equal(expected, actual, Comparers.ModelComparer <CapabilityStatement>());
        }
 public LabelCache(Comparers.Comparer<string> comparer)
 {
     _comparer = comparer;
 }
Beispiel #16
0
            internal override NodeBase Update(object owner, int shift, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result)
            {
                int      idx  = Mask(hash, shift);
                NodeBase node = _array[idx];

                if (node == null)
                {
                    NodeBase newSubNode = BitmapIndexedNode.Empty.Update(owner, shift + BITS, hash, key, value, comparers, behavior, out result);
                    return(SetNode(owner, _count + 1, idx, newSubNode));
                }
                else
                {
                    NodeBase newSubNode = node.Update(owner, shift + BITS, hash, key, value, comparers, behavior, out result);
                    if (newSubNode == node)
                    {
                        return(this);
                    }                                        // No Change
                    return(SetNode(owner, _count, idx, newSubNode));
                }
            }
Beispiel #17
0
        static void Main(string[] args)
        {
            Trace.Write("START");

            Debuggers.LogError("error occured");
            Debuggers.LogError(new Exception("ex occured"));

            Dictionary <string, int> dict = new Dictionary <string, int>()
            {
                { "Marketing", 1 }, { "Sales", 2 }, { "IT", 3 }
            };

            var dictExists = dict.Contains(new KeyValuePair <string, int>("IT", 2));



            Formaters.DateAndTime(DateTime.Now, 10.23456D);
            Debuggers.Start();
            var customers = Linqers.CustomersWithOrdersByYear(2017);

            Linqers.GetProductsLongestNameByCategory();

            string asyncResult;

            Task.Run(async() =>
            {
                asyncResult = await Threads.StartAsync();
            }).GetAwaiter().GetResult();


            Threads.RunTimer();
            var publicTypes       = new Reflections().GetPublicTypes();
            var assemblyName      = new Reflections().GetAssemblyName();
            var isPositiveDecimal = Regexes.PositiveWithTwoDecimalPlaces(5.666M);

            Console.WriteLine("Available memory: " + new PerformanceCounter("Memory", "Available MBytes").NextValue());

            var assemblies = new Reflections().GetTypesFromCurrentDomain();

            Product productForSerialization = new Product()
            {
                CategoryId = 1, Id = 2, IsValid = true
            };

            Serializators.SerializeWithBinaryFormatter(productForSerialization, "bin.dat");
            Serializators.SerializeWithDataContractToFile(productForSerialization, "datacontract.dat");


            string userSerialized = Serializators.SerializeWithBinaryWriter(new Product {
                Id = 10
            });
            DateTime?nullableDateTime = null;
            bool     isDateNotNull    = nullableDateTime.HasValue;

            RateCollection rateCollection = new RateCollection(new Rate[] { new Rate {
                                                                                Value = 1
                                                                            } });

            foreach (var item in rateCollection)
            {
                Console.WriteLine(item);
            }

            var currentAssembly = Assembly.GetExecutingAssembly();

            var sb = new StringBuilder();

            sb.Append("First");
            sb.AppendLine();
            sb.Append("Second");
            Console.WriteLine(sb);

            SortedList <string, string> sortedList = new SortedList <string, string>()
            {
                { "asd", "dsa" }
            };

            Debug.Assert(false, "stop");
            float  amount    = 1.6F;
            object amountObj = amount;
            int    amountInt = (int)(float)amountObj;

            new Product().Add("book1");

            User newUser = new User()
            {
                UserGroup = Group.Supervisors | Group.Users
            };
            bool isTrue    = newUser.UserGroup < Group.Administrator;
            var  userGroup = newUser.UserGroup;

            Console.WriteLine(userGroup);

            string stringNull    = null;
            string stringNotNull = "asd";

            Comparers.AreEqual(stringNull, stringNotNull);

            Rate rate1 = new Rate()
            {
                Value = 1, Category = "cat"
            };
            string xml  = Serializators.SerializeWithDataContract(rate1);
            string json = Serializators.SerializeWithDataContractJson(rate1);

            Console.WriteLine("xml:\r\n" + xml);
            Console.WriteLine("json:\r\n" + json);

            Subscriber sub = new Subscriber();

            sub.Subscribe();
            sub.Execute();


            Console.Read();
            return;


            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Rate));

            Console.WriteLine(string.Format("{0} asdasd {1:000#} asd", 4, 159));
            Console.WriteLine(123.ToString("000#"));

            Rate ratenull = null;
            int  wynik;

            int.TryParse(ratenull.Category, out wynik);

            Console.Read();

            BaseLogger logger = new Logger();

            logger.Log("Log started");
            logger.Log("Base: Log contiuniug");
            ((Logger)logger).LogCompleted();


            Console.Read();
            return;


            Reflections.SetPropertiesOnObject(new Rate()
            {
                MyInt = 10
            }, "MyInt", "MyIntSpecified");
            float  mojfloat = 1.6F;
            double dable    = (double)mojfloat;
            var    hashed   = Hashers.HashByAlgName(@"C:\windows-version.txt", "SHA");

            Threads.ConcurrentDict();
            var x = from i in new List <int> {
                1, 2
            }
            group i by i into grouped
            where grouped.Key > 1
            select grouped.Key;


            string xmlInput = "<xml><RateSheet><rate category=\"boutou\" date=\"2012-12-12\"><value>0.03</value></rate><rate category=\"druga\" date=\"2011-11-11\"><value>0.04</value></rate></RateSheet></xml>";

            var result = Serializators.ReadFromXml(xmlInput);

            SHA1Managed SHhash = new SHA1Managed();

            //new Class2().Method1();
            Class1        class1 = new Class1();
            INewInterface interf = class1;

            interf.Method1();

            IEnumerable <Person> people = new List <Person>()
            {
                new Person {
                    PhoneNumbers = new List <PhoneNumber> {
                        new PhoneNumber {
                            Number = "1"
                        }, new PhoneNumber {
                            Number = "2"
                        }
                    }
                },
                new Person {
                    PhoneNumbers = new List <PhoneNumber> {
                        new PhoneNumber {
                            Number = "2"
                        }, new PhoneNumber {
                            Number = "3"
                        }
                    }
                },
            };

            IEnumerable <IEnumerable <PhoneNumber> > phoneLists = people.Select(p => p.PhoneNumbers);
            IEnumerable <PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
        }
Beispiel #18
0
            internal override NodeBase Update(object owner, int shift, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result)
            {
                int bit = 1 << Mask(hash, shift);
                int idx = GetIndex(bit);

                if ((_bitmap & bit) != 0)
                { // exist
                    NodeBase node       = _nodes[idx];
                    var      newSubNode = node.Update(owner, shift + BITS, hash, key, value, comparers, behavior, out result);
                    if (newSubNode == node)
                    {
                        return(this);
                    }

                    var newNode = EnsureEditable(owner);
                    newNode._nodes[idx] = newSubNode;
                    return(newNode);
                }
                else
                { // not exist
                    int count = PopCount(_bitmap);
                    if (count == 0)
                    {
                        result = OperationResult.SizeChanged;
                        return(new ValueNode(owner, key, value));
                    }

                    if (count < _nodes.Length && IsEditable(owner))
                    {
                        // still has room in the array and editable
                        result = OperationResult.SizeChanged;
                        Array.Copy(_nodes, idx, _nodes, idx + 1, count - idx);
                        _nodes[idx] = new ValueNode(owner, key, value);
                        _bitmap    |= bit;
                        return(this);
                    }

                    return((count >= MAX_BITMAP_INDEXED_SIZE)
                      ? (NodeBase)ExpandToArrayMap(owner, shift, count, hash, key, value, comparers, behavior, out result)
                      : AddToNode(owner, idx, bit, count, key, value, out result));
                }
            }
Beispiel #19
0
 public MultiStepComparer(IComparer <T> primaryComparer, IEnumerable <IComparer <T> > secondaryComparers)
 {
     Comparers.Add(primaryComparer);
     Comparers.AddRange(secondaryComparers);
 }
Beispiel #20
0
 internal abstract NodeBase Update(object owner, int shift, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result);
Beispiel #21
0
 public MultiStepComparer(IComparer <T> primaryComparer, params IComparer <T>[] secondaryComparers)
 {
     Comparers.Add(primaryComparer);
     Comparers.AddRange(secondaryComparers);
 }
Beispiel #22
0
 internal abstract bool TryGet(int shift, int hash, Comparers comparers, TKey key, out TKey actualKey, out TValue value);
 /// <summary>
 /// Wraps the specified data structure with an immutable collection wrapper.
 /// </summary>
 /// <param name="root">The root of the data structure.</param>
 /// <param name="comparers">The comparers.</param>
 /// <param name="count">The number of elements in the data structure.</param>
 /// <returns>
 /// The immutable collection.
 /// </returns>
 private static ImmutableDictionary <TKey, TValue> Wrap(ImmutableSortedDictionary <int, HashBucket> .Node root, Comparers comparers, int count)
 {
     Requires.NotNull(root, "root");
     Requires.NotNull(comparers, "comparers");
     Requires.Range(count >= 0, "count");
     return(new ImmutableDictionary <TKey, TValue>(root, comparers, count));
 }
Beispiel #24
0
            internal override NodeBase Update(object owner, int shift, int hash, TKey key, TValue value, Comparers comparers, KeyCollisionBehavior behavior, out OperationResult result)
            {
                if (hash == _hash)
                {
                    int idx = IndexOf(key, comparers);
                    if (idx != -1)
                    {
                        // Found the same key, just update
                        var editable = EnsureEditable(owner);
                        editable._values[idx] = (ValueNode)editable._values[idx]
                                                .Update(owner, shift, hash, key, value, comparers, behavior, out result);
                        return(editable);
                    }

                    if (_count < _values.Length && IsEditable(owner)) // There are still some spots left
                    {
                        _values[_count] = new ValueNode(owner, key, value);
                        _count++;
                        result = OperationResult.SizeChanged;
                        return(this);
                    }

                    // Key cannot be found in the existing buckets, nor the list has extra room
                    // let's copy the array again
                    ValueNode[] newValues = new ValueNode[_count + 1];
                    Array.Copy(_values, newValues, _count);
                    newValues[_count] = new ValueNode(owner, key, value);

                    result = OperationResult.SizeChanged;
                    return(SetNode(owner, _count + 1, newValues));
                }
                else
                {
                    // different hash, nest in a bit mapnode
                    result = OperationResult.SizeChanged;
                    return(NestToBitmapNode(owner, shift, this, _hash, hash, key, value));
                }
            }
        /// <summary>
        /// Initializes a new instance of the <see cref="ImmutableDictionary&lt;TKey, TValue&gt;"/> class.
        /// </summary>
        /// <param name="root">The root.</param>
        /// <param name="comparers">The comparers.</param>
        /// <param name="count">The number of elements in the map.</param>
        private ImmutableDictionary(ImmutableSortedDictionary <int, HashBucket> .Node root, Comparers comparers, int count)
            : this(Requires.NotNull(comparers, "comparers"))
        {
            Requires.NotNull(root, "root");

            root.Freeze(FreezeBucketAction);
            this.root  = root;
            this.count = count;
        }
Beispiel #26
0
 internal override NodeBase Remove(object owner, int shift, int hash, TKey key, Comparers comparers, out OperationResult result)
 {
     if (!comparers.KeyComparer.Equals(this.Key, key))
     {
         result = OperationResult.NoChangeRequired;
         return(this);
     }
     else
     {
         result = OperationResult.SizeChanged;
         return(null);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ImmutableDictionary&lt;TKey, TValue&gt;"/> class.
 /// </summary>
 /// <param name="comparers">The comparers.</param>
 private ImmutableDictionary(Comparers comparers = null)
 {
     this.comparers = comparers ?? Comparers.Get(EqualityComparer <TKey> .Default, EqualityComparer <TValue> .Default);
     this.root      = ImmutableSortedDictionary <int, HashBucket> .Node.EmptyNode;
 }
Beispiel #28
0
 /// <summary>
 /// Wraps the specified data structure with an immutable collection wrapper.
 /// </summary>
 /// <param name="root">The root of the data structure.</param>
 /// <param name="comparers">The comparers.</param>
 /// <param name="count">The number of elements in the data structure.</param>
 /// <returns>
 /// The immutable collection.
 /// </returns>
 private static ImmutableDictionary <TKey, TValue> Wrap(SortedInt32KeyNode <HashBucket> root, Comparers comparers, int count)
 {
     Requires.NotNull(root, nameof(root));
     Requires.NotNull(comparers, nameof(comparers));
     Requires.Range(count >= 0, nameof(count));
     return(new ImmutableDictionary <TKey, TValue>(root, comparers, count));
 }
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.MutationInput"/> struct.
 /// </summary>
 /// <param name="map">The map.</param>
 internal MutationInput(ImmutableDictionary <TKey, TValue> map)
 {
     _root      = map._root;
     _comparers = map._comparers;
     _count     = map._count;
 }
 public void UnorderableType2()
 {
     IComparer <Unorderable> ordering = Comparers.DefaultComparer <Unorderable>();
 }
Beispiel #31
0
        private static void ProcessSubFolders(this Vault vault, SyncDownResponse rs)
        {
            var comparers  = new Comparers();
            var folderList = new SortedSet <IFolderNode>(vault.userFolders.Values, comparers);
            var recordList = new SortedSet <IRecordNode>(vault.userFolderRecords ?? Enumerable.Empty <IRecordNode>(), comparers);

            if (rs.userFoldersRemoved != null)
            {
                foreach (var ufr in rs.userFoldersRemoved)
                {
                    folderList.RemoveWhere(x => x.FolderUid == ufr.folderUid);
                    recordList.RemoveWhere(x => x.FolderUid == ufr.folderUid);
                }
            }

            if (rs.sharedFolderFolderRemoved != null)
            {
                foreach (var sffr in rs.sharedFolderFolderRemoved)
                {
                    folderList.RemoveWhere(x => x.FolderUid == sffr.folderUid);
                    recordList.RemoveWhere(x => x.FolderUid == sffr.folderUid);
                }
            }

            if (rs.userFolderSharedFoldersRemoved != null)
            {
                foreach (var ufsfr in rs.userFolderSharedFoldersRemoved)
                {
                    folderList.RemoveWhere(x => x.FolderUid == ufsfr.folderUid);
                    recordList.RemoveWhere(x => x.FolderUid == ufsfr.folderUid);
                }
            }

            if (rs.userFoldersRemovedRecords != null)
            {
                foreach (var uffr in rs.userFoldersRemovedRecords)
                {
                    recordList.Remove(uffr);
                }
            }

            if (rs.sharedFolderFolderRecordsRemoved != null)
            {
                foreach (var sffrr in rs.sharedFolderFolderRecordsRemoved)
                {
                    recordList.Remove(sffrr);
                }
            }

            if (rs.userFolders != null)
            {
                foreach (var uf in rs.userFolders)
                {
                    var encryptedKey = uf.userFolderKey.Base64UrlDecode();
                    uf.unencryptedFolderKey = uf.keyType == 2
                        ? CryptoUtils.DecryptRsa(encryptedKey, vault.Auth.PrivateKey)
                        : CryptoUtils.DecryptAesV1(encryptedKey, vault.Auth.DataKey);
                    folderList.Remove(uf);
                    folderList.Add(uf);
                }
            }

            if (rs.sharedFolderFolders != null)
            {
                foreach (var sff in rs.sharedFolderFolders)
                {
                    if (vault.sharedFolders.TryGetValue(sff.sharedFolderUid, out SyncDownSharedFolder sf))
                    {
                        var encryptedKey = sff.sharedFolderFolderKey.Base64UrlDecode();
                        sff.unencryptedFolderKey = CryptoUtils.DecryptAesV1(encryptedKey, sf.unencryptedSharedFolderKey);
                        folderList.Remove(sff);
                        folderList.Add(sff);
                    }
                    else
                    {
                        Trace.TraceError("Sync_Down: shared_folder_folders: Shared Folder UID {0} not found", sff.sharedFolderUid);
                    }
                }
            }

            if (rs.userFolderSharedFolders != null)
            {
                foreach (var ufsf in rs.userFolderSharedFolders)
                {
                    folderList.Remove(ufsf);
                    folderList.Add(ufsf);
                }
            }

            if (rs.userFolderRecords != null)
            {
                foreach (var ufr in rs.userFolderRecords)
                {
                    recordList.Add(ufr);
                }
            }

            if (rs.sharedFolderFolderRecords != null)
            {
                foreach (var sffr in rs.sharedFolderFolderRecords)
                {
                    recordList.Add(sffr);
                }
            }

            var toDelete = new HashSet <string>();

            foreach (var folder in vault.keeperFolders.Values)
            {
                toDelete.Add(folder.FolderUid);
                folder.Children.Clear();
                folder.Records.Clear();
            }
            foreach (var folder in folderList)
            {
                if (vault.keeperFolders.TryGetValue(folder.FolderUid, out FolderNode node))
                {
                    toDelete.Remove(folder.FolderUid);
                    node.Children.Clear();
                    node.Records.Clear();
                    node.Name = null;
                }
                else
                {
                    node = new FolderNode
                    {
                        FolderType = folder.Type,
                        FolderUid  = folder.FolderUid
                    };
                    vault.keeperFolders.Add(folder.FolderUid, node);
                }
                node.ParentUid = folder.ParentUid;

                byte[] unencrypted_data = null;
                switch (folder.Type)
                {
                case FolderType.UserFolder:
                    if (folder is SyncDownUserFolder uf)
                    {
                        unencrypted_data = CryptoUtils.DecryptAesV1(uf.data.Base64UrlDecode(), uf.unencryptedFolderKey);
                    }
                    else
                    {
                        Trace.TraceError("Folder UID {0} expected to be User-Folder", folder.FolderUid);
                    }
                    break;

                case FolderType.SharedFolderForder:
                    if (folder is SyncDownSharedFolderFolder sff)
                    {
                        unencrypted_data = CryptoUtils.DecryptAesV1(sff.data.Base64UrlDecode(), sff.unencryptedFolderKey);
                    }
                    else
                    {
                        Trace.TraceError("Folder UID {0} expected to be Shared-Folder-Folder", folder.FolderUid);
                    }
                    break;

                case FolderType.SharedFolder:
                    if (vault.sharedFolders.TryGetValue(folder.FolderUid, out SyncDownSharedFolder sf))
                    {
                        node.Name = Encoding.UTF8.GetString(CryptoUtils.DecryptAesV1(sf.name.Base64UrlDecode(), sf.unencryptedSharedFolderKey));
                    }
                    else
                    {
                        Trace.TraceError("Folder UID {0} expected to be Shared-Folder", folder.FolderUid);
                    }
                    break;
                }
                if (unencrypted_data != null)
                {
                    var serializer = new DataContractJsonSerializer(typeof(FolderData));
                    using (var stream = new MemoryStream(unencrypted_data))
                    {
                        var folderData = serializer.ReadObject(stream) as FolderData;
                        node.Name = folderData.name;
                    }
                }
                if (string.IsNullOrEmpty(node.Name))
                {
                    node.Name = node.FolderUid;
                }
            }
            foreach (var uid in toDelete)
            {
                vault.keeperFolders.Remove(uid);
            }
            vault.Root.Children.Clear();
            vault.Root.Records.Clear();

            foreach (var node in vault.keeperFolders.Values)
            {
                if (string.IsNullOrEmpty(node.ParentUid))
                {
                    vault.Root.Children.Add(node.FolderUid);
                }
                else
                {
                    if (vault.keeperFolders.TryGetValue(node.ParentUid, out FolderNode parent))
                    {
                        parent.Children.Add(node.FolderUid);
                    }
                    else
                    {
                        Trace.TraceError("Folder UID {0} was lost", node.FolderUid);
                    }
                }
            }

            foreach (var record in recordList)
            {
                if (string.IsNullOrEmpty(record.FolderUid))
                {
                    vault.Root.Records.Add(record.RecordUid);
                }
                else
                {
                    if (vault.keeperFolders.TryGetValue(record.FolderUid, out FolderNode node))
                    {
                        node.Records.Add(record.RecordUid);
                    }
                    else
                    {
                        Trace.TraceError("Folder UID {0} was lost", node.FolderUid);
                        vault.Root.Records.Add(record.RecordUid);
                    }
                }
            }

            vault.userFolders.Clear();
            foreach (var folder in folderList)
            {
                vault.userFolders.Add(folder.FolderUid, folder);
            }
            vault.userFolderRecords = recordList.ToList();
        }