public void UpsertSharedResourceValidate(UserProfile userProfile, SharedResource sharedResource, JArray sharedResourceResults, dynamic expectedResult)
        {
            //arrange
            var dbResponse = dynamicQueries.FindItemsWhereAsync(dbSettings.UserResourcesCollectionId, Constants.Id, Convert.ToString(userProfile.SharedResourceId, CultureInfo.InvariantCulture));

            dbResponse.ReturnsForAnyArgs(sharedResourceResults);

            Document       updatedDocument = new Document();
            JsonTextReader reader          = new JsonTextReader(new StringReader(ShareTestData.upsertSharedResource));

            updatedDocument.LoadFrom(reader);

            dbService.UpdateItemAsync <SharedResources>(
                Arg.Any <string>(),
                Arg.Any <SharedResources>(),
                Arg.Any <string>()).ReturnsForAnyArgs <Document>(updatedDocument);

            dbService.CreateItemAsync <SharedResources>(
                Arg.Any <SharedResources>(),
                Arg.Any <string>()).ReturnsForAnyArgs <Document>(updatedDocument);

            //act
            var response     = shareBusinessLogic.UpsertSharedResource(userProfile, sharedResource);
            var actualResult = JsonConvert.SerializeObject(response.Result);

            //assert
            Assert.Equal(expectedResult, actualResult);
        }
예제 #2
0
        public IActionResult Index()
        {
            Dictionary <string, string> items = new Dictionary <string, string>();

            items.Add("FC_list", _sharedLocalizer[SharedResource.GetNameRes("fc")]);
            items.Add("PDB_list", "PDB");
            items.Add("Accessories_list", _sharedLocalizer[SharedResource.GetNameRes("accessories")]);
            items.Add("Light_list", _sharedLocalizer[SharedResource.GetNameRes("light")]);
            items.Add("Motors_list", _sharedLocalizer[SharedResource.GetNameRes("motors")]);
            items.Add("ESC_list", "ESC");
            items.Add("Props_list", _sharedLocalizer[SharedResource.GetNameRes("props")]);
            items.Add("Servos_list", _sharedLocalizer[SharedResource.GetNameRes("servos")]);
            items.Add("Videotransmitters_list", _sharedLocalizer[SharedResource.GetNameRes("videotransmitters")]);
            items.Add("Videoreceivers_list", _sharedLocalizer[SharedResource.GetNameRes("videoreceivers")]);
            items.Add("Cameras_list", _sharedLocalizer[SharedResource.GetNameRes("cameras")]);
            items.Add("Goggles_list", _sharedLocalizer[SharedResource.GetNameRes("goggles")]);
            items.Add("Antennas_list", _sharedLocalizer[SharedResource.GetNameRes("antennas")]);
            items.Add("Transmitters_list", _sharedLocalizer[SharedResource.GetNameRes("transmitters")]);
            items.Add("Receivers_list", _sharedLocalizer[SharedResource.GetNameRes("receivers")]);
            items.Add("Rcother_list", _sharedLocalizer[SharedResource.GetNameRes("rcother")]);
            items.Add("Batteries_list", _sharedLocalizer[SharedResource.GetNameRes("batteries")]);
            items.Add("Chargers_list", _sharedLocalizer[SharedResource.GetNameRes("chargers")]);
            items.Add("Frames_list", _sharedLocalizer[SharedResource.GetNameRes("frames")]);
            items.Add("Body_list", _sharedLocalizer[SharedResource.GetNameRes("body")]);

            return(View(items));
        }
 public ProfileController(IOptionsMonitor <TwillioClientOptions> twillioClient, IUserService UserService, SharedResource localizer, ValidationErrors validationErrors)
 {
     this.UserService       = UserService;
     this._localizer        = localizer;
     this._validationErrors = validationErrors;
     this._twillioClient    = twillioClient;
 }
