예제 #1
0
        public async Task <ActionResult> Undelete(int instanceOwnerPartyId, Guid instanceGuid)
        {
            string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}";

            Instance instance;

            try
            {
                instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId);
            }
            catch (DocumentClientException dce)
            {
                if (dce.Error.Code.Equals("NotFound"))
                {
                    return(NotFound($"Didn't find the object that should be restored with instanceId={instanceId}"));
                }

                return(StatusCode(500, $"Unknown database exception in restore: {dce}"));
            }

            if (instance.Status.HardDeleted.HasValue)
            {
                return(BadRequest("Instance was permanently deleted and cannot be restored."));
            }
            else if (instance.Status.SoftDeleted.HasValue)
            {
                instance.LastChangedBy      = User.GetUserOrOrgId();
                instance.LastChanged        = DateTime.UtcNow;
                instance.Status.SoftDeleted = null;

                InstanceEvent instanceEvent = new InstanceEvent
                {
                    Created              = DateTime.UtcNow,
                    EventType            = InstanceEventType.Undeleted.ToString(),
                    InstanceId           = instance.Id,
                    InstanceOwnerPartyId = instance.InstanceOwner.PartyId,
                    User = new PlatformUser
                    {
                        UserId = User.GetUserIdAsInt(),
                        AuthenticationLevel = User.GetAuthenticationLevel(),
                        OrgId = User.GetOrg(),
                    }
                };

                try
                {
                    await _instanceRepository.Update(instance);

                    await _instanceEventRepository.InsertInstanceEvent(instanceEvent);

                    return(Ok(true));
                }
                catch (Exception e)
                {
                    return(StatusCode(500, $"Unknown exception in restore: {e}"));
                }
            }

            return(Ok(true));
        }
예제 #2
0
        /// <inheritdoc/>
        public async Task <string> SaveInstanceEvent(object dataToSerialize, string org, string appName)
        {
            InstanceEvent instanceEvent = (InstanceEvent)dataToSerialize;

            instanceEvent.CreatedDateTime = DateTime.UtcNow;
            string apiUrl = $"instances/{instanceEvent.InstanceId}/events";
            string token  = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _cookieOptions.Cookie.Name);

            JwtTokenUtil.AddTokenToRequestHeader(_client, token);

            try
            {
                HttpResponseMessage response = await _client.PostAsync(apiUrl, new StringContent(instanceEvent.ToString(), Encoding.UTF8, "application/json"));

                string eventData = await response.Content.ReadAsStringAsync();

                InstanceEvent result = JsonConvert.DeserializeObject <InstanceEvent>(eventData);
                return(result.Id.ToString());
            }
            catch
            {
                _logger.LogError($"Unable to store instance event");
                return(null);
            }
        }
예제 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        public App()
        {
            ParseArguments();

            // IsCreatedNew is updated during static fields initialization.
            if (!IsCreatedNew)
            {
                Logger.AddLog("Another instance is already running");

                // Optionally tell the other instance to stop.
                if (IsExitRequested)
                {
                    InstanceEvent.Set();
                }

                UpdateLogger();
                Shutdown();
                return;
            }

            // This code is here mostly to make sure that the Taskbar static class is initialized ASAP.
            // The taskbar rectangle is never empty. And if it is, we have no purpose.
            Rectangle ScreenBounds = TaskbarLocation.ScreenBounds;

            Debug.Assert(!ScreenBounds.IsEmpty);

            Startup += OnStartup;

            // Make sure we stop only on a call to Shutdown. This is for plugins that have a main window, we don't want to exit when it's closed.
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }
예제 #4
0
        public async void Post_UserHasToLowAuthLv_ReturnStatusForbidden()
        {
            // Arrange
            string requestUri = $"storage/api/v1/instances/1337/3c42ee2a-9464-42a8-a976-16eb926bd20a/events/";

            HttpClient client = GetTestClient();
            string     token  = PrincipalUtil.GetToken(3, 1337, 0);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            InstanceEvent instance = new InstanceEvent();

            // Act
            HttpResponseMessage response = await client.PostAsync(requestUri, new StringContent(JsonConvert.SerializeObject(instance), Encoding.UTF8, "application/json"));

            if (response.StatusCode.Equals(HttpStatusCode.InternalServerError))
            {
                string serverContent = await response.Content.ReadAsStringAsync();

                Assert.Equal("Hei", serverContent);
            }

            // Assert
            Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
        }
