예제 #1
0
        public async Task <IActionResult> Activate(string hash)
        {
            if (hash == null)
            {
                return(BadRequest());
            }

            try
            {
                NewUserData data = _context.NewUserData.FirstOrDefault(ud => ud.Hash.Equals(hash));

                HttpResponseMessage taskResponse = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={data.processDefinitionId}&&processInstanceId={data.processInstanceId}");

                Task <string>      jsonStringResult = taskResponse.Content.ReadAsStringAsync();
                List <CamundaTask> tasks            = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult.Result);

                if (tasks.Count == 0)
                {
                    return(BadRequest());
                }

                var content = new StringContent("{}", Encoding.UTF8, "application/json");
                HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                return(Ok());
            }
            catch
            {
                return(BadRequest());
            }
        }
예제 #2
0
        public async Task <IActionResult> StartFileUpload(string hash)
        {
            if (hash == null)
            {
                return(BadRequest());
            }

            NewUserData data = _context.NewUserData.FirstOrDefault(ud => ud.Hash.Equals(hash));


            HttpResponseMessage taskResponse2 = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={data.processDefinitionId}&&processInstanceId={data.processInstanceId}");

            Task <string>      jsonStringResult_22 = taskResponse2.Content.ReadAsStringAsync();
            List <CamundaTask> tasks = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult_22.Result);

            if (tasks.Count == 0)
            {
                return(BadRequest());
            }

            HttpResponseMessage taskFormResponse = await client.GetAsync($"{_configuration["url"]}/task/{tasks[0].id}/form-variables");

            Task <string> jsonStringResult = taskFormResponse.Content.ReadAsStringAsync();
            FormVariables vars2            = JsonConvert.DeserializeObject <FormVariables>(jsonStringResult.Result);

            return(Ok(ParseAndGetConstraints(vars2, data.processDefinitionId, data.processInstanceId, tasks[0].id, null)));
        }
예제 #3
0
        public long UserAdd(SqlConnection db, NewUserData user)
        {
            string sql = @"INSERT INTO [User] 
                          (Name,Email,Phone,Password) 
                          VALUES 
                          (@Name,@Email,@Phone,@Password); 
                          SELECT CAST(SCOPE_IDENTITY() as bigint)";

            return(db.Query <long>(sql, new { user.Name, user.Email, user.Phone, user.Password }).Single());
        }
예제 #4
0
 public void OnGet()
 {
     SetupRoles();
     wasCompletedSuccessfully = false;
     MyData = new NewUserData()
     {
         UserName     = "",
         UserPassword = "",
         UserRoles    = new bool[myRoles.Roles.Count()]
     };
 }
예제 #5
0
    public void OnButtonPressed()
    {
        if (!IsDataCorrect())
        {
            _incorrectDataInfo.gameObject.SetActive(true);
            return;
        }
        else
        {
            _incorrectDataInfo.gameObject.SetActive(false);
        }

        string ipAddressString = string.Empty;

        foreach (InputField addressByteText in _addressByteTexts)
        {
            if (!ipAddressString.Equals(string.Empty))
            {
                ipAddressString += (".");
            }

            ipAddressString += addressByteText.text;
        }
        IPAddress serverAddress = IPAddress.Parse(ipAddressString);

        _welcomeScreenObject.SetActive(false);
        _loadingScreenObject.SetActive(true);

        ChatClient.I.ConnectToServer(serverAddress);

        NewUserData newUserData = new NewUserData();

        newUserData.Nickname = _nickname.text;

        ChatUser.I.nickname = _nickname.text;

        Thread newUserThread = new Thread(() => ChatClient.I.SendMessageToServer(newUserData));

        newUserThread.Start();

        if (_dataOnStart.isOn)
        {
            for (int i = 0; i < _addressByteTexts.Count; i++)
            {
                PlayerPrefs.SetString(string.Format("address{0}", i), _addressByteTexts[i].text);
            }
            PlayerPrefs.SetString("nickname", _nickname.text);
        }
        else
        {
            PlayerPrefs.DeleteAll();
        }
    }
예제 #6
0
        public async Task SaveAsync(NewUserData newUser)
        {
            var url = await cloudStorageService.SaveFile(newUser.Image, CONTAINER_NAME);

            await userRepository.SaveAsync(new User
            {
                Email    = newUser.Email,
                Image    = new Image(url),
                Name     = newUser.Name,
                Password = CriptoHelper.encrypt(newUser.Password),
            });
        }