예제 #4
0
        public async Task <IActionResult> Edit(int?id)
        {
            Event find_event;

            if (id != null)
            {
                find_event = await EventsContext.Events.Include(e => e.Type).FirstOrDefaultAsync(p => p.Id == id);

                if (find_event == null)
                {
                    return(NotFound());
                }
            }
            else
            {
                return(NotFound());
            }


            ViewData["add"]           = _sharedLocalizer[SharedResource.GetNameRes("add")];
            ViewData["date"]          = _sharedLocalizer[SharedResource.GetNameRes("date")];
            ViewData["titleEn"]       = _sharedLocalizer[SharedResource.GetNameRes("titleEn")];
            ViewData["titleRu"]       = _sharedLocalizer[SharedResource.GetNameRes("titleRu")];
            ViewData["descriptionEn"] = _sharedLocalizer[SharedResource.GetNameRes("descriptionEn")];
            ViewData["descriptionRu"] = _sharedLocalizer[SharedResource.GetNameRes("descriptionEn")];
            ViewData["eventType"]     = _sharedLocalizer[SharedResource.GetNameRes("eventType")];
            List <EventType>   event_types = EventsContext.EventTypes.ToList();
            EventsManagerModel viewModel   = new EventsManagerModel
            {
                Event      = find_event,
                EventTypes = new SelectList(event_types, "Id", "Name")
            };

            return(View(viewModel));
        }
        public void Dispose_Wait_Running_Or_Queued_Tasks()
        {
            // arrange
            TestResource testResource = new TestResource();
            SharedResource <TestResource> sharedResource = new SharedResource <TestResource>
                                                           (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                           );

            // act
            const int taskCount = 1000;

            Task[] tasks = new Task[taskCount];

            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = sharedResource.UseAsync(p => p.Resource.IncreaseCounterNoThreadSafe());
            }

            sharedResource.Dispose();
            testResource.WaitUntilDisposedFor5Minutes();

            // assert
            Assert.IsTrue(testResource.IsDisposed);
            Assert.IsTrue(testResource.Counter == taskCount);
        }
예제 #6
0
        private async Task <ListPartsManagerViewModel> Parts_list(int page, IQueryable <Part> source, string caller)
        {
            ViewData["add"]           = _sharedLocalizer[SharedResource.GetNameRes("add")];
            ViewData["nameEn"]        = _sharedLocalizer[SharedResource.GetNameRes("nameEn")];
            ViewData["nameRu"]        = _sharedLocalizer[SharedResource.GetNameRes("nameRu")];
            ViewData["details"]       = _sharedLocalizer[SharedResource.GetNameRes("details")];
            ViewData["edit"]          = _sharedLocalizer[SharedResource.GetNameRes("edit")];
            ViewData["delete"]        = _sharedLocalizer[SharedResource.GetNameRes("delete")];
            ViewData["back"]          = _sharedLocalizer[SharedResource.GetNameRes("back")];
            ViewData["next"]          = _sharedLocalizer[SharedResource.GetNameRes("next")];
            ViewData["caller"]        = caller;
            ViewData["methodCreate"]  = "CreateFrom" + caller;
            ViewData["methodDetails"] = "DetailsFrom" + caller;
            ViewData["methodEdit"]    = "EditFrom" + caller;
            ViewData["methodDelete"]  = "Delete" + caller;

            int pageSize = 20;

            var count = await source.CountAsync();

            var items = await source.Skip((page - 1) *pageSize).Take(pageSize).ToListAsync();

            PageViewModel             pageViewModel = new PageViewModel(count, page, pageSize);
            ListPartsManagerViewModel viewModel     = new ListPartsManagerViewModel
            {
                PageViewModel = pageViewModel,
                Parts         = items
            };

            return(viewModel);
        }
 public AccessResourceModel(SharedResource resource)
 {
     Resource = resource ?? throw new ArgumentNullException(nameof(resource));
     Name     = resource.Name;
     Type     = resource.Type;
     TypeName = resource.Type.ToString();
 }