예제 #5
0
        public Task <InstanceEvent> InsertInstanceEvent(InstanceEvent instanceEvent)
        {
            lock (TestDataUtil.dataLock)
            {
                string instanceId = instanceEvent.InstanceId;

                if (instanceId.Contains("/"))
                {
                    instanceId = instanceEvent.InstanceId.Split("/")[1];
                }

                if (!Directory.Exists(GetInstanceEventsPath(instanceId, instanceEvent.InstanceOwnerPartyId)))
                {
                    Directory.CreateDirectory(GetInstanceEventsPath(instanceId, instanceEvent.InstanceOwnerPartyId));
                }

                instanceEvent.Id = Guid.NewGuid();


                string instancePath = GetInstanceEventPath(instanceId, instanceEvent.InstanceOwnerPartyId, instanceEvent.Id.Value);
                File.WriteAllText(instancePath, instanceEvent.ToString());

                return(Task.FromResult(instanceEvent));
            }
        }
            public async void Undelete_ResponseIsDeny_ReturnsStatusForbidden()
            {
                // Arrange
                MessageBoxTestData testData = new MessageBoxTestData();
                Instance           instance = testData.GetSoftDeletedInstance();

                Mock <IApplicationRepository> applicationRepository = new Mock <IApplicationRepository>();

                Mock <IInstanceRepository> instanceRepository = new Mock <IInstanceRepository>();

                instanceRepository.Setup(s => s.GetOne(It.IsAny <string>(), It.IsAny <int>())).ReturnsAsync(instance);
                instanceRepository.Setup(s => s.Update(It.IsAny <Instance>())).ReturnsAsync((Instance i) => i);

                InstanceEvent instanceEvent = null;

                Mock <IInstanceEventRepository> instanceEventRepository = new Mock <IInstanceEventRepository>();

                instanceEventRepository.Setup(s => s.InsertInstanceEvent(It.IsAny <InstanceEvent>())).Callback <InstanceEvent>(p => instanceEvent = p)
                .ReturnsAsync((InstanceEvent r) => r);

                HttpClient client = GetTestClient(instanceRepository.Object, applicationRepository.Object, instanceEventRepository.Object);
                string     token  = PrincipalUtil.GetToken(-1);

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                // Act
                HttpResponseMessage response = await client.PutAsync($"{BasePath}/sbl/instances/{testData.GetInstanceOwnerPartyId()}/{instance.Id.Split("/")[1]}/undelete", null);

                // Assert
                Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
                string content = await response.Content.ReadAsStringAsync();

                Assert.True(string.IsNullOrEmpty(content));
            }
예제 #7
0
        /// <inheritdoc/>
        public async Task <string> SaveInstanceEvent(object dataToSerialize, string applicationOwnerId, string applicationId)
        {
            InstanceEvent instanceEvent = (InstanceEvent)dataToSerialize;

            instanceEvent.CreatedDateTime = DateTime.UtcNow;
            string apiUrl = $"{_platformSettings.GetApiStorageEndpoint}instances/{instanceEvent.InstanceId}/events";

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    HttpResponseMessage response = await client.PostAsync(apiUrl, new StringContent(instanceEvent.ToString(), Encoding.UTF8, "application/json"));

                    string eventData = await response.Content.ReadAsStringAsync();

                    InstanceEvent result = JsonConvert.DeserializeObject <InstanceEvent>(eventData);
                    return(result.Id.ToString());
                }
                catch
                {
                    throw new Exception("Unable to store instance event");
                }
            }
        }