예제 #7
0
        public ActionResult <string> Public_PortalCreateAccount([FromBody] NewUserData obj)
        {
            if (!this.features.CreateAccount.Execute)
            {
                return(BadRequest(new ServiceError
                {
                    Message = this.features.CreateAccount.ErrorMessage
                }));
            }

            return(ExecuteRemoteService(obj));
        }
        internal async Task OnCommandExecute()
        {
            var result = await _dialogService.OpenDialog();

            NewUserData state = _dialogService.State as NewUserData;

            if (result.GetValueOrDefault(false) &&
                state != null)
            {
                var response = await _client.AddTwitterUserAsync(new GetTwitterUserRequest { Handle = state.Handle, Language = state.Handle, VoiceName = state.VoiceName });
            }
        }
예제 #9
0
        public async Task <ActionResult <String> > SignUpAsync(NewUserData user)
        {
            if (!PasswordManager.ValidatePasswordStrength(user.Password))
            {
                return(BadRequest("Password is not strong enough"));
            }
            if (await _usersRepository.FindOneAsync(x => x.Login == user.Login) != null)
            {
                return(BadRequest("Login is already used"));
            }

            var salt = PasswordManager.GenerateSalt_128();

            var Buckets = new List <ObjectId>();

            DatabaseModule.Entities.Bucket defaultBucket;
            try
            {
                defaultBucket = await AuthenticationManager.GetGoogleBucketDefault(_bucketsRepository);

                Buckets.Add(defaultBucket.Id);
            }
            catch (Exception e)
            {
                return(Ok("User was added without linking default bucket"));
            }

            var newUser = new DatabaseModule.Entities.User()
            {
                Login         = user.Login,
                FirstName     = user.FirstName,
                LastName      = user.LastName,
                BirthDate     = user.BirthDate.Date,
                PasswordHash  = PasswordManager.GeneratePasswordHash(user.Password, salt),
                PasswordSalt  = salt,
                Buckets       = Buckets,
                CurrentBucket = defaultBucket
                                //GoogleBucketConfigData = AuthenticationManager.GoogleBucketConfigData(await AuthenticationManager.GetGoogleBucketDefault())
            };

            await _usersRepository.InsertOneAsync(newUser);

            await _foldersRepository.InsertOneAsync(new Folder()
            {
                Name     = "root",
                OwnerId  = newUser.Id,
                ParentId = null
            });

            return(Ok("User was added"));
        }
예제 #10
0
        public async Task <ActionResult> SaveAndLogin(NewUserData newUser)
        {
            try
            {
                await userService.SaveAsync(newUser);

                var userData = await userService.LoginAsync(newUser.ToLoginData());

                return(Ok(userData));
            }
            catch (Exception ex)
            {
                return(BadRequest(Json(ex)));
            }
        }
예제 #11
0
        private void HandleNewUserData(AData receivedData, Socket socket)
        {
            NewUserData data = (NewUserData)receivedData;

            if (OpenWall.UserList.Keys.Any(userSocket => userSocket == socket))
            {
                return;
            }

            ChatUser newUser = new ChatUser();

            newUser.Nickname = data.Nickname;

            AddUserToChannel(socket, newUser, OpenWall);

            NetworkMessage networkMessage = new NetworkMessage(OpenWall.GetChannelData());

            OpenWall.SendDataToAllUsers(networkMessage.ByteMessage);
        }
    private void HideLoadingScreen()
    {
        NewUserData newUserData = new NewUserData();

        newUserData.Nickname = ChatUser.I.nickname;

        Thread newUserThread = new Thread(() => ChatClient.I.SendMessageToServer(newUserData));

        newUserThread.Start();

        _loadingScreen.SetActive(false);
        _manageChannelSpace.SetActive(true);

        foreach (ChannelData channelData in channelDataCache)
        {
            Debug.Log("GO!");

            ChatClient.I.SendMessageToServer(channelData);
        }
    }