예제 #8
0
        static void Main(string[] args)
        {
            Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");
            Console.Write("Working, press Ctrl+C to stop...");

            var resourceA = new SharedResource {
                Name = "ResourceA"
            };
            var resourceB = new SharedResource {
                Name = "ResourceB"
            };

            var consumerA = new ResourceConsumer
            {
                Name   = "ConsumerA",
                First  = resourceA,
                Second = resourceB
            };

            var consumerB = new ResourceConsumer
            {
                Name   = "ConsumerB",
                First  = resourceB,
                Second = resourceA
            };

            var t1 = Task.Run(() => consumerA.DoWork());
            var t2 = Task.Run(() => consumerB.DoWork());

            Task.WaitAll(t1, t2);
        }
예제 #9
0
        public async Task <IActionResult> Index(int page = 1)
        {
            ViewData["add"]     = _sharedLocalizer[SharedResource.GetNameRes("add")];
            ViewData["date"]    = _sharedLocalizer[SharedResource.GetNameRes("date")];
            ViewData["titleEn"] = _sharedLocalizer[SharedResource.GetNameRes("titleEn")];
            ViewData["titleRu"] = _sharedLocalizer[SharedResource.GetNameRes("titleRu")];
            ViewData["details"] = _sharedLocalizer[SharedResource.GetNameRes("details")];
            ViewData["edit"]    = _sharedLocalizer[SharedResource.GetNameRes("edit")];
            ViewData["delete"]  = _sharedLocalizer[SharedResource.GetNameRes("delete")];
            ViewData["back"]    = _sharedLocalizer[SharedResource.GetNameRes("back")];
            ViewData["next"]    = _sharedLocalizer[SharedResource.GetNameRes("next")];

            int pageSize = 20;

            IQueryable <Event> source = EventsContext.Events;
            var count = await source.CountAsync();

            var items = await source.Skip((page - 1) *pageSize).Take(pageSize).ToListAsync();

            PageViewModel pageViewModel          = new PageViewModel(count, page, pageSize);
            IndexEventManagerViewModel viewModel = new IndexEventManagerViewModel
            {
                PageViewModel = pageViewModel,
                Events        = items
            };

            return(View(viewModel));
        }
예제 #10
0
        void ButtonHandler(SharedButton.ControlEvent control, float x, float y, float width, float height, string text)
        {
            switch (control)
            {
            case SharedButton.ControlEvent.Init:

                m_myButton = UIButton.FromType(UIButtonType.System);
                m_myButton.SetTitle(text, UIControlState.Normal);
                m_myButton.Frame = new CoreGraphics.CGRect(x, y, width, height);
                using (var imageData = NSData.FromStream(SharedResource.GetStream("settings.png")))
                {
                    using (var image = UIImage.LoadFromData(imageData))
                    {
                        m_myButton.SetImage(image, UIControlState.Normal);
                        m_myButton.ImageEdgeInsets = new UIEdgeInsets(0, m_myButton.Frame.Size.Width - image.Size.Width - 15, 0, 0);
                        m_myButton.TitleEdgeInsets = new UIEdgeInsets(0, 0, 0, image.Size.Width + 15);
                    }
                }
                View.Add(m_myButton);
                break;

            case SharedButton.ControlEvent.Click:
                m_myButton.SetTitle(text, UIControlState.Normal);
                break;
            }
        }
예제 #11
0
파일: Pipe.cs 프로젝트: kouweizhong/Pipes-1
        protected Pipe(IReadOnlyCollection <IInlet> connectableInlets, IReadOnlyCollection <IOutlet> connectableOutlets)
        {
            var allLetSharedResources = connectableInlets.Select(i => i.SharedResource).Concat(connectableOutlets.Select(o => o.SharedResource)).ToArray();

            SharedResource     = SharedResource.CreateAndConnect(allLetSharedResources);
            ConnectableInlets  = connectableInlets;
            ConnectableOutlets = connectableOutlets;
        }
예제 #12
0
파일: Let.cs 프로젝트: kouweizhong/Pipes-1
        protected Let(IPromised <IPipe> promisedPipe)
        {
            SharedResource = SharedResource.Create();
            pipe           = new Lazy <IPipe>(promisedPipe.GetPromisedObject);

            SharedResource.AssociatedObject = this;
            activeResourceGroup             = null;
        }