예제 #8
0
        public async Task <ActionResult> Undelete(int instanceOwnerId, Guid instanceGuid)
        {
            string instanceId = $"{instanceOwnerId}/{instanceGuid}";

            Instance instance;

            try
            {
                instance = await _instanceRepository.GetOne(instanceId, instanceOwnerId);
            }
            catch (DocumentClientException dce)
            {
                if (dce.Error.Code.Equals("NotFound"))
                {
                    return(NotFound($"Didn't find the object that should be restored with instanceId={instanceId}"));
                }

                return(StatusCode(500, $"Unknown database exception in restore: {dce}"));
            }

            if (instance.InstanceState.IsMarkedForHardDelete)
            {
                return(BadRequest("Instance was permanently deleted and cannot be restored."));
            }
            else if (instance.InstanceState.IsDeleted)
            {
                instance.InstanceState.IsDeleted       = false;
                instance.LastChangedBy                 = User.Identity.Name;
                instance.LastChangedDateTime           = DateTime.UtcNow;
                instance.InstanceState.DeletedDateTime = null;

                InstanceEvent instanceEvent = new InstanceEvent
                {
                    CreatedDateTime     = DateTime.UtcNow,
                    AuthenticationLevel = 0, // update when authentication is turned on
                    EventType           = InstanceEventType.Undeleted.ToString(),
                    InstanceId          = instance.Id,
                    InstanceOwnerId     = instance.InstanceOwnerId.ToString(),
                    UserId = 0, // update when authentication is turned on
                };

                try
                {
                    await _instanceRepository.Update(instance);

                    await _instanceEventRepository.InsertInstanceEvent(instanceEvent);

                    return(Ok(true));
                }
                catch (Exception e)
                {
                    return(StatusCode(500, $"Unknown exception in restore: {e}"));
                }

                // generate instance event 'Undeleted'
            }

            return(Ok(true));
        }
예제 #9
0
        /// <inheritdoc/>
        public async Task <InstanceEvent> InsertInstanceEvent(InstanceEvent item)
        {
            item.Id ??= Guid.NewGuid();

            ItemResponse <InstanceEvent> instanceEvent = await Container.CreateItemAsync(item, new PartitionKey(item.InstanceId));

            return(instanceEvent);
        }
예제 #10
0
        public void MapInstanceEventsToProcessHistoryTest(InstanceEvent instanceEvent, string expectedPerformedBy, string expectedEventType)
        {
            ProcessHistoryItem actual = ProcessHelper.MapInstanceEventsToProcessHistory(new List <InstanceEvent> {
                instanceEvent
            }).First();

            Assert.Equal(expectedPerformedBy, actual.PerformedBy);
            Assert.Equal(expectedEventType, actual.EventType);
        }