예제 #13
0
        public async Task <bool> RegisterUser([FromBody] NewUserData value)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    Name     = value.Name,
                    LastName = value.LastName,
                    Location = value.Location,
                    Type     = value.Type,
                    UserName = value.Email,
                    Email    = value.Email,
                };

                var result = await userManager.CreateAsync(user, value.Password);

                if (result.Succeeded)
                {
                    string ctoken = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    string confirmationLink = Url.Action("ConfirmEmail", "user", new
                    {
                        userId = user.Id,
                        token  = ctoken
                    }, Request.Scheme);

                    string message = $"Thank you for registering, before logging in please activate your account by clicking the link below <br> <a href=\"{confirmationLink}\">{confirmationLink}</a><br></div>";

                    await Task.Run(() => emailSender.SendEmailAsync(value.Email, "Account Activation", message));
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            BLL.ClientHelper clientHelper = new BLL.ClientHelper();
            if (Session["User"] != null)
            {
                LoggedInUser = Session["User"] as Entities.User;
                if (LoggedInUser != null)
                {
                    if (!IsPostBack)
                    {
                        List <User> clients = new List <User>();
                        clients.Add(new User()
                        {
                            FirstName = "geen", ID = 0
                        });
                        var dbusers = clientHelper.GetClientList(LoggedInUser);
                        clients.AddRange(dbusers);
                        NewUserData.DataSource = clients;

                        NewUserData.DataTextField  = "FirstName";
                        NewUserData.DataValueField = "ID";
                        NewUserData.DataBind();
                        //DAL.DBUserConnection dBUserConnection = new DAL.DBUserConnection();
                        //User UserData = dBUserConnection.GetUser(Convert.ToInt32(NewUserData.SelectedValue+1));
                        //UserDataController.Data = UserData;
                        //UserDataController.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("/SignIn");
                }
            }
            else
            {
                Response.Redirect("/SignIn");
            }
        }
예제 #15
0
        public ActionResult <string> CreateAccount([FromBody] NewUserData newUser)
        {
            try
            {
                using (var db = new SqlConnection(GetDBConnectionString()))
                {
                    var service = new UserCreateAccountV1(userRepository);

                    if (!service.Exec(db, newUser))
                    {
                        return(BadRequest(service.Error));
                    }

                    return(Ok());
                }
            }
            catch (System.Exception ex)
            {
                return(BadRequest(new ServiceError {
                    DebugInfo = ex.ToString(), Message = _defaultError
                }));
            }
        }
 public ActionResult <string> Public_AdminCreateAccount([FromBody] NewUserData obj)
 {
     return(ExecuteRemoteService(obj));
 }
예제 #17
0
 public long AdminAdd(SqlConnection db, NewUserData user)
 {
     return(1);
 }
예제 #18
0
        public async Task <IActionResult> PostReviewData([FromBody] ReviewDto dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            User boardMember                  = _context.Users.FirstOrDefault(u => u.Email.Equals(dto.Token));
            WorkApplicationData data          = _context.workApplicationData.FirstOrDefault(wad => wad.Id.Equals(dto.Id));
            List <UserReview>   allReviews    = _context.UserReview.Where(ur => ur.WorkApplicationDataId.Equals(dto.Id)).ToList();
            UserReview          currentReview = allReviews.Find(u => u.WorkApplicationDataId.Equals(data.Id) && u.UserId.Equals(boardMember.Id));

            data.Comments += $"\n {boardMember.Email}: {dto.Comment} \n";

            switch (dto.Result)
            {
            case "approve":
                _context.UserReview.Remove(currentReview);
                data.BoardMembersApprove += 1;

                _context.workApplicationData.Update(data);
                _context.SaveChanges();
                break;

            case "decline":
                _context.UserReview.Remove(currentReview);

                _context.SaveChanges();
                break;

            case "needMoreData":
                _context.UserReview.Remove(currentReview);
                data.BoardMembeNeedsMoreData = true;

                _context.workApplicationData.Update(data);
                _context.SaveChanges();
                break;
            }

            //TODO u workaplication data sacuvati komentare u novom polu i posle ih proslediti kroz mail
            List <UserReview> currentAllReviews = _context.UserReview.Where(ur => ur.WorkApplicationDataId.Equals(dto.Id)).ToList();

            if (currentAllReviews.Count > 0)
            {
                HttpResponseMessage taskResponse = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={data.processDefinitionId}&&processInstanceId={data.processInstanceId}");

                Task <string>      jsonStringResult = taskResponse.Content.ReadAsStringAsync();
                List <CamundaTask> tasks            = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult.Result);

                if (tasks.Count == 0)
                {
                    return(BadRequest());
                }

                var content = new StringContent("{}", Encoding.UTF8, "application/json");
                HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);
            }
            else
            {
                HttpResponseMessage taskResponse = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={data.processDefinitionId}&&processInstanceId={data.processInstanceId}");

                Task <string>      jsonStringResult = taskResponse.Content.ReadAsStringAsync();
                List <CamundaTask> tasks            = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult.Result);

                if (tasks.Count == 0)
                {
                    return(BadRequest());
                }

                StringContent content;
                if (data.BoardMembeNeedsMoreData)
                {
                    content = new StringContent(JsonConvert.SerializeObject(new CompleteUserTaskWithVariable()
                    {
                        variables = new WriterFailedAbstract()
                        {
                            WriterFailed = new object()
                        }
                    }), Encoding.UTF8, "application/json");
                    HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                    try
                    {
                        string guid = Guid.NewGuid().ToString();
                        ControlFlow.ResumeOnError(() => { EmailService.SendEmail(new UserDto()
                            {
                                Email = data.WriterEmail, Password = guid, FirstName = data.Comments
                            }, _context, "NeedMoreWork"); });

                        NewUserData newUserData = new NewUserData()
                        {
                            Hash = guid, NewUserEmmail = data.WriterEmail, processDefinitionId = data.processDefinitionId, processInstanceId = data.processInstanceId
                        };
                        _context.NewUserData.Add(newUserData);
                        _context.SaveChanges();

                        //TODO sacuvati u bazu i obrnuti krug
                        //logujem ga
                        FetchAndLock fetchAndLockFail = new FetchAndLock()
                        {
                            workerId = data.WriterEmail, maxTasks = 10, topics = new List <Topic>()
                            {
                                new Topic()
                                {
                                    lockDuration = 10000, topicName = "NotificiranjeIDavanjeRoka"
                                }
                            }
                        };
                        var fetchAndLockContentFail = new StringContent(JsonConvert.SerializeObject(fetchAndLockFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage lockExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContentFail);

                        //daj mi moj lokovan da izvucem id
                        HttpResponseMessage externalTaskInfoFail = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={data.WriterEmail}");

                        Task <string> jsonStringResult_1Fail         = externalTaskInfoFail.Content.ReadAsStringAsync();
                        List <CamundaExternalTask> externalTasksFail = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1Fail.Result);
                        CamundaExternalTask        currenTaskFail    = externalTasksFail.First();

                        //prosledimm reziltat
                        CompleteExternalTask completeExternalTaskFail = new CompleteExternalTask()
                        {
                            workerId = data.WriterEmail, variables = null
                        };
                        var completeExternalTaskContentFail           = new StringContent(JsonConvert.SerializeObject(completeExternalTaskFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage commpleteExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTaskFail.id}/complete", completeExternalTaskContentFail);

                        const int scheduledPeriodMilliseconds = 70000;
                        var       allTasksWaitHandle          = new AutoResetEvent(true);

                        ThreadPool.RegisterWaitForSingleObject(
                            allTasksWaitHandle,
                            (s, b) => { UploadTimeOutCheck(data, _context, _configuration); },
                            null,
                            scheduledPeriodMilliseconds, false);
                    }
                    catch (Exception e)
                    {
                        return(BadRequest());
                    }
                }
                else if (data.BoardMembersApprove == data.BoardMembersInitialCount)
                {
                    content = new StringContent(JsonConvert.SerializeObject(new CompleteUserTaskWithVariable()
                    {
                        variables = new WriterFailedAbstract()
                        {
                            WriterFailed = new WriterFailed()
                            {
                                value = false
                            }
                        }
                    }), Encoding.UTF8, "application/json");
                    HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                    try
                    {
                        string guid = Guid.NewGuid().ToString();
                        ControlFlow.ResumeOnError(() => { EmailService.SendEmail(new UserDto()
                            {
                                Email = data.WriterEmail, Password = guid, FirstName = data.Comments
                            }, _context, "Approved"); });

                        NewUserData newUserData = new NewUserData()
                        {
                            Hash = guid, processDefinitionId = data.processDefinitionId, processInstanceId = data.processInstanceId
                        };
                        _context.NewUserData.Add(newUserData);
                        _context.SaveChanges();

                        //logujem ga
                        FetchAndLock fetchAndLockFail = new FetchAndLock()
                        {
                            workerId = data.WriterEmail, maxTasks = 10, topics = new List <Topic>()
                            {
                                new Topic()
                                {
                                    lockDuration = 10000, topicName = "NotificiranjeOUspehu"
                                }
                            }
                        };
                        var fetchAndLockContentFail = new StringContent(JsonConvert.SerializeObject(fetchAndLockFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage lockExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContentFail);

                        //daj mi moj lokovan da izvucem id
                        HttpResponseMessage externalTaskInfoFail = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={data.WriterEmail}");

                        Task <string> jsonStringResult_1Fail         = externalTaskInfoFail.Content.ReadAsStringAsync();
                        List <CamundaExternalTask> externalTasksFail = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1Fail.Result);
                        CamundaExternalTask        currenTaskFail    = externalTasksFail.First();

                        //prosledimm reziltat
                        CompleteExternalTask completeExternalTaskFail = new CompleteExternalTask()
                        {
                            workerId = data.WriterEmail, variables = null
                        };
                        var completeExternalTaskContentFail           = new StringContent(JsonConvert.SerializeObject(completeExternalTaskFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage commpleteExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTaskFail.id}/complete", completeExternalTaskContentFail);

                        const int scheduledPeriodMilliseconds = 70000;
                        var       allTasksWaitHandle          = new AutoResetEvent(true);

                        ThreadPool.RegisterWaitForSingleObject(
                            allTasksWaitHandle,
                            (s, b) => { TimeOutCheck(data, _context, _configuration); },
                            null,
                            scheduledPeriodMilliseconds, false);
                    }
                    catch (Exception e)
                    {
                        return(BadRequest());
                    }
                }
                else if (data.BoardMembersApprove < (data.BoardMembersInitialCount - data.BoardMembersApprove))
                {
                    content = new StringContent(JsonConvert.SerializeObject(new CompleteUserTaskWithVariable()
                    {
                        variables = new WriterFailedAbstract()
                        {
                            WriterFailed = new WriterFailed()
                            {
                                value = true
                            }
                        }
                    }), Encoding.UTF8, "application/json");
                    HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                    try
                    {
                        ControlFlow.ResumeOnError(() => { EmailService.SendEmail(new UserDto()
                            {
                                Email = data.WriterEmail, FirstName = data.Comments
                            }, _context, "Declined"); });
                        //logujem ga
                        FetchAndLock fetchAndLockFail = new FetchAndLock()
                        {
                            workerId = data.WriterEmail, maxTasks = 10, topics = new List <Topic>()
                            {
                                new Topic()
                                {
                                    lockDuration = 10000, topicName = "NotificiranjeOOdbijanju"
                                }
                            }
                        };
                        var fetchAndLockContentFail = new StringContent(JsonConvert.SerializeObject(fetchAndLockFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage lockExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContentFail);

                        //daj mi moj lokovan da izvucem id
                        HttpResponseMessage externalTaskInfoFail = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={data.WriterEmail}");

                        Task <string> jsonStringResult_1Fail         = externalTaskInfoFail.Content.ReadAsStringAsync();
                        List <CamundaExternalTask> externalTasksFail = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1Fail.Result);
                        CamundaExternalTask        currenTaskFail    = externalTasksFail.First();

                        //prosledimm reziltat
                        CompleteExternalTask completeExternalTaskFail = new CompleteExternalTask()
                        {
                            workerId = data.WriterEmail, variables = null
                        };
                        var completeExternalTaskContentFail           = new StringContent(JsonConvert.SerializeObject(completeExternalTaskFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage commpleteExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTaskFail.id}/complete", completeExternalTaskContentFail);

                        const int scheduledPeriodMilliseconds = 70000;
                        var       allTasksWaitHandle          = new AutoResetEvent(true);

                        ThreadPool.RegisterWaitForSingleObject(
                            allTasksWaitHandle,
                            (s, b) => { UploadTimeOutCheck(data, _context, _configuration); },
                            null,
                            scheduledPeriodMilliseconds, false);
                    }
                    catch (Exception e)
                    {
                        return(BadRequest());
                    }
                }
                else
                {
                    content = new StringContent(JsonConvert.SerializeObject(new CompleteUserTaskWithVariable()
                    {
                        variables = new WriterFailedAbstract()
                        {
                            WriterFailed = new object()
                        }
                    }), Encoding.UTF8, "application/json");
                    HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                    try
                    {
                        string guid = Guid.NewGuid().ToString();
                        ControlFlow.ResumeOnError(() => { EmailService.SendEmail(new UserDto()
                            {
                                Email = data.WriterEmail, Password = guid, FirstName = data.Comments
                            }, _context, "NeedMoreWork"); });

                        NewUserData newUserData = new NewUserData()
                        {
                            Hash = guid, NewUserEmmail = data.WriterEmail, processDefinitionId = data.processDefinitionId, processInstanceId = data.processInstanceId
                        };
                        _context.NewUserData.Add(newUserData);
                        _context.SaveChanges();

                        //logujem ga
                        FetchAndLock fetchAndLockFail = new FetchAndLock()
                        {
                            workerId = data.WriterEmail, maxTasks = 10, topics = new List <Topic>()
                            {
                                new Topic()
                                {
                                    lockDuration = 10000, topicName = "NotificiranjeIDavanjeRoka"
                                }
                            }
                        };
                        var fetchAndLockContentFail = new StringContent(JsonConvert.SerializeObject(fetchAndLockFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage lockExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContentFail);

                        //daj mi moj lokovan da izvucem id
                        HttpResponseMessage externalTaskInfoFail = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={data.WriterEmail}");

                        Task <string> jsonStringResult_1Fail         = externalTaskInfoFail.Content.ReadAsStringAsync();
                        List <CamundaExternalTask> externalTasksFail = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1Fail.Result);
                        CamundaExternalTask        currenTaskFail    = externalTasksFail.First();

                        //prosledimm reziltat
                        CompleteExternalTask completeExternalTaskFail = new CompleteExternalTask()
                        {
                            workerId = data.WriterEmail, variables = null
                        };
                        var completeExternalTaskContentFail           = new StringContent(JsonConvert.SerializeObject(completeExternalTaskFail), Encoding.UTF8, "application/json");
                        HttpResponseMessage commpleteExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTaskFail.id}/complete", completeExternalTaskContentFail);
                    }
                    catch (Exception e)
                    {
                        return(BadRequest());
                    }
                }
            }

            return(Ok());
        }