예제 #13
0
        public void SetUp()
        {
            inlet = new Mock <ISimpleInlet <int> >();
            inlet.SetupGet(i => i.SharedResource).Returns(SharedResource.Create());

            outlet = new Mock <ISimpleOutlet <int> >();
            outlet.SetupGet(i => i.SharedResource).Returns(SharedResource.Create());

            dummyPipe = new DummyPipe(inlet.Object, outlet.Object);
        }
예제 #14
0
 public LoginController(IAuthenticationService AuthenticationService,
                        SharedResource _localizer,
                        IDataProtectionProvider dataProtectionProvider,
                        IUserService UserService)
 {
     this.AuthenticationService = AuthenticationService;
     this._localizer            = _localizer;
     this.protector             = dataProtectionProvider.CreateProtector(Strings.Protection.UrlEncription);
     this.UserService           = UserService;
 }
예제 #15
0
        public void Dispose_Ignores_Running_Or_Queued_Tasks_That_Canceled_Or_Faulted()
        {
            // arrange
            TestResource testResource = new TestResource();
            SharedResource <TestResource> sharedResource = new SharedResource <TestResource>
                                                           (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                           );

            // act
            const int taskCount = 1000;

            Task[] tasks           = new Task[taskCount];
            int    normalTaskCount = 0;

            for (int i = 0; i < tasks.Length; i++)
            {
                int switchFactor = i % 3;
                if (switchFactor != 0 && switchFactor != 1)
                {
                    normalTaskCount++;
                }

                CancellationTokenSource tokenSource = new CancellationTokenSource();
                tasks[i] = sharedResource.UseAsync(p =>
                {
                    switch (switchFactor)
                    {
                    case 0:
                        throw new InvalidOperationException("Test Exception");

                    case 1:
                        tokenSource.Cancel();
                        tokenSource.Token.ThrowIfCancellationRequested();
                        break;

                    default:
                        p.Resource.IncreaseCounterNoThreadSafe();
                        break;
                    }
                },
                                                   tokenSource.Token);
            }

            sharedResource.Dispose();
            testResource.WaitUntilDisposedFor5Minutes();

            // assert
            Assert.IsTrue(testResource.IsDisposed);
            Assert.IsTrue(testResource.Counter == normalTaskCount);
        }
예제 #16
0
 public SelectList(
     SharedResource SharedResource,
     Constants constants,
     DBContext context,
     IMapper mapper
     )
 {
     this.mapper         = mapper;
     this.SharedResource = SharedResource;
     this.constants      = constants;
     this.context        = context;
 }
예제 #17
0
        public void SetUp()
        {
            inlet = new Mock <ISimpleInlet <int> >();
            inlet.SetupGet(i => i.SharedResource).Returns(SharedResource.Create());
            inlet.SetupGet(i => i.Pipe).Returns(() => valvedPipe);

            outlet = new Mock <ISimpleOutlet <string> >();
            outlet.SetupGet(o => o.SharedResource).Returns(SharedResource.Create());
            outlet.SetupGet(i => i.Pipe).Returns(() => valvedPipe);

            tieBreaker = new Mock <ITwoWayTieBreaker>();

            valvedPipe = new ValvedPipe <int, string, ITwoWayTieBreaker>(inlet.Object, outlet.Object, tieBreaker.Object);
        }
예제 #18
0
 public SignUpController(IClientService ClientService,
                         SharedResource _localizer,
                         IMailService MailService,
                         EmailServerNoReplyOptions ServerNoReplyOptions,
                         IUserService UserService,
                         Constants Constants,
                         IDataProtectionProvider protectionProvider)
 {
     this.ClientService        = ClientService;
     this._localizer           = _localizer;
     this.MailService          = MailService;
     this.ServerNoReplyOptions = ServerNoReplyOptions;
     this.UserService          = UserService;
     this.Constants            = Constants;
     this.protector            = protectionProvider.CreateProtector(Strings.Protection.UrlEncription);
 }
