private async Task <SINnerGroup> CreateGroup(SINnerGroup mygroup)
        {
            try
            {
                if (String.IsNullOrEmpty(this.tbSearchGroupname.Text) && mygroup == null)
                {
                    Program.MainForm.ShowMessageBox("Please specify a groupename to create!");
                    this.tbSearchGroupname.Focus();
                    return(null);
                }
                var client = StaticUtils.GetClient();
                var res    = await client.PostGroupWithHttpMessagesAsync(
                    mygroup,
                    MyCE?.MySINnerFile?.Id);

                ResultGroupPostGroup response = await Backend.Utils.HandleError(res, res.Body) as ResultGroupPostGroup;

                if ((response?.CallSuccess == true))
                {
                    return(response?.MyGroup);
                }

                return(null);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Program.MainForm.ShowMessageBox(ex.Message);
                throw;
            }
            return(null);
        }
        private SINnerGroup SaveValues(SINnerGroup myGroup)
        {
            if (myGroup == null)
            {
                myGroup = new SINnerGroup();
            }

            myGroup.Groupname = tbGroupname.Text;
            myGroup.Id        = Guid.TryParse(tbGroupId.Text, out Guid id) ? id : Guid.NewGuid();
            if (Guid.TryParse(tbParentGroupId.Text, out id))
            {
                myGroup.MyParentGroupId = id;
            }
            myGroup.Password = tbPassword.Text;
            if (String.IsNullOrEmpty(tbPassword.Text))
            {
                myGroup.PasswordHash = null;
            }
            myGroup.Language             = cboLanguage1.SelectedItem.ToString();
            myGroup.IsPublic             = cbIsPublic.Checked;
            myGroup.MyAdminIdentityRole  = tbAdminRole.Text;
            myGroup.GroupCreatorUserName = tbGroupCreatorUsername.Text;
            myGroup.Description          = tbDescription.Text;
            return(myGroup);
        }
 public ucSINnerGroupCreate(SINnerGroup group, bool editMode, bool onlyPWHash)
 {
     MyGroup  = group;
     EditMode = editMode;
     InitializeComponent();
     InitializeMe(onlyPWHash);
 }