예제 #19
0
        public async Task <IActionResult> Activate(string hash)
        {
            if (hash == null)
            {
                return(BadRequest());
            }

            try
            {
                NewUserData data        = _context.NewUserData.FirstOrDefault(ud => ud.Hash.Equals(hash));
                User        currentUser = _context.Users.FirstOrDefault(u => u.Email.Equals(data.NewUserEmmail));
                currentUser.UserVerified = true;


                _context.Update(currentUser);
                _context.SaveChanges();

                if (data.Writer)
                {
                    ControlFlow.ResumeOnError(() => { EmailService.SendEmail(new UserDto()
                        {
                            FirstName = data.Hash, Writer = data.Writer, Email = data.NewUserEmmail
                        }, null, "WorkUpload"); });
                }

                HttpResponseMessage taskResponse = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={data.processDefinitionId}&&processInstanceId={data.processInstanceId}");

                Task <string>      jsonStringResult = taskResponse.Content.ReadAsStringAsync();
                List <CamundaTask> tasks            = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult.Result);

                if (tasks.Count == 0)
                {
                    return(BadRequest());
                }

                var content = new StringContent("{}", Encoding.UTF8, "application/json");
                HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

                //logujem ga
                FetchAndLock fetchAndLock = new FetchAndLock()
                {
                    workerId = currentUser.Email, maxTasks = 10, topics = new List <Topic>()
                    {
                        new Topic()
                        {
                            lockDuration = 10000, topicName = "ProveraKorisnikovePotvrde"
                        }
                    }
                };
                var fetchAndLockContent = new StringContent(JsonConvert.SerializeObject(fetchAndLock), Encoding.UTF8, "application/json");
                HttpResponseMessage lockExternalTask = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContent);

                //daj mi moj lokovan da izvucem id
                HttpResponseMessage externalTaskInfo = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={currentUser.Email}");

                Task <string> jsonStringResult_1         = externalTaskInfo.Content.ReadAsStringAsync();
                List <CamundaExternalTask> externalTasks = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1.Result);
                CamundaExternalTask        currenTask    = externalTasks.First();

                //prosledimm reziltat
                CompleteExternalTask completeExternalTask = new CompleteExternalTask()
                {
                    workerId = currentUser.Email, variables = new VariablesFirstTask()
                    {
                        Writer = new Writer()
                        {
                            value = data.Writer
                        }
                    }
                };
                var completeExternalTaskContent           = new StringContent(JsonConvert.SerializeObject(completeExternalTask), Encoding.UTF8, "application/json");
                HttpResponseMessage commpleteExternalTask = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTask.id}/complete", completeExternalTaskContent);


                return(Ok());
            }
            catch
            {
                return(BadRequest());
            }
        }