예제 #19
0
        /// <summary>
        /// A convenience method for creating an adapter for an inlet pair.
        /// This will automatically connect the adapter to the internal inlet and pass events between the adapter and external inlet.
        ///
        /// The external inlet should be the inlet the world can interact with, while the internal inlet is the corresponding inlet of
        /// our internal pipe system - the implementation of this pipe.
        /// </summary>
        protected IAdapterOutlet <TMessage> CreateAndConnectAdapter <TMessage>(IInlet <TMessage> internalInlet, IInlet <TMessage> externalInlet)
        {
            var promisedPipe = new Promised <IPipe>();

            promisedPipe.Fulfill(this);

            var adapterOutlet = new AdapterOutlet <TMessage>(promisedPipe);

            SharedResource.ConnectTo(adapterOutlet.SharedResource);

            adapterOutlets.Add(adapterOutlet);
            inletOutletBiLookup.Add(externalInlet, adapterOutlet);

            // Do not check if the graph forms a tree - it probably doesn't as all adapters are connected
            // to this pipe. However, messages should never be passed in a cycle or violate the "tree-ness" nevertheless.
            adapterOutlet.ConnectTo(internalInlet, false);
            return(adapterOutlet);
        }
예제 #20
0
        public void Canceled_Action_Is_Skipped()
        {
            // arrange
            const string            testResource   = "Test";
            SharedResource <string> sharedResource = new SharedResource <string>
                                                     (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                     );
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Cancel();

            // act
            bool isCanceledTaskRun = false;
            Task canceledTask      = sharedResource.UseAsync(info =>
            {
                SpinRandomly();
                isCanceledTaskRun = true;
            }, cancellationTokenSource.Token);

            string readTestResource = null;
            Task   normalTask       = sharedResource.UseAsync(info =>
            {
                SpinRandomly();
                readTestResource = testResource;
            });

            Exception cachedException = null;

            try { canceledTask.Wait(); }
            catch (Exception e) { cachedException = e; }

            normalTask.Wait();

            // assert
            Assert.IsFalse(isCanceledTaskRun);
            Assert.IsTrue(cachedException is AggregateException);
            Assert.IsTrue(((AggregateException)cachedException).InnerExceptions.Count == 1);
            Assert.IsTrue(((AggregateException)cachedException).InnerExceptions.First() is OperationCanceledException);
            Assert.IsTrue(readTestResource == testResource);
        }
예제 #21
0
        public void One_MaxConcurrentUserCount_Allows_One_Func_Concurrently()
        {
            // arrange
            TestResource testResource = new TestResource();
            SharedResource <TestResource> sharedResource = new SharedResource <TestResource>
                                                           (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                           );

            const int actionCount = 100;

            Task <int>[] tasks         = new Task <int> [actionCount];
            int[]        startCounters = new int[actionCount];
            int[]        endCounters   = new int[actionCount];

            // act
            for (int i = 0; i < actionCount; i++)
            {
                int index = i;
                tasks[index] = sharedResource.UseAsync(info =>
                {
                    startCounters[index] = info.Resource.IncreaseCounter();
                    SpinRandomly();
                    endCounters[index] = info.Resource.DecreaseCounter();
                    return(index);
                });
            }

            Task.WaitAll(tasks);

            // assert
            Assert.IsTrue(testResource.Counter == 0);
            Assert.IsTrue(startCounters.All(p => p == 1));
            Assert.IsTrue(endCounters.All(p => p == 0));

            for (int i = 0; i < actionCount; i++)
            {
                Assert.IsTrue(tasks[i].Result == i);
            }
        }
