Пример #1
0
 /// <summary>Tracks any exception.</summary>
 public static void TrackException(Exception ex)
 {
     #if !DEBUG
     var telex = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(ex);
     telex.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.UserCode;
     _telemetry.TrackException(telex);
     #endif
 }
Пример #2
0
        public async Task <IActionResult> PutSIN([FromRoute] Guid id, IFormFile uploadedFile)
        {
            ApplicationUser user     = null;
            SINner          dbsinner = null;

            try
            {
                var sin = await _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights).FirstOrDefaultAsync(a => a.Id == id);

                if (sin == null)
                {
                    return(NotFound("Sinner with Id " + id + " not found!"));
                }
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                dbsinner = await CheckIfUpdateSINnerFile(id, user);

                if (dbsinner == null)
                {
                    return(Conflict("CheckIfUpdateSINnerFile"));
                }
                sin.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                if (user == null)
                {
                    throw new NoUserRightException("User not found!");
                }

                sin.DownloadUrl = Startup.GDrive.StoreXmlInCloud(sin, uploadedFile);
                _context.Entry(dbsinner).CurrentValues.SetValues(sin);
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.EventTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry("PutStoreXmlInCloud");
                    telemetry.Properties.Add("User", user.Email);
                    telemetry.Properties.Add("SINnerId", sin.Id.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackEvent(telemetry);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                }
                try
                {
                    int x = await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException e)
                {
                    return(Conflict(e));
                }

                return(Ok(sin.DownloadUrl));
            }
            catch (NoUserRightException e)
            {
                return(BadRequest(e));
            }
            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", dbsinner?.Id?.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in PutSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Пример #3
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.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));
            }
        }
Пример #4
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(new BadRequestObjectResult(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.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.NewGuid();
                    }
                    var olduserrights = await(from a in _context.UserRights where a.SINnerId == sinner.Id select a).ToListAsync();
                    _context.UserRights.RemoveRange(olduserrights);
                    foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights)
                    {
                        ur.Id       = Guid.NewGuid();
                        ur.SINnerId = sinner.Id;
                        _context.UserRights.Add(ur);
                    }

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

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

                    if (dbsinner != null)
                    {
                        _context.SINners.Attach(dbsinner);
                        if (String.IsNullOrEmpty(sinner.GoogleDriveFileId))
                        {
                            sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                        }
                        if (String.IsNullOrEmpty(sinner.DownloadUrl))
                        {
                            sinner.DownloadUrl = dbsinner.DownloadUrl;
                        }
                        //_context.Entry(dbsinner.SINnerMetaData.Visibility).State = EntityState.Modified;
                        _context.Entry(dbsinner.SINnerMetaData.Visibility).CurrentValues.SetValues(sinner.SINnerMetaData.Visibility);

                        //_context.Tags.RemoveRange(dbsinner.AllTags);
                        _context.Entry(dbsinner).State = EntityState.Modified;
                        _context.Entry(dbsinner).CurrentValues.SetValues(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;
                        _context.SINners.Add(sinner);
                    }
                }
                try
                {
                    await _context.SaveChangesAsync();
                }

                catch (DbUpdateConcurrencyException ex)
                {
                    foreach (var entry in ex.Entries)
                    {
                        if (entry.Entity is SINner)
                        {
                            DbUpdateConcurrencyExceptionHandler(entry);
                        }
                        else if (entry.Entity is Tag)
                        {
                            DbUpdateConcurrencyExceptionHandler(entry);
                        }
                        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());
                        telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count);
                        tc.TrackException(telemetry);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.ToString());
                    }
                    HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                    var          msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict)
                    {
                        ReasonPhrase = hue.Message
                    };
                    return(Conflict(msg));
                }
                List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList();
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostSINnerFile", myids));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostSINnerFile", 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());
                    telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count);
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
 /// <summary>
 /// Track a fatal exception (app crash)
 /// </summary>
 /// <param name="ex"></param>
 public void TrackFatalException(Exception ex)
 {
     var exceptionTelemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(new Exception());
     exceptionTelemetry.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.Unhandled;
     _telemetryClient.TrackException(exceptionTelemetry);
 }
Пример #6
0
        private async Task <IActionResult> GetSearchGroupsInternal(string Groupname, string UsernameOrEmail, string sINnerName, string language)
        {
            ApplicationUser user = 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)));
                }

                SINSearchGroupResult result = new SINSearchGroupResult();
                var groupfoundseq           = await(from a in _context.SINnerGroups
                                                    .Include(a => a.MyParentGroup)
                                                    .Include(a => a.MySettings)
                                                    .Include(a => a.MyGroups)
                                                    .ThenInclude(b => b.MyGroups)
                                                    where a.Groupname.ToLowerInvariant().Contains(Groupname.ToLowerInvariant()) &&
                                                    (a.Language == language || String.IsNullOrEmpty(language))
                                                    select a.Id).ToListAsync();
                if (!groupfoundseq.Any())
                {
                    return(NotFound(Groupname));
                }

                foreach (var groupid in groupfoundseq)
                {
                    var ssg = await GetSinSearchGroupResultById(groupid);

                    result.SINGroups.Add(ssg);
                }

                if (!String.IsNullOrEmpty(UsernameOrEmail))
                {
                    List <SINner>   byUser     = new List <SINner>();
                    ApplicationUser bynameuser = await _userManager.FindByNameAsync(UsernameOrEmail);

                    if (bynameuser != null)
                    {
                        var usersinners = await SINner.GetSINnersFromUser(bynameuser, _context, true);

                        byUser.AddRange(usersinners);
                    }

                    ApplicationUser byemailuser = await _userManager.FindByEmailAsync(UsernameOrEmail);

                    if ((byemailuser != null) && (byemailuser != bynameuser))
                    {
                        var usersinners = await SINner.GetSINnersFromUser(byemailuser, _context, true);

                        byUser.AddRange(usersinners);
                    }


                    foreach (var sin in byUser)
                    {
                        if (sin.MyGroup != null)
                        {
                            SINnerSearchGroup ssg = null;
                            var foundseq          = (from a in result.SINGroups
                                                     where a.Groupname?.ToLowerInvariant() == sin.MyGroup?.Groupname.ToLowerInvariant()
                                                     select a).ToList();
                            if (foundseq.Any())
                            {
                                ssg = foundseq.FirstOrDefault();
                            }

                            if (ssg == null)
                            {
                                ssg = new SINnerSearchGroup(sin.MyGroup);
                            }

                            SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                            {
                                MySINner = sin
                            };
                            if (byemailuser != null)
                            {
                                ssgm.Username = byemailuser?.UserName;
                            }
                            if (bynameuser != null)
                            {
                                ssgm.Username = bynameuser?.UserName;
                            }
                            ssg.MyMembers.Add(ssgm);
                        }
                    }
                }
                result.SINGroups = RemovePWHashRecursive(result.SINGroups);

                return(Ok(result));
            }
            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", Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in GetSearchGroups: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Пример #7