예제 #20
0
        public CreatedAtActionResult AddNewUser(NewUserData data)
        {
            // Initialize the new user id variable
            int tmp_key;

            // Update the users database
            try
            {
                // Load the users database into memory
                var users = ReadUsers();

                // Initialize a Random object (because it isn't static)
                var rng = new Random();

                do
                {
                    // Generate a random user id, and if it's taken, pick a new one
                    // until you find one that isn't.

                    tmp_key = rng.Next();

                    // The user id is random for security/privacy reasons;
                    // keys are harder to guess and it makes it harder for
                    // potential attackers to download all the records
                } while (users.ContainsKey(tmp_key.ToString()));

                // Generate some placeholder data
                var tmp_hobbies = new List <Hobby>();
                var tmp_cover   = $"{rng.Next(5)}.jpg";

                // Fill a new UserData object with the supplied data
                // and some placeholders
                var newUser = new UserData {
                    email          = data.email,
                    password       = data.password,
                    salt           = data.salt,
                    realName       = data.realName,
                    birthdate      = data.birthdate,
                    profilePicture = "0.jpg",
                    hobbies        = tmp_hobbies,
                    coverImage     = tmp_cover,
                    id             = tmp_key.ToString(),
                };

                // Add the new user data to the in-memory users database with
                // the newly generated key
                users.Add(tmp_key.ToString(), newUser);

                // Write the updated user data to the database
                UpdateUsers(users);
            } catch (Exception) {
                // If something goes wrong, throw a fit in the console and
                // return a failure state

                Console.WriteLine(" !! EXCEPTION:");
                Console.WriteLine("    An error occurred attempting to add a user to the users database.");

                return(CreatedAtAction("AddNewUser", new { success = false }));
            }

            // Update the user map
            try
            {
                // Load the userMap into memory
                var userMap = ReadUserMap();

                // Add a new entry mapping the supplied email address to the random
                // user id
                userMap.Add(data.email, tmp_key);

                UpdateUserMap(userMap);
            } catch (Exception) {
                // If something goes wrong, throw a fit in the console and
                // return a failure state

                Console.WriteLine(" !! EXCEPTION:");
                Console.WriteLine("    An error occurred attempting to add a user to the user map.");

                return(CreatedAtAction("AddNewUser", new { success = false }));
            }

            try
            {
                return(CreatedAtAction("AddNewUser", new { success = true }));
            } catch (System.InvalidOperationException) {
                return(CreatedAtAction("AddNewUser", new { success = false }));
            }
        }