Example #4
0
        private SINnerGroup SaveValues(SINnerGroup myGroup)
        {
            if (myGroup == null)
            {
                myGroup = new SINnerGroup();
            }

            myGroup.Groupname = this.tbGroupname.Text;
            Guid id = Guid.Empty;

            if (Guid.TryParse(this.tbGroupId.Text, out id))
            {
                myGroup.Id = id;
            }
            else
            {
                myGroup.Id = Guid.NewGuid();
            }
            if (Guid.TryParse(this.tbParentGroupId.Text, out id))
            {
                myGroup.MyParentGroupId = id;
            }
            myGroup.Password            = tbPassword.Text;
            myGroup.Language            = cboLanguage1.SelectedItem.ToString();
            myGroup.IsPublic            = cbIsPublic.Checked;
            myGroup.MyAdminIdentityRole = tbAdminRole.Text;

            return(myGroup);
        }
        private void BViewGroup_Click(object sender, EventArgs e)
        {
            try
            {
                var group = new SINnerGroup();
                group.Groupname = this.tbSearchGroupname.Text;
                group.IsPublic  = false;
                if ((MyCE?.MySINnerFile.MyGroup != null) &&
                    ((String.IsNullOrEmpty(tbSearchGroupname.Text)) ||
                     (tbSearchGroupname.Text == MyCE?.MySINnerFile.MyGroup?.Groupname)))
                {
                    group = MyCE?.MySINnerFile.MyGroup;
                }

                if (this.tvGroupSearchResult.SelectedNode != null)
                {
                    SINnerSearchGroup sel = tvGroupSearchResult.SelectedNode.Tag as SINnerSearchGroup;
                    if (sel != null)
                    {
                        group = new SINnerGroup(sel);
                    }
                }
                frmSINnerGroupEdit ge = new frmSINnerGroupEdit(group, false);
                var result            = ge.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    group = ge.MySINnerGroupCreate.MyGroup;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Program.MainForm.ShowMessageBox(ex.ToString());
            }
        }
        private async void bCreateGroup_Click(object sender, EventArgs e)
        {
            try
            {
                var group = new SINnerGroup();
                group.Groupname = this.tbSearchGroupname.Text;
                group.IsPublic  = false;
                if ((MyCE?.MySINnerFile.MyGroup != null) &&
                    ((String.IsNullOrEmpty(tbSearchGroupname.Text)) ||
                     (tbSearchGroupname.Text == MyCE?.MySINnerFile.MyGroup?.Groupname)))
                {
                    group = MyCE?.MySINnerFile.MyGroup;
                }

                if (this.tvGroupSearchResult.SelectedNode != null)
                {
                    SINnerSearchGroup sel = tvGroupSearchResult.SelectedNode.Tag as SINnerSearchGroup;
                    if (sel != null)
                    {
                        group = new SINnerGroup(sel);
                    }
                }
                frmSINnerGroupEdit ge = new frmSINnerGroupEdit(group, false);
                var result            = ge.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    group = ge.MySINnerGroupCreate.MyGroup;
                    try
                    {
                        using (new CursorWait(false, this))
                        {
                            var a = await CreateGroup(ge.MySINnerGroupCreate.MyGroup);

                            if (a != null)
                            {
                                MySINSearchGroupResult = await SearchForGroups(a.Groupname);

                                if (MyParentForm?.MyParentForm != null)
                                {
                                    await MyParentForm?.MyParentForm?.CheckSINnerStatus();
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Program.MainForm.ShowMessageBox(exception.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Program.MainForm.ShowMessageBox(ex.ToString());
            }
        }
        //public frmSINnerGroupEdit()
        //{
        //    InitializeComponent();
        //}

        public frmSINnerGroupEdit(SINnerGroup group, bool onlyPWHash)
        {
            InitializeComponent();
            MySINnerGroupCreate.MyGroup = group;
            if (group.Id == null || group.Id == Guid.Empty)
            {
                MySINnerGroupCreate.EditMode = true;
            }
            MySINnerGroupCreate.InitializeMe(onlyPWHash);
        }
        private async Task LeaveGroupTask(SINner mySINnerFile, SINnerGroup myGroup, bool noupdate = false)
        {
            try
            {
                var client   = StaticUtils.GetClient();
                var response = await client.DeleteLeaveGroupWithHttpMessagesAsync(myGroup.Id, mySINnerFile.Id);

                if ((response.Response.StatusCode == HttpStatusCode.OK))
                {
                    try
                    {
                        MyCE = MyCE;
                        if (!noupdate)
                        {
                            TlpGroupSearch_VisibleChanged(null, new EventArgs());
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn("Group disbanded: " + e.Message);
                        Program.MainForm.ShowMessageBox("Group " + myGroup.Groupname + " disbanded because of no members left.");
                    }
                    finally
                    {
                        if ((!noupdate) && (MyParentForm?.MyParentForm != null))
#pragma warning disable 4014
                        {
                            MyParentForm?.MyParentForm?.CheckSINnerStatus();
                        }
#pragma warning restore 4014
                    }
                }
                else
                {
                    var rescontent = await response.Response.Content.ReadAsStringAsync();

                    string msg = "StatusCode: " + response.Response.StatusCode + Environment.NewLine;
                    msg += rescontent;
                    Log.Info(msg);
                    Program.MainForm.ShowMessageBox(msg);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                Program.MainForm.ShowMessageBox(e.Message.ToString());
            }
            if (!noupdate)
            {
                OnGroupJoinCallback?.Invoke(this, myGroup);
            }
        }
        private async void bCreateGroup_Click(object sender, EventArgs e)
        {
            try
            {
                var group = new SINnerGroup();
                group.Groupname = this.tbSearchGroupname.Text;
                group.IsPublic  = false;
                frmSINnerGroupEdit ge = new frmSINnerGroupEdit(group, false);
                var result            = ge.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    try
                    {
                        using (new CursorWait(false, this))
                        {
                            var a = await CreateGroup(ge.MySINnerGroupCreate.MyGroup);

                            if (a != null)
                            {
                                MySINSearchGroupResult = await SearchForGroups(a.Groupname, null, null);

                                if (MyParentForm?.MyParentForm != null)
                                {
                                    await MyParentForm.MyParentForm.CheckSINnerStatus();
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString(), ex);
                MessageBox.Show(ex.ToString());
            }
        }
Example #10
0
        private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            //var tc = new Microsoft.ApplicationInsights.TelemetryClient();
            ResultAccountGetSinnersByAuthorization res = null;

            SINSearchGroupResult ret = new SINSearchGroupResult();

            res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup       sg  = new SINnerGroup();
            SINnerSearchGroup ssg = new SINnerSearchGroup(sg)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            using (var t = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
            }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    if (user == null)
                    {
                        var e = new AuthenticationException("User is not authenticated.");
                        res = new ResultAccountGetSinnersByAuthorization(e)
                        {
                            ErrorText = "Unauthorized"
                        };
                        return(BadRequest(res));
                    }

                    var roles = await _userManager.GetRolesAsync(user);

                    ret.Roles     = roles.ToList();
                    ssg.Groupname = user.UserName;
                    ssg.Id        = Guid.Empty;
                    //get all from visibility
                    List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true);

                    MetricTelemetry mt = new MetricTelemetry("GetSINersByAuthorization", "SINners found",
                                                             mySinners.Count, 0, 0, 0, 0);
                    tc.TrackMetric(mt);
                    foreach (var sin in mySinners)
                    {
                        //check if that char is already added:
                        var foundseq = (from a in ssg.MyMembers where a.MySINner.Id == sin.Id select a);
                        if (foundseq.Any())
                        {
                            continue;
                        }
                        sin.LastDownload = DateTime.Now;
                        SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                        {
                            MySINner = sin,
                            Username = user.UserName
                        };
                        if (sin.MyGroup?.Id != null)
                        {
                            if (!user.FavoriteGroups.Any(a => a.FavoriteGuid == sin.MyGroup.Id.Value))
                            {
                                user.FavoriteGroups.Add(new ApplicationUserFavoriteGroup()
                                {
                                    FavoriteGuid = sin.MyGroup.Id.Value
                                });
                            }
                        }
                        else
                        {
                            ssg.MyMembers.Add(ssgm);
                        }
                    }

                    user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList();


                    foreach (var singroupId in user.FavoriteGroups)
                    {
                        SINnerSearchGroup ssgFromSIN;
                        var singroup = await _context.SINnerGroups.FirstOrDefaultAsync(a => a.Id == singroupId.FavoriteGuid);

                        if (ssg.MySINSearchGroups.Any(a => a.Id == singroupId.FavoriteGuid))
                        {
                            ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == singroupId.FavoriteGuid);
                        }
                        else
                        {
                            ssgFromSIN = new SINnerSearchGroup(singroup);
                            ssg.MySINSearchGroups.Add(ssgFromSIN);
                        }

                        //add all members of his group
                        var members = await singroup.GetGroupMembers(_context, false);

                        foreach (var member in members)
                        {
                            member.LastDownload     = DateTime.Now;
                            member.MyGroup          = singroup;
                            member.MyGroup.MyGroups = new List <SINnerGroup>();
                            SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember
                            {
                                MySINner = member
                            };
                            //check if it is already added:
                            var groupseq = from a in ssgFromSIN.MyMembers where a.MySINner == member select a;
                            if (groupseq.Any())
                            {
                                continue;
                            }
                            ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                            //}
                        }

                        singroup.PasswordHash = "";
                        singroup.MyGroups     = new List <SINnerGroup>();
                    }
                    await _context.SaveChangesAsync();

                    ret.SINGroups.Add(ssg);
                    res = new ResultAccountGetSinnersByAuthorization(ret);

                    return(Ok(res));
                }
                catch (Exception e)
                {
                    try
                    {
                        var user = await _signInManager.UserManager.GetUserAsync(User);

                        ExceptionTelemetry et = new ExceptionTelemetry(e);
                        et.Properties.Add("user", User.Identity.Name);
                        tc.TrackException(et);
                    }
                    catch (Exception ex)
                    {
                        _logger?.LogError(ex.ToString());
                    }

                    res = new ResultAccountGetSinnersByAuthorization(e);
                    return(BadRequest(res));
                }
                finally
                {
                    Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry telemetry =
                        new Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry("GetSINnersByAuthorization",
                                                                                              DateTimeOffset.Now, sw.Elapsed, "Azure", res?.CallSuccess ?? false, res?.ErrorText);
                    tc.TrackAvailability(telemetry);
                }

#pragma warning disable CS0162 // Unreachable code detected
                t.Complete();
#pragma warning restore CS0162 // Unreachable code detected
            }
        }
Example #11
0
 public string ShowDialog(IWin32Window owner, string text, string caption)
 {
     Text = caption;
     lPasswordText.Text = text;
     return(ShowDialog(owner) == DialogResult.OK ? SINnerGroup.GetHashString(tbPassword.Text) : "");
 }
Example #12
0
 private void BOk_Click(object sender, EventArgs e)
 {
     MyGroup = SaveValues(MyGroup);
 }
Example #13
0
 public string ShowDialog(string text, string caption)
 {
     this.Text = caption;
     this.lPasswordText.Text = text;
     return(this.ShowDialog() == DialogResult.OK ? SINnerGroup.GetHashString(tbPassword.Text) : "");
 }
Example #14
0
        private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo)
        {
            _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + ".");
            ApplicationUser user   = null;
            SINner          sinner = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }
                if (uploadInfo.UploadDateTime == null)
                {
                    uploadInfo.UploadDateTime = DateTime.Now;
                }
                if (uploadInfo.Client != null)
                {
                    if (!UploadClientExists(uploadInfo.Client.Id))
                    {
                        _context.UploadClients.Add(uploadInfo.Client);
                    }
                    else
                    {
                        _context.UploadClients.Attach(uploadInfo.Client);
                        _context.Entry(uploadInfo.Client).State = EntityState.Modified;
                        _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client);
                    }
                }
                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                foreach (var tempsinner in uploadInfo.SINners)
                {
                    sinner = tempsinner;
                    if (sinner.Id.ToString() == "string")
                    {
                        sinner.Id = Guid.Empty;
                    }

                    if (String.IsNullOrEmpty(sinner.MyExtendedAttributes.JsonSummary))
                    {
                        return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null"));
                    }

                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if ((sinner.SINnerMetaData.Visibility.Id == null) ||
                        (sinner.SINnerMetaData.Visibility.Id == Guid.Empty))
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    var oldsinner = (from a in _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights)
                                     .Include(b => b.MyGroup)
                                     where a.Id == sinner.Id
                                     select a).FirstOrDefault();
                    if (oldsinner != null)
                    {
                        var  olduserrights = oldsinner.SINnerMetaData.Visibility.UserRights.ToList();
                        bool canedit       = false;
                        foreach (var oldright in olduserrights)
                        {
                            if ((oldright.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant() &&
                                 (oldright.CanEdit == true)))
                            {
                                canedit = true;
                                break;
                            }
                        }
                        if (!canedit)
                        {
                            string msg = "SINner " + sinner.Id + " is not editable for user " + user.Email + ".";
                            throw new NoUserRightException(msg);
                        }
                        _context.UserRights.RemoveRange(olduserrights);
                        bool userfound = false;
                        foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights)
                        {
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ur.CanEdit = true;
                                userfound  = true;
                            }
                            ur.Id       = Guid.NewGuid();
                            ur.SINnerId = sinner.Id;
                            _context.UserRights.Add(ur);
                        }
                        if (!userfound)
                        {
                            SINerUserRight ownUser = new SINerUserRight();
                            ownUser.Id       = Guid.NewGuid();
                            ownUser.SINnerId = sinner.Id;
                            ownUser.CanEdit  = true;
                            ownUser.EMail    = user.Email;
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownUser);
                            _context.UserRights.Add(ownUser);
                        }
                    }
                    else
                    {
                        var ownuserfound = false;
                        var list         = sinner.SINnerMetaData.Visibility.UserRights.ToList();
                        foreach (var ur in list)
                        {
                            ur.SINnerId = sinner.Id;
                            if (ur.EMail.ToLowerInvariant() == "*****@*****.**".ToLowerInvariant())
                            {
                                sinner.SINnerMetaData.Visibility.UserRights.Remove(ur);
                            }
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ownuserfound = true;
                            }
                        }
                        if (!ownuserfound)
                        {
                            SINerUserRight ownright = new SINerUserRight();
                            ownright.CanEdit  = true;
                            ownright.EMail    = user.Email;
                            ownright.SINnerId = sinner.Id;
                            ownright.Id       = Guid.NewGuid();
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownright);
                        }
                    }

                    foreach (var tag in sinner.SINnerMetaData.Tags)
                    {
                        tag.SetSinnerIdRecursive(sinner.Id);
                    }

                    sinner.UploadClientId = uploadInfo.Client.Id;
                    SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user);

                    SINnerGroup oldgroup = null;
                    if (dbsinner != null)
                    {
                        oldgroup = dbsinner.MyGroup;
                        _context.SINners.Attach(dbsinner);
                        if (String.IsNullOrEmpty(sinner.GoogleDriveFileId))
                        {
                            sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                        }
                        if (String.IsNullOrEmpty(sinner.DownloadUrl))
                        {
                            sinner.DownloadUrl = dbsinner.DownloadUrl;
                        }

                        _context.UserRights.RemoveRange(dbsinner.SINnerMetaData.Visibility.UserRights);
                        _context.SINnerVisibility.Remove(dbsinner.SINnerMetaData.Visibility);
                        var alltags = await dbsinner.GetTagsForSinnerFlat(_context);

                        _context.Tags.RemoveRange(alltags);
                        _context.SINnerMetaData.Remove(dbsinner.SINnerMetaData);
                        _context.SINners.Remove(dbsinner);
                        dbsinner.SINnerMetaData.Visibility.UserRights.Clear();
                        dbsinner.SINnerMetaData.Visibility = null;
                        dbsinner.SINnerMetaData.Tags       = null;
                        dbsinner.SINnerMetaData            = null;

                        await _context.SaveChangesAsync();

                        await _context.SINners.AddAsync(sinner);

                        string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString();
                        msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange;
                        _logger.LogError(msg);
                        List <Tag> taglist = sinner.SINnerMetaData.Tags;
                        UpdateEntityEntries(taglist);
                    }
                    else
                    {
                        returncode     = HttpStatusCode.Created;
                        sinner.MyGroup = null;
                        _context.SINners.Add(sinner);
                    }

                    try
                    {
                        await _context.SaveChangesAsync();

                        if (oldgroup != null)
                        {
                            var roles = await _userManager.GetRolesAsync(user);

                            await SINnerGroupController.PutSiNerInGroupInternal(oldgroup.Id.Value, sinner.Id.Value, user, _context,
                                                                                _logger, oldgroup.PasswordHash, roles);
                        }
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        if (e is HubException)
                        {
                            return(Conflict(e));
                        }

                        HubException hue = new HubException("Exception in PostSINnerFile: " + e.ToString(), e);
                        //var msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict) { ReasonPhrase = e.Message };
                        return(Conflict(hue));
                    }
                }

                List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList();
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostSIN", myids));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostSIN", myids));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }

                HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #15