예제 #22
0
        public void MaxConcurrentUserCount_Can_Be_Set_When_IsMaxConcurrentUserCountReadOnly_Is_False()
        {
            // arrange
            const string            testResource   = "Test";
            SharedResource <string> sharedResource = new SharedResource <string>
                                                     (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: false
                                                     );

            // act
            Exception cachedException = null;

            try { sharedResource.MaxConcurrentUserCount = 2; }
            catch (Exception e) { cachedException = e; }

            // assert
            Assert.IsNull(cachedException);
        }
        void ButtonHandler(SharedButton.ControlEvent control, float x, float y, float width, float height, string text)
        {
            switch (control)
            {
            case SharedButton.ControlEvent.Init:
                var layout = FindViewById <LinearLayout>(Resource.Id.myLayout);
                m_myButton      = new Button(this);
                m_myButton.Text = text;
                var draw = new BitmapDrawable(this.Resources, SharedResource.GetStream("settings.png"));
                draw.SetBounds(0, 0, 128, 128);
                m_myButton.SetCompoundDrawables(null, null, draw, null);
                m_myButton.CompoundDrawablePadding = 5;
                layout.AddView(m_myButton);
                break;

            case SharedButton.ControlEvent.Click:
                m_myButton.Text = text;
                break;
            }
        }
예제 #24
0
        public static void Test()
        {
            int    called  = 0;
            Action dispose = () => called++;

            //Make sure the mock IDisposable class works the way it's supposed to
            using (new GenericDisposable(dispose))
            {
                Assert.That(called, Is.EqualTo(0));
            }
            Assert.That(called, Is.EqualTo(1));
            called = 0;

            SharedResource <GenericDisposable> s1 = null;
            SharedResource <GenericDisposable> s2 = null;

            try
            {
                s1 = new SharedResource <GenericDisposable>(() => new GenericDisposable(dispose));
                Assert.That(called, Is.EqualTo(0));
                s2 = s1.Copy();
                Assert.That(called, Is.EqualTo(0));
                s1.Dispose();
                s1 = null;
                Assert.That(called, Is.EqualTo(0));
                s2.Dispose();
                s2 = null;
                Assert.That(called, Is.EqualTo(1));
            }
            finally
            {
                if (s1 != null)
                {
                    s1.Dispose();
                }
                if (s2 != null)
                {
                    s2.Dispose();
                }
            }
        }
예제 #25
0
        public void MaxConcurrentUserCount_Can_Not_Be_Set_To_Number_Less_Or_Equal_To_Zero()
        {
            // arrange
            const string            testResource   = "Test";
            SharedResource <string> sharedResource = new SharedResource <string>
                                                     (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: false
                                                     );

            // act
            Exception cachedException = null;

            try { sharedResource.MaxConcurrentUserCount = 0; }
            catch (Exception e) { cachedException = e; }

            // assert
            Assert.IsNotNull(cachedException);
            Assert.IsTrue(cachedException.Message == "The MaxConcurrentUserCount must be greater than zero.");
        }
예제 #26
0
        public void Dispose_Disposes_Resource()
        {
            // arrange
            TestResource testResource = new TestResource();
            SharedResource <TestResource> sharedResource = new SharedResource <TestResource>
                                                           (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                           );

            // act
            Task task = sharedResource.UseAsync(p => p.Resource.IncreaseCounterNoThreadSafe());

            sharedResource.Dispose();
            testResource.WaitUntilDisposedFor5Minutes();

            // assert
            Assert.IsTrue(testResource.IsDisposed);
            Assert.IsTrue(testResource.Counter == 1);
        }
예제 #27
0
        public void Disposed_Resource_Throws_Exception_When_Try_To_Use()
        {
            // arrange
            SharedResource <TestResource> sharedResource = new SharedResource <TestResource>
                                                           (
                resource: new TestResource(),
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                           );

            // act
            sharedResource.Dispose();
            Exception cachedException = null;

            try { sharedResource.UseAsync(i => i.Resource.IncreaseCounter()); }
            catch (Exception e) { cachedException = e; }

            // assert
            Assert.IsNotNull(cachedException);
            Assert.IsTrue(cachedException.Message == "This shared resource is already disposed.");
        }
예제 #28
0
        public void MaxConcurrentUserCount_Can_Not_Be_Set_When_IsMaxConcurrentUserCountReadOnly_Is_True()
        {
            // arrange
            const string            testResource   = "Test";
            SharedResource <string> sharedResource = new SharedResource <string>
                                                     (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                     );

            // act
            Exception cachedException = null;

            try { sharedResource.MaxConcurrentUserCount = 2; }
            catch (Exception e) { cachedException = e; }

            // assert
            Assert.IsNotNull(cachedException);
            Assert.IsTrue(cachedException.Message == "The MaxConcurrentUserCount is read-only.");
        }