예제 #11
0
        private void ClearDirty(SimulationModel.Key key, ISimulationAccess access)
        {
            HashSet <Subnet>   nets      = dirtyNets;
            HashSet <Instance> instances = dirtyInstances;

            if (nets != null && nets.Count > 0)
            {
                dirtyNets = new HashSet <Subnet>();
                foreach (Subnet net in nets)
                {
                    if (Debug)
                    {
                        Console.Write("  net {0} /", net);
                    }
                    Value v = null;
                    foreach (Port p in net.Drivers)
                    {
                        Value u = p.GetDrivenValue(key);
                        if (Debug)
                        {
                            Console.Write("{0}/", u);
                        }
                        v = v == null ? u : v.Resolve(u);
                    }
                    if (Debug)
                    {
                        Console.WriteLine("-> {0}", v);
                    }
                    if (v == null)
                    {
                        int w = net.Width;
                        v = Value.Create(Value.U, w == 0 ? 1 : w);
                    }
                    net.SetValue(key, v);
                    foreach (Port p in net.Readers)
                    {
                        instances.Add(p.Instance);
                    }
                }
            }

            if (instances != null && instances.Count > 0)
            {
                InstanceEvent evnt   = new InstanceEvent(InstanceEvent.Types.InstanceDirty);
                InstanceState iState = new InstanceState(access, null);
                dirtyInstances = new HashSet <Instance>();
                foreach (Instance instance in instances)
                {
                    if (Debug)
                    {
                        Console.WriteLine("  propagate instance {0}", instance);
                    }
                    iState.Instance = instance;
                    instance.HandleEvent(evnt, iState);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Inserts new instance event into the instanceEvent collection.
        /// </summary>
        /// <param name="instanceEvent">Instance event to be stored. </param>
        /// <returns>The stored instance event.</returns>
        public async Task <string> PostInstanceEvent(InstanceEvent instanceEvent)
        {
            string requestUri            = $"{versionPrefix}/instances/{instanceEvent.InstanceId}/events";
            HttpResponseMessage response = await client.PostAsync(hostName + requestUri, new StringContent(instanceEvent.ToString(), Encoding.UTF8, "application/json"));

            string newId = await response.Content.ReadAsStringAsync();

            return(newId);
        }
예제 #13
0
        public Task<InstanceEvent> InsertInstanceEvent(InstanceEvent instanceEvent)
        {
            instanceEvent.Id = Guid.NewGuid();

            string path = GetInstanceEventPath(instanceEvent.InstanceId, instanceEvent.Id.Value);
            Directory.CreateDirectory(GetInstanceEventFolder());
            File.WriteAllText(path, instanceEvent.ToString());

            return Task.FromResult(instanceEvent);
        }
        /// <inheritdoc/>
        public async Task <InstanceEvent> InsertInstanceEvent(InstanceEvent item)
        {
            ResourceResponse <Document> response = await Client.CreateDocumentAsync(CollectionUri, item);

            Document document = response.Resource;

            InstanceEvent instanceEvent = JsonConvert.DeserializeObject <InstanceEvent>(document.ToString());

            return(instanceEvent);
        }
예제 #15
0
        /// <summary>
        /// This method will remove duplicate events keeping the last of two or more events in a row.
        /// Duplicates are defined as two events of the same event type, triggered by the same
        /// user on the same resource.
        /// </summary>
        /// <param name="originalList">The original list of instance events.</param>
        /// <returns>A sorted and filtered list of instance events.</returns>
        public static List <InstanceEvent> RemoveDuplicateEvents(List <InstanceEvent> originalList)
        {
            foreach (InstanceEvent item in originalList.Where(ie => !string.IsNullOrEmpty(ie.DataId) && ie.EventType.Equals(InstanceEventType.Created.ToString())))
            {
                item.EventType = InstanceEventType.Saved.ToString();
            }

            List <InstanceEvent> orderedEnumerable =
                originalList
                .Where(ie =>
                       string.IsNullOrEmpty(ie.DataId) ||
                       ie.EventType.Equals(
                           InstanceEventType.Saved.ToString(),
                           StringComparison.InvariantCultureIgnoreCase))
                .OrderBy(ie => ie.Created).ToList();

            List <InstanceEvent> finalResult = new List <InstanceEvent>();

            for (int i = 0; i < orderedEnumerable.Count; i++)
            {
                InstanceEvent currentInstanceEvent = orderedEnumerable[i];

                InstanceEvent nextInstanceEvent =
                    i + 1 < orderedEnumerable.Count ? orderedEnumerable[i + 1] : null;

                if (nextInstanceEvent == null)
                {
                    // Last event should always be added.
                    finalResult.Add(currentInstanceEvent);
                    continue;
                }

                if (currentInstanceEvent.EventType != nextInstanceEvent.EventType)
                {
                    finalResult.Add(currentInstanceEvent);
                    continue;
                }

                string currentSubject = currentInstanceEvent.User?.UserId != null
                    ? currentInstanceEvent.User?.UserId.ToString()
                    : currentInstanceEvent.User?.OrgId;

                string nextSubject = nextInstanceEvent.User?.UserId != null
                    ? nextInstanceEvent.User?.UserId.ToString()
                    : nextInstanceEvent.User?.OrgId;

                if (currentSubject != nextSubject)
                {
                    // Events caused by different actors should be kept as separate events.
                    finalResult.Add(currentInstanceEvent);
                }
            }

            return(finalResult);
        }
예제 #16
0
        /// <inheritdoc/>
        public async Task <InstanceEvent> GetOneEvent(string instanceId, Guid eventGuid)
        {
            string cosmosId = eventGuid.ToString();
            Uri    uri      = UriFactory.CreateDocumentUri(databaseId, collectionId, cosmosId);

            InstanceEvent theEvent = await _client
                                     .ReadDocumentAsync <InstanceEvent>(
                uri,
                new RequestOptions { PartitionKey = new PartitionKey(instanceId) });

            return(theEvent);
        }
예제 #17
0
        public async Task <ActionResult> Delete(Guid instanceGuid, int instanceOwnerPartyId, bool hard)
        {
            string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}";

            Instance instance;

            instance = await _instanceRepository.GetOne(instanceOwnerPartyId, instanceGuid);

            if (instance == null)
            {
                return(NotFound($"Didn't find the object that should be deleted with instanceId={instanceId}"));
            }

            DateTime now = DateTime.UtcNow;

            instance.Status ??= new InstanceStatus();

            if (hard)
            {
                instance.Status.IsHardDeleted = true;
                instance.Status.IsSoftDeleted = true;
                instance.Status.HardDeleted   = now;
                instance.Status.SoftDeleted ??= now;
            }
            else
            {
                instance.Status.IsSoftDeleted = true;
                instance.Status.SoftDeleted   = now;
            }

            instance.LastChangedBy = User.GetUserOrOrgId();
            instance.LastChanged   = now;

            InstanceEvent instanceEvent = new InstanceEvent
            {
                Created              = DateTime.UtcNow,
                EventType            = InstanceEventType.Deleted.ToString(),
                InstanceId           = instance.Id,
                InstanceOwnerPartyId = instance.InstanceOwner.PartyId,
                User = new PlatformUser
                {
                    UserId = User.GetUserIdAsInt(),
                    AuthenticationLevel = User.GetAuthenticationLevel(),
                    OrgId = User.GetOrg(),
                },
            };

            await _instanceRepository.Update(instance);

            await _instanceEventRepository.InsertInstanceEvent(instanceEvent);

            return(Ok(true));
        }
예제 #18
0
        private static void CreatePluginList(Assembly pluginAssembly, List <Type> pluginClientTypeList, Guid embeddedPluginGuid, ITracer logger, out List <IPluginClient> pluginList)
        {
            pluginList = new List <IPluginClient>();

            foreach (Type ClientType in pluginClientTypeList)
            {
                try
                {
                    Contract.RequireNotNull(ClientType.FullName, out string FullName);
                    object?PluginHandle = pluginAssembly.CreateInstance(FullName);
                    if (PluginHandle != null)
                    {
                        string?PluginName            = PluginProperty <string?>(PluginHandle, nameof(IPluginClient.Name));
                        Guid   PluginGuid            = PluginProperty <Guid>(PluginHandle, nameof(IPluginClient.Guid));
                        bool   PluginRequireElevated = PluginProperty <bool>(PluginHandle, nameof(IPluginClient.RequireElevated));
                        bool   PluginHasClickHandler = PluginProperty <bool>(PluginHandle, nameof(IPluginClient.HasClickHandler));

                        if (PluginName != null && PluginName.Length > 0 && PluginGuid != Guid.Empty)
                        {
                            bool            createdNew;
                            EventWaitHandle?InstanceEvent;

                            if (PluginGuid != embeddedPluginGuid)
                            {
                                InstanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, GuidToString(PluginGuid), out createdNew);
                            }
                            else
                            {
                                createdNew    = true;
                                InstanceEvent = null;
                            }

                            if (createdNew && PluginName != null)
                            {
                                IPluginClient NewPlugin = new PluginClient(PluginHandle, PluginName, PluginGuid, PluginRequireElevated, PluginHasClickHandler, InstanceEvent);
                                pluginList.Add(NewPlugin);
                            }
                            else
                            {
                                logger.Write(Category.Warning, "Another instance of a plugin is already running");

                                InstanceEvent?.Close();
                                InstanceEvent = null;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
예제 #19
0
        public async Task <ActionResult> Delete(Guid instanceGuid, int instanceOwnerId, bool hard)
        {
            string instanceId = $"{instanceOwnerId}/{instanceGuid}";

            Instance instance;

            try
            {
                instance = await _instanceRepository.GetOne(instanceId, instanceOwnerId);
            }
            catch (DocumentClientException dce)
            {
                if (dce.Error.Code.Equals("NotFound"))
                {
                    return(NotFound($"Didn't find the object that should be deleted with instanceId={instanceId}"));
                }

                return(StatusCode(500, $"Unknown database exception in delete: {dce}"));
            }
            catch (Exception e)
            {
                return(StatusCode(500, $"Unknown exception in delete: {e}"));
            }

            instance.InstanceState.IsDeleted             = true;
            instance.InstanceState.IsMarkedForHardDelete = hard;
            instance.LastChangedBy       = User.Identity.Name;
            instance.LastChangedDateTime = instance.InstanceState.DeletedDateTime = DateTime.UtcNow;

            InstanceEvent instanceEvent = new InstanceEvent
            {
                CreatedDateTime     = DateTime.UtcNow,
                AuthenticationLevel = 0, // update when authentication is turned on
                EventType           = InstanceEventType.Deleted.ToString(),
                InstanceId          = instance.Id,
                InstanceOwnerId     = instance.InstanceOwnerId.ToString(),
                UserId = 0, // update when authentication is turned on
            };

            try
            {
                await _instanceRepository.Update(instance);

                await _instanceEventRepository.InsertInstanceEvent(instanceEvent);
            }
            catch (Exception e)
            {
                return(StatusCode(500, $"Unknown exception in delete: {e}"));
            }

            return(Ok(true));
        }
예제 #20
0
        private async Task DispatchEvent(string eventType, Instance instance)
        {
            InstanceEvent instanceEvent = new InstanceEvent
            {
                AuthenticationLevel = 0, // update when authentication is turned on
                EventType           = eventType,
                InstanceId          = instance.Id,
                InstanceOwnerId     = instance.InstanceOwnerId,
                UserId      = 0, // update when authentication is turned on
                ProcessInfo = instance.Process,
            };

            await _instanceEventRepository.InsertInstanceEvent(instanceEvent);
        }
예제 #21
0
        /// <summary>
        /// Inserts new instance event into the instanceEvent collection.
        /// </summary>
        /// <param name="instanceEvent">Instance event to be stored. </param>
        /// <returns>The stored instance event.</returns>
        public async Task <string> PostInstanceEvent(InstanceEvent instanceEvent)
        {
            string requestUri            = $"{versionPrefix}/instances/{instanceEvent.InstanceId}/events";
            HttpResponseMessage response = await client.PostAsync(hostName + requestUri, new StringContent(instanceEvent.ToString(), Encoding.UTF8, "application/json"));

            if (response.IsSuccessStatusCode)
            {
                string newId = await response.Content.ReadAsStringAsync();

                return(newId);
            }

            throw new StorageClientException($"POST error: {response.ReasonPhrase}");
        }
예제 #22
0
        private static void CreatePluginList(Assembly pluginAssembly, List <Type> PluginClientTypeList, Guid embeddedPluginGuid, IPluginLogger logger, out List <IPluginClient> PluginList)
        {
            PluginList = new List <IPluginClient>();

            foreach (Type ClientType in PluginClientTypeList)
            {
                try
                {
                    object PluginHandle = pluginAssembly.CreateInstance(ClientType.FullName);
                    if (PluginHandle != null)
                    {
                        string PluginName            = PluginHandle.GetType().InvokeMember(nameof(IPluginClient.Name), BindingFlags.Default | BindingFlags.GetProperty, null, PluginHandle, null) as string;
                        Guid   PluginGuid            = (Guid)PluginHandle.GetType().InvokeMember(nameof(IPluginClient.Guid), BindingFlags.Default | BindingFlags.GetProperty, null, PluginHandle, null);
                        bool   PluginRequireElevated = (bool)PluginHandle.GetType().InvokeMember(nameof(IPluginClient.RequireElevated), BindingFlags.Default | BindingFlags.GetProperty, null, PluginHandle, null);
                        bool   PluginHasClickHandler = (bool)PluginHandle.GetType().InvokeMember(nameof(IPluginClient.HasClickHandler), BindingFlags.Default | BindingFlags.GetProperty, null, PluginHandle, null);

                        if (!string.IsNullOrEmpty(PluginName) && PluginGuid != Guid.Empty)
                        {
                            bool            createdNew;
                            EventWaitHandle InstanceEvent;

                            if (PluginGuid != embeddedPluginGuid)
                            {
                                InstanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, GuidToString(PluginGuid), out createdNew);
                            }
                            else
                            {
                                createdNew    = true;
                                InstanceEvent = null;
                            }

                            if (createdNew)
                            {
                                IPluginClient NewPlugin = new PluginClient(PluginHandle, PluginName, PluginGuid, PluginRequireElevated, PluginHasClickHandler, InstanceEvent);
                                PluginList.Add(NewPlugin);
                            }
                            else
                            {
                                logger.AddLog("Another instance of a plugin is already running");
                                InstanceEvent.Close();
                                InstanceEvent = null;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
예제 #23
0
        public async Task <ActionResult <InstanceEvent> > GetOne(int instanceOwnerPartyId, Guid instanceGuid, Guid eventGuid)
        {
            string        instanceId = $"{instanceOwnerPartyId}/{instanceGuid}";
            InstanceEvent theEvent   = await _repository.GetOneEvent(instanceId, eventGuid);

            if (theEvent != null)
            {
                return(Ok(theEvent));
            }
            else
            {
                return(NotFound());
            }
        }
예제 #24
0
        /// <inheritdoc/>
        public async Task <InstanceEvent> InsertInstanceEvent(InstanceEvent item)
        {
            try
            {
                ResourceResponse <Document> response = await _client.CreateDocumentAsync(_collectionUri, item);

                Document document = response.Resource;

                InstanceEvent instanceEvent = JsonConvert.DeserializeObject <InstanceEvent>(document.ToString());

                return(instanceEvent);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #25
0
        private InstanceEvent GenerateProcessChangeEvent(string eventType, Instance instance, DateTime now)
        {
            UserContext userContext = userHelper.GetUserContext(HttpContext).Result;

            InstanceEvent instanceEvent = new InstanceEvent
            {
                InstanceId          = instance.Id,
                InstanceOwnerId     = instance.InstanceOwnerId,
                EventType           = eventType,
                CreatedDateTime     = now,
                UserId              = userContext.UserId,
                AuthenticationLevel = userContext.AuthenticationLevel,
                ProcessInfo         = instance.Process,
            };

            return(instanceEvent);
        }
예제 #26
0
        /// <inheritdoc/>
        public Task <List <InstanceEvent> > GetInstanceEvents(string instanceId, string instanceOwnerId, string org, string app, string[] eventTypes, string from, string to)
        {
            string               developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            string               testDataForParty = _settings.GetTestdataForPartyPath(org, app, developer);
            string               folderForEvents = $"{testDataForParty}{instanceOwnerId}/{instanceId}/events";
            DateTime?            fromDateTime = null, toDateTime = null;
            List <InstanceEvent> events = new List <InstanceEvent>();

            if (!(string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to)))
            {
                try
                {
                    fromDateTime = DateTime.ParseExact(from, "s", CultureInfo.InvariantCulture);
                    toDateTime   = DateTime.ParseExact(to, "s", CultureInfo.InvariantCulture);
                }
                catch
                {
                    _logger.LogError("Unable to perform query. Invalid format for time span. Use string format of UTC.");
                }
            }

            if (Directory.Exists(folderForEvents))
            {
                foreach (string file in Directory.EnumerateFiles(folderForEvents, "*.json"))
                {
                    string        instanceData = File.ReadAllText(file, Encoding.UTF8);
                    InstanceEvent item         = JsonConvert.DeserializeObject <InstanceEvent>(instanceData);
                    events.Add(item);
                }
            }

            IQueryable <InstanceEvent> result = events.AsQueryable();

            if (eventTypes != null && eventTypes.Length > 0 && events.Any())
            {
                result = result.Where(e => eventTypes.Contains(e.EventType));
            }

            if (fromDateTime.HasValue && toDateTime.HasValue && events.Any())
            {
                result = result.Where(e => fromDateTime <e.CreatedDateTime && toDateTime> e.CreatedDateTime);
            }

            return(Task.FromResult(result.ToList()));
        }
            public async void Delete_ArchivedHasRole_ReturnsOk()
            {
                // Arrange
                int            instanceOwnerId    = 1000;
                string         instanceGuid       = "1916cd18-3b8e-46f8-aeaf-4bc3397ddd12";
                string         json               = File.ReadAllText($"data/instances/{org}/{app}/{instanceOwnerId}/{instanceGuid}.json");
                Instance       instance           = JsonConvert.DeserializeObject <Instance>(json);
                HttpStatusCode expectedStatusCode = HttpStatusCode.OK;
                bool           expectedResult     = true;


                Mock <IApplicationRepository> applicationRepository = new Mock <IApplicationRepository>();

                Instance storedInstance = null;

                Mock <IInstanceRepository> instanceRepository = new Mock <IInstanceRepository>();

                instanceRepository.Setup(s => s.GetOne(It.IsAny <string>(), It.IsAny <int>())).ReturnsAsync(instance);
                instanceRepository.Setup(s => s.Update(It.IsAny <Instance>())).Callback <Instance>(p => storedInstance = p).ReturnsAsync((Instance i) => i);

                InstanceEvent instanceEvent = null;

                Mock <IInstanceEventRepository> instanceEventRepository = new Mock <IInstanceEventRepository>();

                instanceEventRepository.Setup(s => s.InsertInstanceEvent(It.IsAny <InstanceEvent>())).Callback <InstanceEvent>(p => instanceEvent = p)
                .ReturnsAsync((InstanceEvent r) => r);

                HttpClient client = GetTestClient(instanceRepository.Object, applicationRepository.Object, instanceEventRepository.Object);

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _validTokenUsr3);

                // Act
                HttpResponseMessage response = await client.DeleteAsync($"{BasePath}/sbl/instances/{instanceOwnerId}/{instanceGuid}?hard=false");

                HttpStatusCode actualStatusCode = response.StatusCode;
                string         content          = await response.Content.ReadAsStringAsync();

                bool actualResult = JsonConvert.DeserializeObject <bool>(content);

                // Assert
                Assert.Equal(expectedResult, actualResult);
                Assert.Equal(expectedStatusCode, actualStatusCode);
                Assert.False(storedInstance.Status.HardDeleted.HasValue);
                Assert.True(storedInstance.Status.SoftDeleted.HasValue);
            }
예제 #28
0
        public async Task <ActionResult> Undelete(int instanceOwnerPartyId, Guid instanceGuid)
        {
            Instance instance;

            instance = await _instanceRepository.GetOne(instanceOwnerPartyId, instanceGuid);

            if (instance == null)
            {
                return(NotFound($"Didn't find the object that should be restored with instanceId={instanceOwnerPartyId}/{instanceGuid}"));
            }

            if (instance.Status.IsHardDeleted)
            {
                return(NotFound("Instance was permanently deleted and cannot be restored."));
            }
            else if (instance.Status.IsSoftDeleted)
            {
                instance.LastChangedBy        = User.GetUserOrOrgId();
                instance.LastChanged          = DateTime.UtcNow;
                instance.Status.IsSoftDeleted = false;
                instance.Status.SoftDeleted   = null;

                InstanceEvent instanceEvent = new InstanceEvent
                {
                    Created              = DateTime.UtcNow,
                    EventType            = InstanceEventType.Undeleted.ToString(),
                    InstanceId           = instance.Id,
                    InstanceOwnerPartyId = instance.InstanceOwner.PartyId,
                    User = new PlatformUser
                    {
                        UserId = User.GetUserIdAsInt(),
                        AuthenticationLevel = User.GetAuthenticationLevel(),
                        OrgId = User.GetOrg(),
                    }
                };

                await _instanceRepository.Update(instance);

                await _instanceEventRepository.InsertInstanceEvent(instanceEvent);

                return(Ok(true));
            }

            return(Ok(true));
        }
예제 #29
0
        public async Task <ActionResult <string> > Post(int instanceOwnerPartyId, Guid instanceGuid, [FromBody] InstanceEvent instanceEvent)
        {
            if (instanceEvent?.InstanceId == null)
            {
                return(BadRequest("Missing parameter values: instance event must exist and instanceId must be set"));
            }

            instanceEvent.Created = instanceEvent.Created?.ToUniversalTime() ?? DateTime.UtcNow;

            InstanceEvent result = await _repository.InsertInstanceEvent(instanceEvent);

            if (result == null)
            {
                return(BadRequest("Unable to write new instance event to database"));
            }

            return(Created(result.Id.ToString(), result));
        }
        public async Task <ActionResult> Post([FromBody] InstanceEvent instanceEvent)
        {
            if (instanceEvent == null || instanceEvent.InstanceId == null)
            {
                return(BadRequest("Missing parameter values: instance event must exist and instanceId must be set"));
            }

            instanceEvent.Created = DateTime.UtcNow;

            InstanceEvent result = await _repository.InsertInstanceEvent(instanceEvent);

            if (result == null)
            {
                return(BadRequest("Unable to write new instance event to database"));
            }

            return(Created(result.Id.ToString(), result));
        }