예제 #21
0
        public async Task <IActionResult> CompleteFileUploadTask([FromBody] NewUserDataDto dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            NewUserData newUserData = _context.NewUserData.FirstOrDefault(nud => nud.Hash.Equals(dto.Hash));

            EntityFramework.Model.User user = _context.Users.FirstOrDefault(u => u.Email.Equals(newUserData.NewUserEmmail));
            if (!user.UserVerified)
            {
                return(BadRequest());
            }

            if (dto.SimulateFail == true)
            {
                user.UserRetryCount += 1;
                _context.Users.Update(user);
                _context.SaveChanges();

                return(Ok());
            }

            HttpResponseMessage taskResponse = await client.GetAsync($"{_configuration["url"]}/task?processDefinitionId={dto.ProcessDefinitionId}&&processInstanceId={dto.ProcessInstanceId}");

            Task <string>      jsonStringResult = taskResponse.Content.ReadAsStringAsync();
            List <CamundaTask> tasks            = JsonConvert.DeserializeObject <List <CamundaTask> >(jsonStringResult.Result);

            if (tasks.Count == 0)
            {
                return(BadRequest());
            }

            //complete task
            var content = new StringContent("{}", Encoding.UTF8, "application/json");
            HttpResponseMessage commpleteTask = await client.PostAsync($"{_configuration["url"]}/task/{tasks[0].id}/complete", content);

            user.UserRetryCount += 1;
            _context.Update(user);
            _context.SaveChanges();

            try
            {
                WorkApplicationData data = new WorkApplicationData()
                {
                    BoardMembeNeedsMoreData = false,
                    BoardMembersApprove     = 0,
                    BoardMembers            = new List <UserReview>(),
                    processDefinitionId     = dto.ProcessDefinitionId,
                    processInstanceId       = dto.ProcessInstanceId,
                    WriterEmail             = user.Email,
                    Comments = "Board member had this to say for your work: \n"
                };

                _context.workApplicationData.Add(data);
                _context.SaveChanges();


                WorkApplicationData currentData = _context.workApplicationData.FirstOrDefault(d => d.Id.Equals(data.Id));
                List <User>         reviewers   = _context.Users.Where(u => u.Email.Contains("clanodbora")).ToList();
                currentData.BoardMembersInitialCount = reviewers.Count();

                foreach (var reviewer in reviewers)
                {
                    currentData.BoardMembers.Add(new UserReview()
                    {
                        UserId = reviewer.Id, WorkApplicationDataId = currentData.Id
                    });
                }

                _context.workApplicationData.Update(currentData);
                _context.SaveChanges();

                //logujem ga
                FetchAndLock fetchAndLock = new FetchAndLock()
                {
                    workerId = user.Email, maxTasks = 10, topics = new List <Topic>()
                    {
                        new Topic()
                        {
                            lockDuration = 10000, topicName = "ProveraKojiPutPisacPodnosiRadove"
                        }
                    }
                };
                var fetchAndLockContent = new StringContent(JsonConvert.SerializeObject(fetchAndLock), Encoding.UTF8, "application/json");
                HttpResponseMessage lockExternalTask = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContent);

                //daj mi moj lokovan da izvucem id
                HttpResponseMessage externalTaskInfo = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={user.Email}");

                Task <string> jsonStringResult_1         = externalTaskInfo.Content.ReadAsStringAsync();
                List <CamundaExternalTask> externalTasks = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1.Result);
                CamundaExternalTask        currenTask    = externalTasks.First();

                //prosledimm rezultat
                ClanOdbora clan = new ClanOdbora()
                {
                    value = user.Email
                };
                ClanoviOdbora clanovi = new ClanoviOdbora()
                {
                    value = reviewers.ConvertAll <string>(u => u.FirstName)
                };
                NumberOfTrials brojPojusaja = new NumberOfTrials()
                {
                    value = user.UserRetryCount
                };
                Camunda.Model.ProcessModel.VariablesSecondTask test = new VariablesSecondTask()
                {
                    ClanOdbora = clan, ClanoviOdbora = clanovi, NumberOfTrials = brojPojusaja
                };
                CompleteExternalTask completeExternalTask = new CompleteExternalTask()
                {
                    workerId = user.Email, variables = test
                };
                var completeExternalTaskContent           = new StringContent(JsonConvert.SerializeObject(completeExternalTask), Encoding.UTF8, "application/json");
                HttpResponseMessage commpleteExternalTask = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTask.id}/complete", completeExternalTaskContent);
            }
            catch (Exception e)
            {
                return(BadRequest());
            }


            if (user.UserRetryCount > 3)
            {
                try
                {
                    EmailService.SendEmail(new UserDto()
                    {
                        Email = user.Email
                    }, _context, "NumberOfUploads");

                    //logujem ga
                    FetchAndLock fetchAndLockFail = new FetchAndLock()
                    {
                        workerId = user.Email, maxTasks = 10, topics = new List <Topic>()
                        {
                            new Topic()
                            {
                                lockDuration = 10000, topicName = "NotificiranjeONeuspehu"
                            }
                        }
                    };
                    var fetchAndLockContentFail = new StringContent(JsonConvert.SerializeObject(fetchAndLockFail), Encoding.UTF8, "application/json");
                    HttpResponseMessage lockExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/fetchAndLock", fetchAndLockContentFail);

                    //daj mi moj lokovan da izvucem id
                    HttpResponseMessage externalTaskInfoFail = await client.GetAsync($"{_configuration["url"]}/external-task?workerId={user.Email}");

                    Task <string> jsonStringResult_1Fail         = externalTaskInfoFail.Content.ReadAsStringAsync();
                    List <CamundaExternalTask> externalTasksFail = JsonConvert.DeserializeObject <List <CamundaExternalTask> >(jsonStringResult_1Fail.Result);
                    CamundaExternalTask        currenTaskFail    = externalTasksFail.First();

                    //prosledimm reziltat
                    CompleteExternalTask completeExternalTaskFail = new CompleteExternalTask()
                    {
                        workerId = user.Email, variables = null
                    };
                    var completeExternalTaskContentFail           = new StringContent(JsonConvert.SerializeObject(completeExternalTaskFail), Encoding.UTF8, "application/json");
                    HttpResponseMessage commpleteExternalTaskFail = await client.PostAsync($"{_configuration["url"]}/external-task/{currenTaskFail.id}/complete", completeExternalTaskContentFail);
                }
                catch (Exception e)
                {
                    return(BadRequest());
                }
            }
            return(Ok());
        }