0
        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));
            }
        }
Пример #8
0
        internal static async Task <ActionResult <SINner> > PutSiNerInGroupInternal(Guid GroupId, Guid SinnerId, ApplicationUser user, ApplicationDbContext context, ILogger logger, string pwhash, IList <string> userroles)
        {
            try
            {
                if (GroupId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(GroupId), "GroupId may not be empty.");
                }

                if (SinnerId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(SinnerId), "SinnerId may not be empty.");
                }

                var groupset = await(from a in context.SINnerGroups
                                     .Include(a => a.MySettings)
                                     .Include(a => a.MyParentGroup)
                                     .Include(a => a.MyParentGroup.MyGroups)
                                     .Include(a => a.MyGroups)
                                     .ThenInclude(a => a.MyGroups)
                                     where a.Id == GroupId
                                     select a).ToListAsync();
                if (!groupset.Any())
                {
                    throw new ArgumentException("GroupId not found", nameof(GroupId));
                }

                var group = groupset.FirstOrDefault();

                if ((!String.IsNullOrEmpty(group.PasswordHash)) &&
                    (group.PasswordHash != pwhash))
                {
                    throw new NoUserRightException("PW is wrong!");
                }

                if (!String.IsNullOrEmpty(group.MyAdminIdentityRole))
                {
                    if (!userroles.Contains(group.MyAdminIdentityRole))
                    {
                        throw new NoUserRightException("User " + user.UserName + " has not the role " + group.MyAdminIdentityRole + ".");
                    }
                }

                var sinnerseq = await(from a in context.SINners
                                      .Include(a => a.MyGroup)
                                      .Include(a => a.MyGroup.MyParentGroup)
                                      .Include(a => a.MyGroup.MyParentGroup.MyGroups)
                                      .Include(a => a.MyGroup.MyGroups)
                                      .Include(a => a.SINnerMetaData)
                                      .Include(a => a.SINnerMetaData.Visibility)
                                      .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                      where a.Id == SinnerId
                                      select a).ToListAsync();
                SINner sin = null;
                if (!sinnerseq.Any())
                {
                    throw new ArgumentException("SinnerId not found", nameof(SinnerId));
                }
                else
                {
                    sin = sinnerseq.FirstOrDefault();
                    if (sin != null)
                    {
                        sin.MyGroup = group;
                    }
                }

                await context.SaveChangesAsync();

                sin.MyGroup.MyGroups = RemovePWHashRecursive(sin.MyGroup.MyGroups);
                return(sin);
            }
            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 PutSiNerInGroupInternal: " + e.Message, e);
                throw hue;
            }
        }
Пример #9
0
        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(new HubException("group == null.")));
                }
                if (String.IsNullOrEmpty(mygroup?.Groupname))
                {
                    return(BadRequest(new HubException("Groupname may not be empty.")));
                }

                if (SinnerId == Guid.Empty)
                {
                    return(BadRequest(new HubException("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(new HubException("Sinner  " + sinner.Id + ": Visibility contains no entries!")));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest(new HubException("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)));
                    }

                    List <SINnerGroup> groupfoundseq;
                    if (mygroup.Id == null || mygroup.Id == Guid.Empty)
                    {
                        groupfoundseq = await(from a in _context.SINnerGroups
                                              where a.Id == mygroup.Id
                                              select a).Take(1).ToListAsync();
                    }
                    else
                    {
                        groupfoundseq = await(from a in _context.SINnerGroups
                                              where a.Groupname == mygroup.Groupname &&
                                              a.Language == mygroup.Language
                                              select a).Take(1).ToListAsync();
                    }

                    SINnerGroup storegroup = null;
                    if ((groupfoundseq.Any()))
                    {
                        storegroup = groupfoundseq.FirstOrDefault();
                        user       = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                        var roles = await _userManager.GetRolesAsync(user);

                        if (!roles.Contains("GroupAdmin") || roles.Contains(storegroup?.MyAdminIdentityRole))
                        {
                            string msg = "A group with the name " + mygroup.Groupname + " already exists and user is not GroupAdmin or " + storegroup?.MyAdminIdentityRole + "!";
                            return(BadRequest(new HubException(msg)));
                        }
                    }

                    if (storegroup == null)
                    {
                        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;
                    }
                    else
                    {
                        returncode = HttpStatusCode.Accepted;
                        _context.Entry(storegroup).CurrentValues.SetValues(mygroup);
                    }

                    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.Accepted:
                    return(Accepted("PostGroup", mygroup));

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

                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));
            }
        }