예제 #29
0
        public async Task <object> UpsertSharedResource(UserProfile userProfile, SharedResource sharedResource)
        {
            List <SharedResource> sharedResources = new List <SharedResource>();
            dynamic userSharedResourcesDBData     = null;
            dynamic response = null;

            if (userProfile?.SharedResourceId != null && userProfile.SharedResourceId != Guid.Empty)
            {
                userSharedResourcesDBData = await dbClient.FindItemsWhereAsync(dbSettings.UserResourcesCollectionId, Constants.Id, Convert.ToString(userProfile.SharedResourceId, CultureInfo.InvariantCulture));
            }
            if (userSharedResourcesDBData != null && userSharedResourcesDBData.Count > 0)
            {
                var userSharedResources = new List <SharedResources>();
                userSharedResources = JsonUtilities.DeserializeDynamicObject <List <SharedResources> >(userSharedResourcesDBData);
                userSharedResources[0].SharedResourceId = userProfile.SharedResourceId;
                userSharedResources[0].SharedResource.Add(sharedResource);
                response = await dbService.UpdateItemAsync(userProfile.SharedResourceId.ToString(), userSharedResources[0],
                                                           dbSettings.UserResourcesCollectionId);
            }
            else
            {
                var userSharedResources = new SharedResources();
                if (userSharedResourcesDBData != null)
                {
                    userSharedResources.SharedResourceId = userProfile.SharedResourceId;
                }
                else
                {
                    userSharedResources.SharedResourceId = Guid.NewGuid();
                }
                sharedResources.Add(sharedResource);
                userSharedResources.SharedResource = sharedResources;
                userProfile.SharedResourceId       = userSharedResources.SharedResourceId;
                await dbService.UpdateItemAsync(userProfile.Id, userProfile,
                                                dbSettings.ProfilesCollectionId);

                response = await dbService.CreateItemAsync((userSharedResources), dbSettings.UserResourcesCollectionId);
            }
            return(response);
        }
예제 #30
0
        public void Next_Action_Runs_If_Previous_Action_Throws_Exception()
        {
            // arrange
            const string            testResource     = "Test";
            const string            exceptionMessage = "Test Exception";
            SharedResource <string> sharedResource   = new SharedResource <string>
                                                       (
                resource: testResource,
                maxConcurrentUserCount: 1,
                isMaxConcurrentUserCountReadOnly: true
                                                       );

            // act
            Task thrownTask = sharedResource.UseAsync(info =>
            {
                SpinRandomly();
                throw new InvalidOperationException(exceptionMessage);
            });

            string readTestResource = null;
            Task   normalTask       = sharedResource.UseAsync(info =>
            {
                SpinRandomly();
                readTestResource = testResource;
            });

            Exception cachedException = null;

            try { thrownTask.Wait(); }
            catch (Exception e) { cachedException = e; }

            normalTask.Wait();

            // assert
            Assert.IsNotNull(cachedException);
            Assert.IsTrue(cachedException is AggregateException);
            Assert.IsTrue(((AggregateException)cachedException).InnerExceptions.Count == 1);
            Assert.IsTrue(((AggregateException)cachedException).InnerExceptions.First().Message == exceptionMessage);
            Assert.IsTrue(readTestResource == testResource);
        }
예제 #31
0
    private Object DoLoad(string path)
    {
        SharedResource res = null;

        if (m_iResTable.ContainsKey(path))
        {
            if(m_iResTable.TryGetValue(path, out res))
            {
                res.RefCount += 1;
                return res.ResObj;
            }
        }
        else
        {
            res = new SharedResource();
            res.RefCount = 1;
            res.ResObj = Resources.Load(path);
            if(null != res.ResObj)
            {
                m_iResTable.Add(path,res);
                return res.ResObj;
            }
        }
        return null;
    }