0
        private async void bCreateGroup_Click(object sender, EventArgs e)
        {
            try
            {
                var group = new SINnerGroup();
                group.Groupname = this.tbSearchGroupname.Text;
                group.IsPublic  = false;
                if ((MyCE.MySINnerFile.MyGroup != null) &&
                    ((String.IsNullOrEmpty(tbSearchGroupname.Text)) ||
                     (tbSearchGroupname.Text == MyCE.MySINnerFile.MyGroup?.Groupname)))
                {
                    group = MyCE.MySINnerFile.MyGroup;
                }
                if (this.tvGroupSearchResult.SelectedNode != null)
                {
                    SINnerSearchGroup sel = tvGroupSearchResult.SelectedNode.Tag as SINnerSearchGroup;
                    if (sel != null)
                    {
                        group = new SINnerGroup(sel);
                    }
                }
                frmSINnerGroupEdit ge = new frmSINnerGroupEdit(group, false);
                var result            = ge.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    group = ge.MySINnerGroupCreate.MyGroup;
                    try
                    {
                        using (new CursorWait(false, this))
                        {
                            if (group == MyCE.MySINnerFile.MyGroup)
                            {
                                var client = await StaticUtils.GetClient();

                                var response = await client.PostGroupWithHttpMessagesAsync(group, MyCE.MySINnerFile.Id);

                                if ((response.Response.StatusCode == HttpStatusCode.Accepted) ||
                                    (response.Response.StatusCode == HttpStatusCode.Created) ||
                                    (response.Response.StatusCode == HttpStatusCode.OK))
                                {
                                    //ok
                                }
                                else if ((response.Response.StatusCode == HttpStatusCode.NotFound))
                                {
                                    var rescontent = await response.Response.Content.ReadAsStringAsync();

                                    string msg = "StatusCode: " + response.Response.StatusCode + Environment.NewLine;
                                    msg += rescontent;
                                    throw new ArgumentNullException(nameof(group), msg);
                                }
                                else
                                {
                                    var rescontent = await response.Response.Content.ReadAsStringAsync();

                                    throw new ArgumentException(rescontent);
                                }
                            }
                            else
                            {
                                //create mode

                                var a = await CreateGroup(ge.MySINnerGroupCreate.MyGroup);

                                if (a != null)
                                {
                                    MySINSearchGroupResult = await SearchForGroups(a.Groupname, null, null);

                                    if (MyParentForm?.MyParentForm != null)
                                    {
                                        await MyParentForm.MyParentForm.CheckSINnerStatus();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString(), ex);
                MessageBox.Show(ex.ToString());
            }
        }
 /// <summary>
 /// Store the new group
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='mygroup'>
 /// </param>
 /// <param name='sinnerId'>
 /// </param>
 public static object PostGroup(this ISINnersClient operations, SINnerGroup mygroup = default(SINnerGroup), Guid?sinnerId = default(Guid?))
 {
     return(Task.Factory.StartNew(s => ((ISINnersClient)s).PostGroupAsync(mygroup, sinnerId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
        public async Task <IActionResult> PostGroup([FromBody] SINnerGroup mygroup, Guid SinnerId)
        {
            _logger.LogTrace("Post SINnerGroupInternal: " + mygroup?.Groupname + " (" + SinnerId + ").");
            ApplicationUser user = null;

            //SINner sinner = null;
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }

                if (mygroup == null)
                {
                    return(BadRequest("group == null."));
                }
                if (String.IsNullOrEmpty(mygroup?.Groupname))
                {
                    return(BadRequest("Groupname may not be empty."));
                }

                if (SinnerId == Guid.Empty)
                {
                    return(BadRequest("SinnerId may not be empty."));
                }

                SINnerGroup parentGroup = null;

                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                var sinnerseq = await(from a in _context.SINners.Include(b => b.SINnerMetaData.Visibility.UserRights) where a.Id == SinnerId select a).ToListAsync();
                if (!sinnerseq.Any())
                {
                    string msg = "Please upload SINner prior to adding him/her to a group!";
                    return(BadRequest(new HubException(msg)));
                }
                foreach (var sinner in sinnerseq)
                {
                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if (sinner.SINnerMetaData.Visibility.Id == null)
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    bool found = false;
                    foreach (var sinur in sinner.SINnerMetaData.Visibility.UserRights)
                    {
                        if (sinur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                        {
                            if (sinur.CanEdit == true)
                            {
                                found = true;
                            }
                            break;
                        }
                    }
                    if (!found)
                    {
                        string msg = "Sinner " + sinner.Id + " is not editable for user " + user.UserName + ".";
                        return(BadRequest(new HubException(msg)));
                    }

                    var groupfoundseq = await(from a in _context.SINnerGroups where a.Groupname == mygroup.Groupname select a).ToListAsync();
                    if (groupfoundseq.Any())
                    {
                        string msg = "A group with the name " + mygroup.Groupname + " already exists!";
                        return(BadRequest(new HubException(msg)));
                    }

                    if (mygroup.Id == null || mygroup.Id == Guid.Empty)
                    {
                        mygroup.Id = Guid.NewGuid();
                    }
                    mygroup.MyParentGroup = parentGroup;
                    parentGroup?.MyGroups.Add(mygroup);
                    _context.SINnerGroups.Add(mygroup);
                    returncode = HttpStatusCode.Created;

                    try
                    {
                        await _context.SaveChangesAsync();
                    }

                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is SINnerGroup)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());


                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        HubException hue = new HubException("Exception in PostGroup: " + e.ToString(), e);
                        var          msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            ReasonPhrase = e.Message
                        };
                        return(Conflict(hue));
                    }
                }
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostGroup", mygroup.Id));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostGroup", mygroup.Id));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("Groupname", mygroup?.Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PostGroup: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #18
0
        public async Task <ActionResult <SINSearchGroupResult> > GetSINnersByAuthorization()
        {
            SINSearchGroupResult ret = new SINSearchGroupResult();
            SINnerGroup          sg  = new SINnerGroup();
            SINnerSearchGroup    ssg = new SINnerSearchGroup(sg)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            try
            {
                var user = await _signInManager.UserManager.GetUserAsync(User);

                if (user == null)
                {
                    ret.ErrorText = "Unauthorized";
                    throw new AuthenticationException("User is not authenticated.");
                }
                var roles = await _userManager.GetRolesAsync(user);

                ret.Roles     = roles.ToList();
                ssg.Groupname = user.Email;
                ssg.Id        = Guid.Empty;
                //get all from visibility
                //SINnersList list = new SINnersList();
                List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true);

                foreach (var sin in mySinners)
                {
                    SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                    {
                        MySINner = sin,
                        Username = user.UserName
                    };
                    ssg.MyMembers.Add(ssgm);
                    if (sin.MyGroup != null)
                    {
                        SINnerSearchGroup ssgFromSIN;
                        if (ssg.MySINSearchGroups.Any(a => a.Id == sin.MyGroup.Id))
                        {
                            ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == sin.MyGroup.Id);
                        }
                        else
                        {
                            ssgFromSIN = new SINnerSearchGroup(sin.MyGroup);
                            ssg.MySINSearchGroups.Add(ssgFromSIN);
                        }
                        //add all members of his group
                        var members = await sin.MyGroup.GetGroupMembers(_context);

                        foreach (var member in members)
                        {
                            if ((member.SINnerMetaData.Visibility.IsGroupVisible == true) ||
                                (member.SINnerMetaData.Visibility.IsPublic)
                                )
                            {
                                member.MyGroup          = sin.MyGroup;
                                member.MyGroup.MyGroups = new List <SINnerGroup>();
                                SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember
                                {
                                    MySINner = member
                                };
                                ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                            }
                        }
                        sin.MyGroup.PasswordHash = "";
                        sin.MyGroup.MyGroups     = new List <SINnerGroup>();
                    }
                }

                ret.SINGroups.Add(ssg);
                return(Ok(ret));
            }
            catch (Exception e)
            {
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException(e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #19
0
        private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            //var tc = new Microsoft.ApplicationInsights.TelemetryClient();
            ResultAccountGetSinnersByAuthorization res = null;

            SINSearchGroupResult ret = new SINSearchGroupResult();

            res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup sg   = new SINnerGroup();
            var         user = await _signInManager.UserManager.GetUserAsync(User);

            if (user == null)
            {
                var e = new AuthenticationException("User is not authenticated.");
                res = new ResultAccountGetSinnersByAuthorization(e)
                {
                    ErrorText = "Unauthorized"
                };
                return(BadRequest(res));
            }
            user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList();

            SINnerSearchGroup ssg = new SINnerSearchGroup(sg, user)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            using (var t = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
            {
                IsolationLevel = IsolationLevel.ReadUncommitted
            }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var roles = await _userManager.GetRolesAsync(user);

                    ret.Roles     = roles.ToList();
                    ssg.Groupname = user.UserName;
                    ssg.Id        = Guid.Empty;
                    var worklist      = user.FavoriteGroups.Select(a => a.FavoriteGuid).ToList();
                    var groupworklist = _context.SINnerGroups
                                        .Include(a => a.MyGroups)
                                        .ThenInclude(b => b.MyGroups)
                                        .ThenInclude(c => c.MyGroups)
                                        .ThenInclude(d => d.MyGroups)
                                        .Where(a => a.Id != null && worklist.Contains(a.Id.Value));
                    ssg.MySINSearchGroups = await RecursiveBuildGroupMembers(groupworklist, user);

                    var memberworklist = _context.SINners
                                         .Include(a => a.MyGroup)
                                         .Include(a => a.SINnerMetaData.Visibility)
                                         .Where(a => a.Id != null && worklist.Contains(a.Id.Value));
                    foreach (var member in memberworklist)
                    {
                        if (member.SINnerMetaData?.Visibility?.IsGroupVisible == false)
                        {
                            if (member.SINnerMetaData?.Visibility.UserRights.Any(a =>
                                                                                 !string.IsNullOrEmpty(a.EMail)) == true)
                            {
                                if (member.SINnerMetaData?.Visibility.UserRights.Any(a =>
                                                                                     user.NormalizedEmail.Equals(a.EMail, StringComparison.OrdinalIgnoreCase)) == false)
                                {
                                    //dont show this guy!
                                    continue;
                                }
                            }
                        }

                        member.LastDownload = DateTime.Now;
                        if (member.MyGroup == null)
                        {
                            member.MyGroup = new SINnerGroup();
                        }
                        if (member.MyGroup.MyGroups == null)
                        {
                            member.MyGroup.MyGroups = new List <SINnerGroup>();
                        }
                        SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember(user, member)
                        {
                            MySINner = member
                        };
                        ssg.MyMembers.Add(sinssgGroupMember);
                    }

                    await _context.SaveChangesAsync();

                    ret.SINGroups.Add(ssg);
                    res = new ResultAccountGetSinnersByAuthorization(ret);
                    return(Ok(res));
                }
                catch (Exception e)
                {
                    try
                    {
                        await _signInManager.UserManager.GetUserAsync(User);

                        ExceptionTelemetry et = new ExceptionTelemetry(e);
                        et.Properties.Add("user", User.Identity.Name);
                        tc.TrackException(et);
                    }
                    catch (Exception ex)
                    {
                        _logger?.LogError(ex.ToString());
                    }

                    res = new ResultAccountGetSinnersByAuthorization(e);
                    return(BadRequest(res));
                }
                finally
                {
                    AvailabilityTelemetry telemetry = new AvailabilityTelemetry("GetSINnersByAuthorization", DateTimeOffset.Now, sw.Elapsed, "Azure", res.CallSuccess, res.ErrorText);
                    tc?.TrackAvailability(telemetry);
                }
            }
        }
        public async Task <ActionResult <SINner> > PutGroupInGroup(Guid GroupId, string groupname, Guid?parentGroupId, string adminIdentityRole, bool isPublicVisible)
        {
            _logger.LogTrace("PutGroupInGroup: " + GroupId + " (" + parentGroupId + ", " + adminIdentityRole + ").");
            ApplicationUser user = null;

            try
            {
                user = await _signInManager.UserManager.GetUserAsync(User);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }

                    return(BadRequest(new HubException(msg)));
                }

                SINnerGroup parentGroup = null;
                if (parentGroupId != null)
                {
                    var getParentseq = (from a in _context.SINnerGroups.Include(a => a.MyGroups)
                                        where a.Id == parentGroupId
                                        select a).Take(1);
                    if (!getParentseq.Any())
                    {
                        return(NotFound("Parentgroup with Id " + parentGroupId.ToString() + " not found."));
                    }
                    parentGroup = getParentseq.FirstOrDefault();
                }

                SINnerGroup myGroup     = null;
                var         getGroupseq = (from a in _context.SINnerGroups
                                           where a.Id == GroupId
                                           select a).Take(1);
                if (!getGroupseq.Any())
                {
                    return(NotFound("Group with Id " + parentGroupId.ToString() + " not found."));
                }
                myGroup                     = getGroupseq.FirstOrDefault();
                myGroup.Groupname           = groupname;
                myGroup.IsPublic            = isPublicVisible;
                myGroup.MyAdminIdentityRole = adminIdentityRole;
                myGroup.MyParentGroup       = parentGroup;
                if (parentGroup != null)
                {
                    if (parentGroup.MyGroups == null)
                    {
                        parentGroup.MyGroups = new List <SINnerGroup>();
                    }
                    if (!parentGroup.MyGroups.Contains(myGroup))
                    {
                        parentGroup.MyGroups.Add(myGroup);
                    }
                }

                await _context.SaveChangesAsync();

                return(Ok(myGroup));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("GroupId", GroupId.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PutSINerInGroup: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #21
0
        private async Task <SINnerGroup> CreateGroup(SINnerGroup mygroup)
        {
            try
            {
                if (String.IsNullOrEmpty(this.tbSearchGroupname.Text))
                {
                    MessageBox.Show("Please specify a groupename to create!");
                    this.tbSearchGroupname.Focus();
                    return(null);
                }
                if (this.MyCE == null)
                {
                    MessageBox.Show("MySinner not set!");
                    return(null);
                }

                var client = await StaticUtils.GetClient();

                var Result = await client.PostGroupWithHttpMessagesAsync(
                    mygroup,
                    MyCE.MySINnerFile.Id);

                var rescontent = await Result.Response.Content.ReadAsStringAsync();

                if ((Result.Response.StatusCode == HttpStatusCode.OK) ||
                    (Result.Response.StatusCode == HttpStatusCode.Created))
                {
                    var jsonResultString = Result.Response.Content.ReadAsStringAsync().Result;
                    try
                    {
                        SINnerGroup newgroup = Newtonsoft.Json.JsonConvert.DeserializeObject <SINnerGroup>(jsonResultString);
                        //Guid id;
                        //if (!Guid.TryParse(objIds.ToString(), out id))
                        //{
                        //    string msg = "ChummerHub did not return a valid Id for the group " + this.tbSearchGroupname.Text + ".";
                        //    System.Diagnostics.Trace.TraceError(msg);
                        //    throw new ArgumentException(msg);
                        //}


                        var join = await client.PutSINerInGroupWithHttpMessagesAsync(newgroup.Id,
                                                                                     MyCE.MySINnerFile.Id, mygroup.PasswordHash);

                        if (join.Response.StatusCode == HttpStatusCode.OK)
                        {
                            var getgroup = await client.GetGroupByIdWithHttpMessagesAsync(newgroup.Id);

                            MyCE.MySINnerFile.MyGroup = getgroup.Body;
                            if (OnGroupJoinCallback != null)
                            {
                                OnGroupJoinCallback(this, getgroup.Body);
                            }
                            return(getgroup.Body);
                        }
                        else
                        {
                            var joinresp = join.Response.Content.ReadAsStringAsync().Result;
                            System.Diagnostics.Trace.TraceInformation(joinresp);
                            MessageBox.Show(joinresp);
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.TraceError(ex.ToString());
                        throw;
                    }
                }
                else if (Result.Response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var jsonResultString = Result.Response.Content.ReadAsStringAsync().Result;
                    if (jsonResultString?.Contains("already exists!") == true)
                    {
                        var searchgroup = await client.GetSearchGroupsWithHttpMessagesAsync(mygroup.Groupname, null, null);

                        var id       = searchgroup.Body as Guid?;
                        var getgroup = await client.GetGroupByIdWithHttpMessagesAsync(id);

                        MyCE.MySINnerFile.MyGroup = getgroup.Body;
                        if (OnGroupJoinCallback != null)
                        {
                            OnGroupJoinCallback(this, getgroup.Body);
                        }
                        return(getgroup.Body);
                    }
                }
                else
                {
                    MessageBox.Show(rescontent);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString());
                MessageBox.Show(ex.Message);
                throw;
            }
            return(null);
        }
Example #22
0
        public async Task <bool> CheckSINnerStatus()
        {
            try
            {
                if (myUC?.MyCE?.MySINnerFile?.Id == null || myUC.MyCE.MySINnerFile.Id == Guid.Empty)
                {
                    await bUpload.DoThreadSafeAsync(() => bUpload.Text = "SINless Character/Error");

                    return(false);
                }

                using (new CursorWait(this, true))
                {
                    SinnersClient client = StaticUtils.GetClient();
                    ResultSinnerGetSINnerGroupFromSINerById response = await client.GetSINnerGroupFromSINerByIdAsync(myUC.MyCE.MySINnerFile.Id.Value);

                    SINnerGroup objMySiNnerGroup = response.MySINnerGroup;

                    await PluginHandler.MainForm.DoThreadSafeAsync(() =>
                    {
                        if (objMySiNnerGroup != null)
                        {
                            myUC.MyCE.MySINnerFile.MyGroup = objMySiNnerGroup;
                            bUpload.Text         = "Remove from SINners";
                            bGroupSearch.Enabled = true;
                            lUploadStatus.Text   = "Online";
                            bUpload.Enabled      = true;
                        }
                        else
                        {
                            myUC.MyCE.MySINnerFile.MyGroup = null;
                            lUploadStatus.Text             = "Not Online";
                            bGroupSearch.Enabled           = false;
                            bGroupSearch.SetToolTip(
                                "SINner needs to be uploaded first, before he/she can join a group.");
                            bUpload.Enabled = true;
                            bUpload.Text    = "Upload";
                        }
                        //else if (eResponseStatus == HttpStatusCode.NoContent)
                        //{
                        //    myUC.MyCE.MySINnerFile.MyGroup = null;
                        //    lUploadStatus.Text = "Status Code: " + eResponseStatus;
                        //    bGroupSearch.Enabled = true;
                        //    bGroupSearch.SetToolTip(
                        //        "SINner does not belong to a group.");
                        //    bUpload.Text = "Remove from SINners";
                        //    lUploadStatus.Text = "Online";
                        //    bUpload.Enabled = true;
                        //}
                        cbTagCustom.Enabled        = false;
                        TagValueCustomName.Enabled = false;
                    });

                    await this.DoThreadSafeAsync(UpdateTags);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                await bUpload.DoThreadSafeAsync(() => bUpload.Text = "Unknown Status");

                return(false);
            }
            return(true);
        }
 /// <summary>
 /// Store the new group
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='mygroup'>
 /// </param>
 /// <param name='sinnerId'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <object> PostGroupAsync(this ISINnersClient operations, SINnerGroup mygroup = default(SINnerGroup), Guid?sinnerId = default(Guid?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.PostGroupWithHttpMessagesAsync(mygroup, sinnerId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
        private async Task <SINSearchGroupResult> JoinGroupTask(SINnerSearchGroup searchgroup, CharacterExtended myCE)
        {
            bool exceptionlogged      = false;
            SINSearchGroupResult ssgr = null;

            try
            {
                DialogResult       result    = DialogResult.Cancel;
                frmSINnerGroupEdit groupEdit = null;
                if (searchgroup.HasPassword == true)
                {
                    SINnerGroup joinGroup = new SINnerGroup(searchgroup);
                    PluginHandler.MainForm.DoThreadSafe(() =>
                    {
                        groupEdit = new frmSINnerGroupEdit(joinGroup, true);
                        result    = groupEdit.ShowDialog(this);
                    });
                }

                if ((result == DialogResult.OK) || (searchgroup.HasPassword == false))
                {
                    try
                    {
                        using (new CursorWait(true, this))
                        {
                            var client   = StaticUtils.GetClient();
                            var response =
                                await client.PutSINerInGroupWithHttpMessagesAsync(searchgroup.Id, myCE.MySINnerFile.Id,
                                                                                  groupEdit?.MySINnerGroupCreate?.MyGroup?.PasswordHash);

                            if ((response.Response.StatusCode != HttpStatusCode.OK))
                            {
                                var rescontent = await response.Response.Content.ReadAsStringAsync();

                                if (response.Response.StatusCode == HttpStatusCode.BadRequest)
                                {
                                    if (rescontent.Contains("PW is wrong!"))
                                    {
                                        throw new ArgumentException("Wrong Password provided!");
                                    }

                                    string searchfor = "NoUserRightException\",\"Message\":\"";
                                    if (rescontent.Contains(searchfor))
                                    {
                                        string msg =
                                            rescontent.Substring(rescontent.IndexOf(searchfor) + searchfor.Length);
                                        msg = msg.Substring(0, msg.IndexOf("\""));
                                        throw new ArgumentException(msg);
                                    }

                                    throw new ArgumentException(rescontent);
                                }
                                else
                                {
                                    string msg = "StatusCode: " + response.Response.StatusCode + Environment.NewLine;
                                    msg += rescontent;
                                    throw new ArgumentException(msg);
                                }
                            }
                            else
                            {
                                var found = await client.GetGroupByIdWithHttpMessagesAsync(searchgroup.Id, null,
                                                                                           CancellationToken.None);

                                var res = Backend.Utils.HandleError(found);
                                if (found?.Response?.IsSuccessStatusCode == true)
                                {
                                    ssgr = new SINSearchGroupResult(found.Body.MyGroup);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                        exceptionlogged = true;
                        throw;
                    }
                    finally
                    {
                        MyParentForm?.MyParentForm?.CheckSINnerStatus();
                    }
                }
            }
            catch (Exception e)
            {
                if (!exceptionlogged)
                {
                    Log.Error(e);
                }

                throw;
            }


            return(ssgr);
        }
Example #25
0
        public async Task <bool> CheckSINnerStatus()
        {
            try
            {
                if (myUC?.MyCE?.MySINnerFile?.Id == null || myUC.MyCE.MySINnerFile.Id == Guid.Empty)
                {
                    this.DoThreadSafe(() =>
                    {
                        bUpload.Text = "SINless Character/Error";
                    });
                    return(false);
                }

                using (new CursorWait(this, true))
                {
                    var client   = StaticUtils.GetClient();
                    var response = await client.GetSINnerGroupFromSINerByIdWithHttpMessagesAsync(myUC.MyCE.MySINnerFile.Id.Value).ConfigureAwait(true);

                    HttpStatusCode eResponseStatus  = response.Response.StatusCode;
                    SINnerGroup    objMySiNnerGroup = eResponseStatus == HttpStatusCode.OK ? response.Body.MySINnerGroup : null;
                    response.Dispose();
                    PluginHandler.MainForm.DoThreadSafe(() =>
                    {
                        if (eResponseStatus == HttpStatusCode.OK)
                        {
                            myUC.MyCE.MySINnerFile.MyGroup = objMySiNnerGroup;
                            bUpload.Text         = "Remove from SINners";
                            bGroupSearch.Enabled = true;
                            lUploadStatus.Text   = "Online";
                            bUpload.Enabled      = true;
                        }
                        else if (eResponseStatus == HttpStatusCode.NotFound)
                        {
                            myUC.MyCE.MySINnerFile.MyGroup = null;
                            lUploadStatus.Text             = "Not Online";
                            bGroupSearch.Enabled           = false;
                            bGroupSearch.SetToolTip(
                                "SINner needs to be uploaded first, before he/she can join a group.");
                            bUpload.Enabled = true;
                            bUpload.Text    = "Upload";
                        }
                        else if (eResponseStatus == HttpStatusCode.NoContent)
                        {
                            myUC.MyCE.MySINnerFile.MyGroup = null;
                            lUploadStatus.Text             = "Status Code: " + eResponseStatus;
                            bGroupSearch.Enabled           = true;
                            bGroupSearch.SetToolTip(
                                "SINner does not belong to a group.");
                            bUpload.Text       = "Remove from SINners";
                            lUploadStatus.Text = "Online";
                            bUpload.Enabled    = true;
                        }
                        cbTagCustom.Enabled        = false;
                        TagValueCustomName.Enabled = false;
                    });
                    this.DoThreadSafe(UpdateTags);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                this.DoThreadSafe(() =>
                {
                    bUpload.Text = "Unknown Status";
                });
                return(false);
            }
            return(true);
        }
Example #26
0
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetSinnerAsAdmin()'
        public async Task <ActionResult <ResultGroupGetSearchGroups> > GetSinnerAsAdmin()
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetSinnerAsAdmin()'
        {
            SINSearchGroupResult ret = new SINSearchGroupResult();
            ResultAccountGetSinnersByAuthorization res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup sg   = new SINnerGroup();
            var         user = await _signInManager.UserManager.GetUserAsync(User);

            if (user == null)
            {
                var e = new AuthenticationException("User is not authenticated.");
                res = new ResultAccountGetSinnersByAuthorization(e)
                {
                    ErrorText = "Unauthorized"
                };
                return(BadRequest(res));
            }
            user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList();

            SINnerSearchGroup ssg = new SINnerSearchGroup(sg, user)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            try
            {
                var roles = await _userManager.GetRolesAsync(user);

                ret.Roles     = roles.ToList();
                ssg.Groupname = user.Email;
                ssg.Id        = Guid.Empty;
                //get all from visibility
                List <SINner> mySinners = await _context.SINners.Include(a => a.MyGroup)
                                          .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                          .OrderByDescending(a => a.UploadDateTime)
                                          .Take(200)
                                          .ToListAsync();

                foreach (var sin in mySinners)
                {
                    SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember(user, sin);
                    ssg.MyMembers.Add(ssgm);
                    if (sin.MyGroup != null)
                    {
                        SINnerSearchGroup ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == sin.MyGroup.Id);
                        if (ssgFromSIN == null)
                        {
                            ssgFromSIN = new SINnerSearchGroup(sin.MyGroup, user);
                            ssg.MySINSearchGroups.Add(ssgFromSIN);
                        }
                        //add all members of his group
                        var members = await sin.MyGroup.GetGroupMembers(_context, false);

                        foreach (var member in members)
                        {
                            member.MyGroup          = sin.MyGroup;
                            member.MyGroup.MyGroups = new List <SINnerGroup>();
                            SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember(user, member);
                            ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                        }
                        sin.MyGroup.PasswordHash = string.Empty;
                        sin.MyGroup.MyGroups     = new List <SINnerGroup>();
                    }
                }

                ret.SINGroups.Add(ssg);
                res = new ResultAccountGetSinnersByAuthorization(ret);
                return(Ok(res));
            }
            catch (Exception e)
            {
                try
                {
                    await _signInManager.UserManager.GetUserAsync(User);

                    //var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e);
                    et.Properties.Add("user", User.Identity.Name);
                    tc.TrackException(et);
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex.ToString());
                }
                res = new ResultAccountGetSinnersByAuthorization(e);
                return(BadRequest(res));
            }
        }
 /// <summary>
 /// Store the new group
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='mygroup'>
 /// </param>
 /// <param name='sinnerId'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task PostGroupAsync(this ISINnersClient operations, SINnerGroup mygroup = default(SINnerGroup), Guid?sinnerId = default(Guid?), CancellationToken cancellationToken = default(CancellationToken))
 {
     await operations.PostGroupWithHttpMessagesAsync(mygroup, sinnerId, null, cancellationToken).ConfigureAwait(false);
 }