public void IsResource() { var resources = CreateResources(); var testee = new ResourceCollection<MyResource>(resources.Length, 1, 0, resources, new Link[0]); testee.Should().BeAssignableTo<Resource>(); }
internal ConsolidatedResource(IResourceGroup group, ResourceCollection resources, MemoryStream consolidatedContent) { _group = group; _resources = resources; _lastModified = resources.LastModified(); _contentStream = consolidatedContent; }
public ResourceCapture(WebPageBase page, Action<ResourceCollection, string> callBack, ResourceCollection source, string key) { _page = page; _callBack = callBack; _resource = source; _key = key; }
/// <summary> /// 初始化引用资源的信息 /// <para>将公有资源赋值到引用上</para> /// </summary> /// <param name="resources"></param> public void InitRefResource(ResourceCollection resources) { foreach (var reference in Refs) { reference.Resource = resources[reference.ResName]; } }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetDeployment)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a project var projectResource = new ProjectResource {Name = "Octopus"}; octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(projectResource); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource) null); // Create a Release var release = new ReleaseResource { Id = "Releases-1", Links = new LinkCollection()}; release.Links.Add("Deployments", "/api/releases/releases-1/deployments"); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(projectResource, "1.0.0")).Returns(release); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(projectResource, "Gibberish")).Returns((ReleaseResource) null); // Create Deployments var deployments = new ResourceCollection<DeploymentResource>(new List<DeploymentResource> { new DeploymentResource {Id = "deployments-1"} }, new LinkCollection()); octoRepo.Setup(o => o.Releases.GetDeployments(release, 0)).Returns(deployments); octoRepo.Setup(o => o.Releases.Get("Releases-1")).Returns(release); }
public void OrderedResourceDictionary() { var random = new Random(); var input = Enumerable.Repeat<object>(null, 1000).Select( x => random.Next()).ToList(); var resources = new ResourceCollection<Entity>.OrderedResourceDictionary(); foreach (var i in input) { var entity = new Entity( new Service("dummy", 0, HttpService.SchemeHttp), // Encode i in EntityPath i.ToString()); var list = new List<Entity> { entity }; resources.Add(i.ToString(), list); } // Get back what's encoded in Key string. CollectionAssert.AreEqual( input, resources.Keys.Select(x => Convert.ToInt32(x)).ToList()); var output = resources.Values.Select(x => Convert.ToInt32( // Get back what's encoded in Entity.Path. x[0].Path.Substring(10))).ToList(); CollectionAssert.AreEqual(input, output); }
public void CloneFrom(ResourceCollection other) { int e = 0, o = 0; while (e < Resources.Count || o < other.Resources.Count) { int oid = o; if (e < Resources.Count) { for (; oid < other.Resources.Count; ++oid) if (other.Resources[oid].Name == Resources[e].Name) break; } else oid = other.Resources.Count; if (e == Resources.Count || oid < other.Resources.Count) { for (; o < oid; ++o) { var otherEntity = other.Resources[o]; var myEntity = new Resource() { Name = otherEntity.Name }; myEntity.Amount = otherEntity.Amount; Resources.Insert(e++, myEntity); } } if (e < Resources.Count) { if (oid < other.Resources.Count) { if (oid != o) Debug.LogError("Id missmatch"); Resources[e++].Amount = other.Resources[o++].Amount; } else { Resources.RemoveAt(e); } } } }
public static void Initialize(ContentManager content) { ResourceManager.content = content; TileTextureBank = new ResourceCollection<Texture2D>(); TileTextureBank.Add("Square", content.Load<Texture2D>("Art\\square")); TileTextureBank.Add("Grass", content.Load<Texture2D>("Art\\grass32x32")); }
public ClosedSlot(ResourceCollection resourceCalendars) { foreach (var resource in resourceCalendars) { this.Resources.Add(new Resource(resource.ResourceName, resource.ResourceType)); } this.ImageSource = "../../Resources/Images/CompanyClosed.png"; }
public override void CloneFrom(SimComponent component) { var other = (SCResourceSite)component; if (Resources == null) Resources = new ResourceCollection(); Resources.CloneFrom(other.Resources); DieOnDeplete = other.DieOnDeplete; base.CloneFrom(component); }
public async Task CanConstructResource() { var feed = await TestAtomFeed.ReadFeed(Path.Combine(TestAtomFeed.Directory, "JobCollection.GetAsync.xml")); using (var context = new Context(Scheme.Https, "localhost", 8089)) { dynamic collection = new ResourceCollection(feed); CheckCommonStaticPropertiesOfResource(collection); //// Static property checks Assert.Equal("jobs", collection.Title); Assert.Throws<RuntimeBinderException>(() => { var p = collection.Links; }); Assert.Throws<RuntimeBinderException>(() => { var p = collection.Messages; }); Assert.DoesNotThrow(() => { Pagination p = collection.Pagination; Assert.Equal(14, p.TotalResults); Assert.Equal(0, p.StartIndex); Assert.Equal(0, p.ItemsPerPage); }); Assert.DoesNotThrow(() => { ReadOnlyCollection<Resource> p = collection.Resources; Assert.Equal(14, p.Count); }); foreach (var resource in collection.Resources) { CheckCommonStaticPropertiesOfResource(resource); CheckExistenceOfJobProperties(resource); Assert.IsType(typeof(Resource), resource); } { dynamic resource = collection.Resources[0]; CheckCommonStaticPropertiesOfResource(resource); Assert.IsType(typeof(Uri), resource.Id); Assert.Equal("https://localhost:8089/services/search/jobs/scheduler__admin__search__RMD50aa4c13eb03d1730_at_1401390000_866", resource.Id.ToString()); Assert.IsType(typeof(string), resource.Content.Sid); Assert.Equal("scheduler__admin__search__RMD50aa4c13eb03d1730_at_1401390000_866", resource.Content.Sid); Assert.IsType(typeof(string), resource.Title); Assert.Equal("search search index=_internal | head 1000", resource.Title); Assert.NotNull(resource.Links); Assert.IsType(typeof(ReadOnlyDictionary<string, Uri>), resource.Links); Assert.Equal(new string[] { "alternate", "search.log", "events", "results", "results_preview", "timeline", "summary", "control" }, resource.Links.Keys); CheckExistenceOfJobProperties(resource); } } }
public void LastModifiedEqualsLastModifiedOfCollection() { ResourceCollection resources = new ResourceCollection(); resources.Add(CreateResource(DateTime.Now)); resources.Add(CreateResource(DateTime.Now.AddDays(-1))); ConsolidatedResource consolidated = new ConsolidatedResource(null, resources, new MemoryStream()); Assert.That(consolidated.LastModified, Is.EqualTo(resources.LastModified())); }
public static Boolean IncludesSubscription(ResourceCollection<Subscription> collection, Subscription subscription) { foreach (Subscription item in collection) { if (item.Id.Equals(subscription.Id)) { return true; } } return false; }
public void Dispose() { ResourceEntity resource = new ResourceEntity(); resource.Position = _position; resource.Source = _page.OutputStack.Pop(); var resources=new ResourceCollection(); resources.Name = Guid.NewGuid().ToString("N"); resources.Add(resource); _callBack(resources, _key); }
public void LastModifiedReturnsGreatestValueFromItems() { DateTime mostRecent = DateTime.Now; ResourceCollection resources = new ResourceCollection(); resources.Add(CreateResource(mostRecent.AddDays(-1))); resources.Add(CreateResource(mostRecent)); resources.Add(CreateResource(mostRecent.AddDays(-30))); Assert.That(resources.LastModified(), Is.EqualTo(mostRecent)); }
public void ConsolidateEqualToSumOfParts() { ResourceCollection resources = new ResourceCollection(); StringWriter expectedWriter = new StringWriter(); AddResourceContent(resources, "my content", expectedWriter); AddResourceContent(resources, "my other content", expectedWriter); StringWriter actualWriter = new StringWriter(); resources.ConsolidateContentTo(actualWriter); Assert.That(actualWriter.ToString(), Is.EqualTo(expectedWriter.ToString())); }
public void AtFoot() { var resources = new ResourceCollection(); resources.Name = _resource.Name; _resource.Each(m => { ResourceEntity entity = m.ToNew(); entity.Position = ResourcePosition.Foot; resources.Add(entity); }); _callBack(resources, _key); }
public void ConsolidatePlacesSeparatorStringBetweenParts() { string separator = Environment.NewLine; ResourceCollection resources = new ResourceCollection(); StringWriter expectedWriter = new StringWriter(); AddResourceContent(resources, "my content", expectedWriter); expectedWriter.Write(separator); AddResourceContent(resources, "my other content", expectedWriter); StringWriter actualWriter = new StringWriter(); resources.ConsolidateContentTo(actualWriter, separator); Assert.That(actualWriter.ToString(), Is.EqualTo(expectedWriter.ToString())); }
public void ConsolidateFiltersContent() { string contentA = "a a a"; string contentB = "b b b"; string separator = Environment.NewLine; ResourceCollection resources = new ResourceCollection(); resources.Add(new StubResource(contentA)); resources.Add(new StubResource(contentB)); StringWriter actualWriter = new StringWriter(); resources.ConsolidateContentTo(actualWriter, r => r.GetContent().Replace(" ", ""), separator); Assert.That(actualWriter.ToString(), Is.EqualTo(String.Format("aaa{0}bbb", Environment.NewLine))); }
public void SetUp() { clientFactory = Substitute.For<IOctopusClientFactory>(); client = Substitute.For<IOctopusAsyncClient>(); clientFactory.CreateAsyncClient(Arg.Any<OctopusServerEndpoint>()).Returns(client); operation = new RegisterMachineOperation(clientFactory); serverEndpoint = new OctopusServerEndpoint("http://octopus", "ABC123"); environments = new ResourceCollection<EnvironmentResource>(new EnvironmentResource[0], LinkCollection.Self("/foo")); machines = new ResourceCollection<MachineResource>(new MachineResource[0], LinkCollection.Self("/foo")); client.RootDocument.Returns(new RootResource {Links = LinkCollection.Self("/api").Add("Environments", "/api/environments").Add("Machines", "/api/machines")}); client.When(x => x.Paginate(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<Func<ResourceCollection<EnvironmentResource>, bool>>())) .Do(ci => ci.Arg<Func<ResourceCollection<EnvironmentResource>, bool>>()(environments)); client.When(x => x.Paginate(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<Func<ResourceCollection<MachineResource>, bool>>())) .Do(ci => ci.Arg<Func<ResourceCollection<MachineResource>, bool>>()(machines)); client.List<MachineResource>(Arg.Any<string>(), Arg.Any<object>()).Returns(machines); }
public void SetUp() { deployReleaseCommand = new DeployReleaseCommand(RepositoryFactory, Log, FileSystem); var project = new ProjectResource(); var release = new ReleaseResource { Version = "1.0.0" }; var releases = new ResourceCollection<ReleaseResource>(new[] { release }, new LinkCollection()); var deploymentPromotionTarget = new DeploymentPromotionTarget { Name = "TestEnvironment" }; var promotionTargets = new List<DeploymentPromotionTarget> { deploymentPromotionTarget }; var deploymentTemplate = new DeploymentTemplateResource { PromoteTo = promotionTargets }; var deploymentPreviewResource = new DeploymentPreviewResource { StepsToExecute = new List<DeploymentTemplateStep>() }; var deployment = new DeploymentResource { TaskId = "1" }; taskResource = new TaskResource(); Repository.Projects.FindByName(ProjectName).Returns(project); Repository.Projects.GetReleases(project).Returns(releases); Repository.Releases.GetPreview(deploymentPromotionTarget).Returns(deploymentPreviewResource); Repository.Releases.GetTemplate(release).Returns(deploymentTemplate); Repository.Deployments.Create(Arg.Any<DeploymentResource>()).Returns(deployment); Repository.Tasks.Get(deployment.TaskId).Returns(taskResource); }
public async Task <ActionResult <ResourceCollection <BookDto> > > GetBooksAsync(Guid authorId) { List <BookDto> bookDtoList = new List <BookDto>(); string key = $"{authorId}_books"; if (!MemoryCache.TryGetValue(key, out bookDtoList)) { var books = await RepositoryWrapper.Book.GetBooksAsync(authorId); bookDtoList = Mapper.Map <IEnumerable <BookDto> >(books).ToList(); MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddMinutes(30); options.Priority = CacheItemPriority.Normal; MemoryCache.Set(key, bookDtoList, options); } bookDtoList = bookDtoList.Select(CreateLinksForBook).ToList(); var bookList = new ResourceCollection <BookDto>(bookDtoList); return(CreateLinksForBooks(bookList)); }
public void SetUp() { clientFactory = Substitute.For <IOctopusClientFactory>(); client = Substitute.For <IOctopusClient>(); clientFactory.CreateClient(Arg.Any <OctopusServerEndpoint>()).Returns(client); operation = new RegisterMachineOperation(clientFactory); serverEndpoint = new OctopusServerEndpoint("http://octopus", "ABC123"); environments = new ResourceCollection <EnvironmentResource>(new EnvironmentResource[0], LinkCollection.Self("/foo")); machines = new ResourceCollection <MachineResource>(new MachineResource[0], LinkCollection.Self("/foo")); client.RootDocument.Returns(new RootResource { Links = LinkCollection.Self("/api").Add("Environments", "/api/environments").Add("Machines", "/api/machines") }); client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <EnvironmentResource>, bool> >())) .Do(ci => ci.Arg <Func <ResourceCollection <EnvironmentResource>, bool> >()(environments)); client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <MachineResource>, bool> >())) .Do(ci => ci.Arg <Func <ResourceCollection <MachineResource>, bool> >()(machines)); client.List <MachineResource>(Arg.Any <string>(), Arg.Any <object>()).Returns(machines); }
public FormMultiPlayerMenu(FormMainMenu _parent) { InitializeComponent(); BackgroundImage = ResourceCollection.GetResourceByName("main_menu.png"); btnHotseat.BackgroundImage = ResourceCollection.GetResourceByName("menu_button_hot_seat.png"); btnLan.BackgroundImage = ResourceCollection.GetResourceByName("menu_button_lan.png"); btnInternet.BackgroundImage = ResourceCollection.GetResourceByName("menu_button_internet.png"); button1.BackgroundImage = ResourceCollection.GetResourceByName("menu_button_back.png"); this.TransparencyKey = Color.FromArgb(31, 32, 33); this.BackColor = Color.FromArgb(31, 32, 33); this.Icon = Properties.Resources.logo1; this._parent = _parent; _movable = false; _tHotseat = new Timer() { Interval = 5, Enabled = false }; _tLan = new Timer() { Interval = 5, Enabled = false }; _tInternet = new Timer() { Interval = 5, Enabled = false }; _tHotseat.Tick += _tHotseat_Tick; _tLan.Tick += _tLan_Tick; _tInternet.Tick += _tInternet_Tick; }
private static void ProcessUtilizations(ResourceCollection <AzureUtilizationRecord> utilizations, string CustomerId, string SubscriptionId, TraceWriter log) { log.Info($"{utilizations.TotalCount } utilizations found"); log.Info($"Inserting Utilizaton data into database"); DumpUtility blkOperation = new DumpUtility(ConfigurationHelper.GetConnectionString(ConfigurationKeys.DbConnectoinString)); blkOperation.Insert <CspUtilization>(utilizations.Items .Select(s => new CspUtilization() { CustomerId = CustomerId, SubscriptionId = SubscriptionId, ResourceGuid = s.Resource?.Id, ResourceName = s.Resource?.Name, Category = s.Resource?.Category, SubCategory = s.Resource?.Subcategory, Region = s.Resource?.Region, UsageDateUtc = s.UsageStartTime.UtcDateTime, Quantity = s.Quantity, Unit = s.Unit }).ToList()); log.Info($"Database operation completed."); }
public ResourceFactory ( IEnumerable <IEntityResourceProvider> resourceProviders, TerminalResourceProvider terminalResourceProvider, BinaryResourceProvider binaryResourceProvider, VirtualResourceProvider virtualResourceProvider, TypeCache typeCache, ResourceValidator resourceValidator, ResourceCollection resourceCollection, RootAccess rootAccess ) { TerminalProvider = terminalResourceProvider; BinaryProvider = binaryResourceProvider; VrProvider = virtualResourceProvider; ExternalResourceProviders = resourceProviders.ToList(); TypeCache = typeCache; ResourceValidator = resourceValidator; ResourceCollection = resourceCollection; RootAccess = rootAccess; EntityResourceProviders = new Dictionary <string, IEntityResourceProviderInternal>(); }
public void ResourceCollection_IteratesOverCollectionsProperly() { string body = @"<search-results> <page-size>2</page-size> <ids type='array'> <items>0</items> <items>1</items> <items>2</items> <items>3</items> <items>4</items> </ids> </search-results>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(body); NodeWrapper xml = new NodeWrapper(doc.ChildNodes[0]); ResourceCollection<string> resourceCollection = new ResourceCollection<string>(xml, delegate(string[] ids) { List<string> results = new List<string>(); foreach (string id in ids) { results.Add(values[int.Parse(id)]); } return results; }); int index = 0; int count = 0; foreach (string item in resourceCollection) { Assert.AreEqual(values[index], item); index++; count++; } Assert.AreEqual(values.Length, count); }
public void Search_OnTextFields() { var createRequest = new CustomerRequest { Email = "*****@*****.**", CreditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { PostalCode = "44444" }, Options = new CreditCardOptionsRequest { VerifyCard = true } } }; Result <Customer> result = gateway.Customer.Create(createRequest); string token = result.Target.CreditCards[0].Token; string postalCode = result.Target.CreditCards[0].BillingAddress.PostalCode; string customerId = result.Target.Id; string customerEmail = result.Target.Email; CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest(). PaymentMethodToken.Is(token). BillingAddressDetailsPostalCode.Is(postalCode). CustomerId.Is(customerId). CustomerEmail.Is(customerEmail); ResourceCollection <CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest); CreditCardVerification verification = collection.FirstItem; Assert.AreEqual(1, collection.MaximumCount); Assert.AreEqual(token, verification.CreditCard.Token); Assert.AreEqual(postalCode, verification.BillingAddress.PostalCode); }
/// <summary> /// executes the create partner service request scenario. /// </summary> protected override void RunScenario() { string supportTopicId = this.Context.Configuration.Scenario.DefaultSupportTopicId; var partnerOperations = this.Context.UserPartnerOperations; if (string.IsNullOrEmpty(supportTopicId.ToString())) { this.Context.ConsoleHelper.StartProgress("Fetching support topics"); // Get the list of support topics ResourceCollection <SupportTopic> supportTopicsCollection = partnerOperations.ServiceRequests.SupportTopics.Get(); this.Context.ConsoleHelper.StopProgress(); this.Context.ConsoleHelper.WriteObject(supportTopicsCollection, "Support topics"); // prompt the user the enter the support topic ID supportTopicId = this.Context.ConsoleHelper.ReadNonEmptyString("Please enter the support topic ID ", "The support topic ID can't be empty"); } else { Console.WriteLine("Found support topic ID: {0} in configuration.", supportTopicId); } ServiceRequest serviceRequestToCreate = new ServiceRequest() { Title = "TrialSR", Description = "Ignore this SR", Severity = ServiceRequestSeverity.Critical, SupportTopicId = supportTopicId }; this.Context.ConsoleHelper.StartProgress("Creating Service Request"); ServiceRequest serviceRequest = partnerOperations.ServiceRequests.Create(serviceRequestToCreate, "en-US"); this.Context.ConsoleHelper.StopProgress(); this.Context.ConsoleHelper.WriteObject(serviceRequest, "Created Service Request"); }
public void Search_FindDuplicateCardsGivenPaymentMethodToken() { CreditCardRequest creditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/2012" }; CustomerRequest jimRequest = new CustomerRequest { FirstName = "Jim", CreditCard = creditCard }; CustomerRequest joeRequest = new CustomerRequest { FirstName = "Jim", CreditCard = creditCard }; Customer jim = gateway.Customer.Create(jimRequest).Target; Customer joe = gateway.Customer.Create(joeRequest).Target; CustomerSearchRequest searchRequest = new CustomerSearchRequest(). PaymentMethodTokenWithDuplicates.Is(jim.CreditCards[0].Token); ResourceCollection <Customer> collection = gateway.Customer.Search(searchRequest); List <string> customerIds = new List <string>(); foreach (Customer customer in collection) { customerIds.Add(customer.Id); } Assert.IsTrue(customerIds.Contains(jim.Id)); Assert.IsTrue(customerIds.Contains(joe.Id)); }
async Task <ResourceCollection <Transaction> > ITransactionReader.GetAll( Guid userId, DateTimeOffset from, DateTimeOffset to) { var transactionCollections = new List <ResourceCollection <Transaction> >(); var accounts = await((IAccountReader)this).GetAll(userId); foreach (var account in accounts.Items) { var accountTransactions = await GetAll(userId, account.Id, from, to); transactionCollections.Add(accountTransactions); } return(transactionCollections.Aggregate(ResourceCollection <Transaction> .Empty(), (acc, curr) => { var items = new List <Transaction>(); items.AddRange(acc.Items); items.AddRange(curr.Items); return new ResourceCollection <Transaction>(items, acc.Count + curr.Count); })); }
public string GetServiceName(string org, string app) { string defaultLang = "nb"; string filename = $"resource.{defaultLang}.json"; string serviceResourceDirectoryPath = _settings.GetLanguageResourcePath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + filename; string serviceName = string.Empty; var watch = System.Diagnostics.Stopwatch.StartNew(); if (System.IO.File.Exists(serviceResourceDirectoryPath)) { string textResource = System.IO.File.ReadAllText(serviceResourceDirectoryPath, Encoding.UTF8); ResourceCollection textResourceObject = JsonConvert.DeserializeObject <ResourceCollection>(textResource); if (textResourceObject != null) { serviceName = textResourceObject.Resources.FirstOrDefault(r => r.Id == "ServiceName") != null?textResourceObject.Resources.FirstOrDefault(r => r.Id == "ServiceName").Value : string.Empty; } } watch.Stop(); _logger.Log(LogLevel.Information, "Getservicename - {0} ", watch.ElapsedMilliseconds); return(serviceName); }
public void GetAllCustomers( OwinApplication webService, HttpResponseMessage message, ResourceCollection<CustomerListModel> result) { "Given a web service" .f(() => webService = new OwinApplication(6161)); "When requesting all customers" .f(async () => message = await webService.Client.GetAsync("api/customers")); "Then the status code of the HTTP message equals OK" .f(() => message.StatusCode.Should().Be(HttpStatusCode.OK)); "Then the inner result can be parsed" .f(async () => result = await message.Content.ReadAsAsync<ResourceCollection<CustomerListModel>>()); "Then there are some customers in the result" .f(() => result.Results.Count().Should().BeGreaterOrEqualTo(91)); "Then there is a self link in the result" .f(() => result.Links.Should().Contain(l => l.Rel == "self")); }
public void GetAllCustomers( OwinApplication webService, HttpResponseMessage message, ResourceCollection <CustomerListModel> result) { "Given a web service" .f(() => webService = new OwinApplication(6161)); "When requesting all customers" .f(async() => message = await webService.Client.GetAsync("api/customers")); "Then the status code of the HTTP message equals OK" .f(() => message.StatusCode.Should().Be(HttpStatusCode.OK)); "Then the inner result can be parsed" .f(async() => result = await message.Content.ReadAsAsync <ResourceCollection <CustomerListModel> >()); "Then there are some customers in the result" .f(() => result.Results.Count().Should().BeGreaterOrEqualTo(91)); "Then there is a self link in the result" .f(() => result.Links.Should().Contain(l => l.Rel == "self")); }
public void CardTypeIndicators() { string name = Guid.NewGuid().ToString("n"); var createRequest = new CustomerRequest { CreditCard = new CreditCardRequest { CardholderName = name, Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Unknown, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } } }; gateway.Customer.Create(createRequest); CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest(). CreditCardCardholderName.Is(name); ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest); CreditCardVerification verification = collection.FirstItem; Assert.AreEqual(verification.CreditCard.Prepaid, Braintree.CreditCardPrepaid.UNKNOWN); Assert.AreEqual(verification.CreditCard.Debit, Braintree.CreditCardDebit.UNKNOWN); Assert.AreEqual(verification.CreditCard.DurbinRegulated, Braintree.CreditCardDurbinRegulated.UNKNOWN); Assert.AreEqual(verification.CreditCard.Commercial, Braintree.CreditCardCommercial.UNKNOWN); Assert.AreEqual(verification.CreditCard.Healthcare, Braintree.CreditCardHealthcare.UNKNOWN); Assert.AreEqual(verification.CreditCard.Payroll, Braintree.CreditCardPayroll.UNKNOWN); Assert.AreEqual(verification.CreditCard.CountryOfIssuance, Braintree.CreditCard.CountryOfIssuanceUnknown); Assert.AreEqual(verification.CreditCard.IssuingBank, Braintree.CreditCard.IssuingBankUnknown); Assert.AreEqual(verification.CreditCard.ProductId, Braintree.CreditCard.ProductIdUnknown); }
public static mediaList ToMediaList(this ResourceCollection directoryEntries, int index, int count) { var requestedPage = directoryEntries.Skip(index).Take(count).ToList(); var collections = new List <AbstractMedia>(); foreach (var subdirectory in requestedPage.Where(x => x is Container)) { collections.Add(new mediaCollection { id = subdirectory.Identifier.Id, title = subdirectory.DisplayName, itemType = itemType.collection, canEnumerate = true, canPlay = true }); } foreach (var entry in requestedPage.Where(x => x is MusicFile)) { var meta = entry.ToMediaMetadata(); ((trackMetadata)meta.Item).albumId = null != directoryEntries.Identifier ? directoryEntries.Identifier.Id : null; collections.Add(meta); } return(new mediaList { count = count, index = index, Items = collections.ToArray(), total = directoryEntries.Count }); }
public ActionResult CreateSubscription(int id) { //check for customer, if exists, generate a token off them //if not, generate a generic token and create the customer on post CreateCustomerViewModel model = new CreateCustomerViewModel { PlanId = id }; using (_db) { model.User = _db.Users.Single(u => u.Email == User.Identity.Name); } //Token generation var customerRequest = new CustomerSearchRequest().Email.Is(User.Identity.Name); ResourceCollection <Customer> collection = PaymentGateways.Gateway.Customer.Search(customerRequest); string clientToken; if (collection.Ids.Count != 0) { string custId = collection.FirstItem.Id; clientToken = PaymentGateways.Gateway.ClientToken.generate( new ClientTokenRequest { CustomerId = custId } ); } else { clientToken = PaymentGateways.Gateway.ClientToken.generate(); } ViewBag.ClientToken = clientToken; ViewBag.PlanID = model.PlanId; return(View(model)); }
public void Ids_ReturnsAllIdsInCollection() { string body = @"<search-results> <page-size>2</page-size> <ids type='array'> <items>0</items> <items>1</items> <items>2</items> <items>3</items> <items>4</items> </ids> </search-results>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(body); NodeWrapper xml = new NodeWrapper(doc.ChildNodes[0]); ResourceCollection<string> resourceCollection = new ResourceCollection<string>(xml, delegate(string[] ids) { return new List<string>(); }); List<string> assertIds = new List<string>() {"0","1","2","3","4"}; Assert.AreEqual(resourceCollection.Ids, assertIds); }
/// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { Scheduler.RunTask(async() => { IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; if (!string.IsNullOrEmpty(Category) && string.IsNullOrEmpty(OfferId)) { ResourceCollection <Offer> offers = await partner.Offers.ByCountry(countryCode).ByCategory(Category).GetAsync(CancellationToken).ConfigureAwait(false); WriteOutput(offers.Items); } else if (string.IsNullOrEmpty(OfferId)) { ResourceCollection <Offer> offers = await partner.Offers.ByCountry(countryCode).GetAsync(CancellationToken).ConfigureAwait(false); WriteOutput(offers.Items); } else { Offer offer = await partner.Offers.ByCountry(countryCode).ById(OfferId).GetAsync(CancellationToken).ConfigureAwait(false); WriteObject(offer); } }, true); }
public void Init() { _now = DateTime.Now; _lastModified = _now.AddYears(-1); var resources = new ResourceCollection { CreateResource("Content1", _lastModified.AddDays(-3)), CreateResource("Content2", _lastModified), CreateResource("Content3", _lastModified.AddDays(-10)) }; _finder = new Mock<IResourceFinder>(); _finder.Setup(f => f.FindResources(_resourceType)).Returns(resources); var groupTemplate = new StubResourceGroupTemplate(new ResourceGroup(VirtualPath, resources)); groupTemplate.ResourceType = _resourceType; var configContext = new AssmanContext(ResourceMode.Debug); configContext.AddFinder(_finder.Object); _instance = new DynamicallyConsolidatedResourceHandler(VirtualPath, configContext.GetCompiler(), groupTemplate.WithEmptyContext()) { Now = () => _now }; }
/// <summary> /// Initializes a new instance of the <see cref="Resources{T}" /> class. /// </summary> public Resources() { Resource[] collection = null; if (typeof(T).IsEnum) { var resources = ResourceCollection.GetResources(typeof(T)); if (resources != null) { var names = Enum.GetNames(typeof(T)); var ids = new int[names.Length]; int maxId = 0; for (var i = 0; i < names.Length; i++) { var id = (int)Enum.Parse(typeof(T), names[i]); ids[i] = id; if (maxId < id) { maxId = id; } } collection = new Resource[names.Length]; for (var i = 0; i < names.Length; i++) { var name = names[i]; Resource data; if (resources.TryGetValue(name, out data)) { collection[ids[i]] = data; } } } } this.resources = collection; }
public static WidgetInstance ToViewModel(this Widget pageWidget, ResourceCollection pageJs, ResourceCollection pageCss, IContentManager contentManager, Controller controller, string sourceUrl) { var widget = pageWidget.GetInstance(); pageJs.AddRange(AdminPanelViewModel.DependentJs); pageCss.AddRange(AdminPanelViewModel.DependentCss); var remainingJs = contentManager.Resources.GetResourcePaths(widget.AdminJs.Except(pageJs).ToResourceCollection()).ToList(); var remainingCss = contentManager.Resources.GetResourcePaths(widget.AdminCss.Except(pageCss).ToResourceCollection()).ToList (); string contents; using (var sw = new MemoryStream()) { using (var writer = new HtmlTextWriter(new StringWriter())) { widget.Render(new WidgetContext(controller.ControllerContext, pageWidget, writer, sourceUrl)); contents = writer.InnerWriter.ToString(); } } return(new WidgetInstance { Id = pageWidget.Id, InitializeFunction = widget.CreateFunction, CssClass = widget.CssClass, Js = remainingJs, Css = remainingCss, Contents = contents }); }
public void SetServiceName(string org, string app, [FromBody] dynamic serviceName) { string defaultLang = "nb"; string filename = $"resource.{defaultLang}.json"; string serviceResourceDirectoryPath = _settings.GetLanguageResourcePath(org, app, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)) + filename; if (System.IO.File.Exists(serviceResourceDirectoryPath)) { string textResource = System.IO.File.ReadAllText(serviceResourceDirectoryPath, Encoding.UTF8); ResourceCollection textResourceObject = JsonConvert.DeserializeObject <ResourceCollection>(textResource); if (textResourceObject != null) { textResourceObject.Add("ServiceName", serviceName.serviceName.ToString()); } string resourceString = JsonConvert.SerializeObject(textResourceObject, _serializerSettings); _repository.SaveLanguageResource(org, app, "nb", resourceString); } else { ResourceCollection resourceCollection = new ResourceCollection { Language = "nb", Resources = new List <Resource> { new Resource { Id = "ServiceName", Value = serviceName.serviceName.ToString() } } }; _repository.SaveLanguageResource(org, app, "nb", JsonConvert.SerializeObject(resourceCollection, _serializerSettings)); } }
/// <summary> /// Get all resources /// </summary> /// <returns></returns> public ResourceCollection GetAllResources() { try { ResourceCollection collection = new ResourceCollection(); // execute query using (IDataReader dr = Database.ExecuteReader("UspGetAllResources", CommandType.StoredProcedure)) { while (dr.Read()) { Resource resource = Populate(dr); collection.Add(resource); } } return(collection); } catch (Exception ex) { throw ex; } }
/// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); }
/// <inheritdoc/> protected override void InitializeResources() { var table = TablesStream.ManifestResourceTable; var tmp = new ResourceCollection((int)table.Rows, null, (ctx, i) => CreateResource(i + 1)); Interlocked.CompareExchange(ref resources, tmp, null); }
public IEnumerable <ResourcePath> GetResourcePaths(ResourceCollection resources) { return(GetResourcePaths(resources, EyePatchApplication.ReleaseMode == ReleaseMode.Production, EyePatchApplication.ReleaseMode == ReleaseMode.Production, EyePatchApplication.ReleaseMode == ReleaseMode.Production)); }
private ResourcePath ProcessGroup(ResourceCollection set, bool minify, bool cacheRefresh) { if (!set.Any()) { throw new ApplicationException("Cannot process empty group"); } var firstElement = set.First(); if (set.Count() == 1 && firstElement.IsExternal) { return new ResourcePath { ContentType = firstElement.ContentType, Url = firstElement.Url } } ; var cacheKey = minify ? set.UnqiueId.ToMinPath() : set.UnqiueId; var upgraded = false; try { cacheLock.EnterUpgradeableReadLock(); var cached = cacheProvider.Get <ResourcePath>(cacheKey); if (cached != null && cacheRefresh) { return(cached); } cacheLock.EnterWriteLock(); upgraded = true; var priorWrite = cacheProvider.Get <ResourcePath>(cacheKey); if (priorWrite != null && cacheRefresh) { return(priorWrite); } // regenerate var result = new ResourcePath(); result.ContentType = firstElement.ContentType; result.Url = Url.Action("fetch", "resource", new { id = cacheKey }); // mash result.Contents = set.Mash(); // minify if (minify) { result.Contents = firstElement.ContentType == "text/javascript" ? JavaScriptCompressor.Compress(result.Contents) : CssCompressor.Compress(result.Contents); } // write backup file var physicalFilePath = GetFilePath(set.UnqiueId, minify); if (!Directory.Exists(Path.GetDirectoryName(physicalFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath)); } if (File.Exists(physicalFilePath)) { File.Delete(physicalFilePath); } File.WriteAllText(physicalFilePath, result.Contents); result.FileName = physicalFilePath; cacheProvider.Add(cacheKey, result, set.Files()); return(result); } finally { if (upgraded) { cacheLock.ExitWriteLock(); } cacheLock.ExitUpgradeableReadLock(); } }
/// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); }
/// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { operations.PutResourceCollectionAsync(resourceComplexObject).GetAwaiter().GetResult(); }
protected override void Initialize() { textures = new ResourceCollection<Texture2D>(); spriteBatch = new SpriteBatch(Game.GraphicsDevice); textures.Add("Sun", Game.Content.Load<Texture2D>("sunbg")); }
public ActionResult CreateSubscription(FormCollection collection) { using (_db) { string nonceFromTheClient = collection["payment_method_nonce"]; string planid = collection["planid"]; string cardToken = ""; var user = _db.Users.Single(u => u.Email == User.Identity.Name); //Search for customer var customerRequest = new CustomerSearchRequest().Email.Is(User.Identity.Name); ResourceCollection <Customer> results = PaymentGateways.Gateway.Customer.Search(customerRequest); if (results.Ids.Count == 0) { // If no result, create the customer, create cardToken var request = new CustomerRequest { FirstName = user.FirstName, LastName = user.LastName, Email = User.Identity.Name, Phone = "", CreditCard = new CreditCardRequest { PaymentMethodNonce = nonceFromTheClient, Options = new CreditCardOptionsRequest { VerifyCard = true } } }; Result <Customer> result = PaymentGateways.Gateway.Customer.Create(request); if (!result.IsSuccess()) { TempData["message"] = result.Message; return(Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri)); } cardToken = result.Target.PaymentMethods[0].Token; } SubscriptionRequest newSub; if (!cardToken.Equals("")) { newSub = new SubscriptionRequest { PaymentMethodToken = cardToken, PlanId = planid, NeverExpires = true, Options = new SubscriptionOptionsRequest { StartImmediately = true } }; } else { newSub = new SubscriptionRequest { PaymentMethodNonce = nonceFromTheClient, PlanId = planid, NeverExpires = true, Options = new SubscriptionOptionsRequest { StartImmediately = true } }; } Result <Subscription> subResult = PaymentGateways.Gateway.Subscription.Create(newSub); if (!subResult.IsSuccess()) { TempData["message"] = subResult.Message; return(Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri)); } switch (int.Parse(planid)) { case 1: user.MemberLevel = MemberLevel.Bronze; break; case 2: user.MemberLevel = MemberLevel.Silver; break; case 3: user.MemberLevel = MemberLevel.Gold; break; default: Debug.WriteLine("Invalid Plan Number"); break; } _db.SaveChanges(); TempData["message"] = "success"; return(View("Index")); } }
// [ResponseCache(Duration = 60, VaryByQueryKeys = new string[] { "sortBy", "searchQuery" })] public async Task <ActionResult <ResourceCollection <AuthorDto> > > GetAuthorsAsync( [FromQuery] AuthorResourceParameters parameters) { PagedList <Author> pagedList = null; // 为了简单,仅当请求中不包含过滤和搜索查询字符串时, // 才进行缓存,实际情况不应有此限制 if (string.IsNullOrWhiteSpace(parameters.BirthPlace) && string.IsNullOrWhiteSpace(parameters.SearchQuery)) { string cacheKey = $"authors_page_{parameters.PageNumber}_pageSize_{parameters.PageSize}_{parameters.SortBy}"; string cachedContent = await DistributedCache.GetStringAsync(cacheKey); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new PagedListConverter <Author>()); settings.Formatting = Formatting.Indented; if (string.IsNullOrWhiteSpace(cachedContent)) { pagedList = await RepositoryWrapper.Author.GetAllAsync(parameters); DistributedCacheEntryOptions options = new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(2) }; var serializedContent = JsonConvert.SerializeObject(pagedList, settings); await DistributedCache.SetStringAsync(cacheKey, serializedContent); } else { pagedList = JsonConvert.DeserializeObject <PagedList <Author> >(cachedContent, settings); } } else { pagedList = await RepositoryWrapper.Author.GetAllAsync(parameters); } var paginationMetadata = new { totalCount = pagedList.TotalCount, pageSize = pagedList.PageSize, currentPage = pagedList.CurrentPage, totalPages = pagedList.TotalPages, previousePageLink = pagedList.HasPrevious ? Url.Link(nameof(GetAuthorsAsync), new { pageNumber = pagedList.CurrentPage - 1, pageSize = pagedList.PageSize, birthPlace = parameters.BirthPlace, serachQuery = parameters.SearchQuery, sortBy = parameters.SortBy, }) : null, nextPageLink = pagedList.HasNext ? Url.Link(nameof(GetAuthorsAsync), new { pageNumber = pagedList.CurrentPage + 1, pageSize = pagedList.PageSize, birthPlace = parameters.BirthPlace, serachQuery = parameters.SearchQuery, sortBy = parameters.SortBy, }) : null }; Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata)); var authorDtoList = Mapper.Map <IEnumerable <AuthorDto> >(pagedList); authorDtoList = authorDtoList.Select(author => CreateLinksForAuthor(author)); var resourceList = new ResourceCollection <AuthorDto>(authorDtoList.ToList()); return(CreateLinksForAuthors(resourceList, parameters, paginationMetadata)); }
public async Task Request() { if (ChannelNames.Any() && !Repository.SupportsChannels()) { throw new CommandException("Your Octopus server does not support channels, which was introduced in Octopus 3.2. Please upgrade your Octopus server, or remove the --channel arguments."); } if (string.IsNullOrWhiteSpace(ProjectName)) { throw new CommandException("Please specify a project name using the parameter: --project=XYZ"); } if (string.IsNullOrWhiteSpace(MinVersion)) { throw new CommandException("Please specify a minimum version number using the parameter: --minversion=X.Y.Z"); } if (string.IsNullOrWhiteSpace(MaxVersion)) { throw new CommandException("Please specify a maximum version number using the parameter: --maxversion=X.Y.Z"); } var min = SemanticVersion.Parse(MinVersion); var max = SemanticVersion.Parse(MaxVersion); project = await GetProject().ConfigureAwait(false); var channelsTask = GetChannelIds(project); releases = await Repository.Projects.GetReleases(project).ConfigureAwait(false); channels = await channelsTask.ConfigureAwait(false); commandOutputProvider.Debug("Finding releases for project..."); toDelete = new List <ReleaseResource>(); wouldDelete = new List <ReleaseResource>(); await releases.Paginate(Repository, page => { foreach (var release in page.Items) { if (channels.Any() && !channels.Contains(release.ChannelId)) { continue; } var version = SemanticVersion.Parse(release.Version); if (min > version || version > max) { continue; } if (WhatIf) { commandOutputProvider.Information("[Whatif] Version {Version:l} would have been deleted", version); wouldDelete.Add(release); } else { toDelete.Add(release); commandOutputProvider.Information("Deleting version {Version:l}", version); } } // We need to consider all releases return(true); }) .ConfigureAwait(false); // Don't do anything else for WhatIf if (WhatIf) { return; } foreach (var release in toDelete) { await Repository.Client.Delete(release.Link("Self")).ConfigureAwait(false); } }
public void Search_OnAllTextFields() { string creditCardToken = string.Format("cc{0}", new Random().Next(1000000).ToString()); CustomerRequest request = new CustomerRequest { Company = "Braintree", Email = "*****@*****.**", Fax = "5551231234", FirstName = "Tom", LastName = "Smith", Phone = "5551231235", Website = "http://example.com", CreditCard = new CreditCardRequest { CardholderName = "Tim Toole", Number = "4111111111111111", ExpirationDate = "05/2012", Token = creditCardToken, BillingAddress = new CreditCardAddressRequest { Company = "Braintree", CountryName = "United States of America", ExtendedAddress = "Suite 123", FirstName = "Drew", LastName = "Michaelson", Locality = "Chicago", PostalCode = "12345", Region = "IL", StreetAddress = "123 Main St" } } }; Customer customer = gateway.Customer.Create(request).Target; customer = gateway.Customer.Find(customer.Id); CustomerSearchRequest searchRequest = new CustomerSearchRequest(). Id.Is(customer.Id). FirstName.Is("Tom"). LastName.Is("Smith"). Company.Is("Braintree"). Email.Is("*****@*****.**"). Website.Is("http://example.com"). Fax.Is("5551231234"). Phone.Is("5551231235"). AddressFirstName.Is("Drew"). AddressLastName.Is("Michaelson"). AddressLocality.Is("Chicago"). AddressPostalCode.Is("12345"). AddressRegion.Is("IL"). AddressCountryName.Is("United States of America"). AddressStreetAddress.Is("123 Main St"). AddressExtendedAddress.Is("Suite 123"). PaymentMethodToken.Is(creditCardToken). CardholderName.Is("Tim Toole"). CreditCardNumber.Is("4111111111111111"). CreditCardExpirationDate.Is("05/2012"); ResourceCollection <Customer> collection = gateway.Customer.Search(searchRequest); Assert.AreEqual(1, collection.MaximumCount); Assert.AreEqual(customer.Id, collection.FirstItem.Id); }
/// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { ResourceCollection <License> licenses = Partner.Customers[CustomerId].Users[UserId].Licenses.Get(LicenseGroup?.Select(item => item).ToList()); WriteObject(licenses.Items.Select(l => new PSLicense(l)), true); }
/// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { ResourceCollection <AgreementMetaData> agreements = Partner.AgreementDetails.Get(); WriteObject(agreements.Items.Select(a => new PSAgreementMetaData(a)), true); }
private void Awake() { woodResources = new ResourceCollection <WoodResource>(); stoneResources = new ResourceCollection <StoneResource>(); }
/// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="culture"></param> /// <param name="value"></param> /// <returns></returns> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { String state = value as String; if (state == null) { return base.ConvertFrom(context, culture, value); } if (state == String.Empty) { return new ResourceCollection(); } String[] parts = state.Split('&'); ResourceCollection collection = new ResourceCollection(); foreach (string encRes in parts) { string[] props = Encoder.UrlDecode(encRes).Split('&'); Resource r = new Resource(); r.Name = Encoder.UrlDecode(props[0]); r.Value = Encoder.UrlDecode(props[1]); collection.Add(r); } return collection; }