예제 #22
0
        public bool Exec(SqlConnection db, NewUserData newUser)
        {
            if (string.IsNullOrEmpty(newUser.Name))
            {
                Error = new ServiceError {
                    Message = "Name is empty!"
                };
                return(false);
            }

            if (string.IsNullOrEmpty(newUser.Email))
            {
                Error = new ServiceError {
                    Message = "Email is empty!"
                };
                return(false);
            }
            else
            {
                if (!newUser.Email.Contains("@"))
                {
                    Error = new ServiceError {
                        Message = "Email is invalid!"
                    };
                    return(false);
                }
                else
                {
                    if (!newUser.Email.Split('@')[1].Contains("."))
                    {
                        Error = new ServiceError {
                            Message = "Email is invalid!"
                        };
                        return(false);
                    }
                }
            }

            if (string.IsNullOrEmpty(newUser.Password))
            {
                Error = new ServiceError {
                    Message = "Password is empty!"
                };
                return(false);
            }

            if (newUser.Password.Length < 6)
            {
                Error = new ServiceError {
                    Message = "Password must be 6 characters at least"
                };
                return(false);
            }

            if (repository.UserExists(db, newUser.Email))
            {
                Error = new ServiceError {
                    Message = "User already registered"
                };
                return(false);
            }

            repository.UserAdd(db, newUser);

            return(true);
        }