示例#1
0
        public async Task <ActionResult> CreateAsync([Bind(Include = "Id,Name,Description,Completed")] Item item)
        {
            if (ModelState.IsValid)
            {
                await db.CreateItemAsync(item);

                return(RedirectToAction("Index"));
            }

            return(View(item));
        }
示例#2
0
        private async Task <bool> ToggleBotInChannel(IActivity activity, bool enabled, CancellationToken cancellationToken)
        {
            // First, check if the user sending the request is a Team Administrator.
            if (activity.From.Role == "bot")
            {
                return(false);
            }
            // THIS IS NOT THE BEST. I KNOW. I can't figure out how to get the list of admins for a channel.
            // (The Teams Bot documentation sucks for advanced users.)
            // Only let me and TechOps toggle the bot on and off.
            if (activity.From.Name.Contains("TechOps") || activity.From.Name.Contains("Aaron Rosenberger"))
            {
                string channelId = (string)activity.ChannelData["teamsChannelId"];
                string teamId;

                try
                {
                    teamId = (string)activity.ChannelData["teamsTeamId"];
                }
                catch (Exception)
                {
                    Trace.TraceError("Could not get team id.");
                    teamId = "defaultpartition";
                }

                _isEnabled = enabled;
                TeamsChannelMetadataModel metadata = await _db.GetItemAsync(channelId, teamId, cancellationToken);

                bool existsInDb = metadata != null;
                if (!existsInDb)
                {
                    metadata = new TeamsChannelMetadataModel
                    {
                        Id     = channelId,
                        TeamId = teamId
                    };
                }

                metadata.IsEnabled = _isEnabled;

                if (existsInDb)
                {
                    await _db.UpdateItemAsync(metadata.Id, metadata, metadata.TeamId, cancellationToken);
                }
                else
                {
                    await _db.CreateItemAsync(metadata, metadata.TeamId, cancellationToken);
                }

                return(true);
            }

            return(false);
        }
        public static async Task Run([BlobTrigger("mdap-batch-files/{name}")]
                                     Stream myBlob, string name, TraceWriter log)
        {
            var guid = Guid.NewGuid();

            try
            {
                Log($"Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes", guid, log);

                var startTime = DateTime.Now;

                var stopwatch = Stopwatch.StartNew();
                var rows      = DataParser.ParserFile(myBlob).ToArray();

                var elapsed = stopwatch.ElapsedMilliseconds;
                Log($"Finished parsing {rows.Count()} row(s) in {elapsed} ms", guid, log);

                var rowArray = rows.ToArray();

                List <Task> tasks = new List <Task>();
                foreach (var dataRow in rowArray)
                {
                    var task = Repository.CreateItemAsync(dataRow);
                    tasks.Add(task);
                }

                //rowArray.Select(Repository.CreateItemAsync).ToArray();

                Log("Finished calling inserts. Awaiting insertion tasks...", guid, log);

                await Task.WhenAll(tasks);

                stopwatch.Stop();

                Log($"Finished inserting {rows.Count()} row(s) in {stopwatch.ElapsedMilliseconds - elapsed} ms", guid, log);

                Log($"Total execution time {stopwatch.ElapsedMilliseconds} ms", guid, log);

                LogEvent("Parse and insert finished", startTime, DateTime.Now, name);

                //var response = await HttpClient.GetAsync($"https://fileingestionapi.azurewebsites.net/api/values/{name}");

                //var data = await response.Content.ReadAsStringAsync();

                //Log($"Response Data: {data}", guid, log);
            }
            catch (Exception ex)
            {
                log.Error($"{GetLogPrefix(guid)} Error occured during ingestion API invocation: {ex.Message}", ex);
                throw;
            }
        }
示例#4
0
        public async Task <IActionResult> Create(decimal longitude, decimal latitude, string address)
        {
            var trashCanId = Guid.NewGuid();
            var trashCan   = new TrashCan
            {
                id               = trashCanId.ToString(),
                Lat              = latitude,
                Long             = longitude,
                Address          = address,
                TrashCanStatuses = new List <TrashCanStatus>()
            };
            await _documentDbRepository.CreateItemAsync(trashCan);

            return(Ok(trashCanId));
        }
示例#5
0
        /// <summary>
        /// Responds to a karma request. NOTE: Assumes <paramref name="karmaString"/> is a valid karma string.
        /// </summary>
        /// <param name="karmaString">A valid karma string.</param>
        /// <param name="uniqueId">If the entity given karma was a Teams user, the unique ID for that user</param>
        /// <param name="givenName">If the entity given karma was a Teams user, the Given Name for that user</param>
        /// <returns>The bot's response including the karma amount difference.</returns>
        public async Task <string> GetReplyMessageForKarma(string karmaString, string uniqueId, string givenName, CancellationToken cancellationToken)
        {
            // We don't want commonly used karma strings to be interpreted as karma, like "C++"
            if (KarmaBlacklist.Contains(karmaString.Replace(" ", "")))
            {
                return(null);
            }

            // Break down the karma string into parts
            Match karmaMatch = GetKarmaRegexMatch(karmaString);

            // Get the entity that was given karma
            string entityForMessaging = karmaMatch.Groups[1].Value;
            string uniqueEntity       = givenName ?? Regex.Replace(entityForMessaging, "<.*?>|@|\"|[\\s]", "").ToLower();

            // Delta: the karma in pluses or minuses.
            string delta = karmaMatch.Groups[2].Value;
            // The amount of karma to give or take away.
            int deltaLength = delta.Length - 1;

            if (delta.Contains("-"))
            {
                deltaLength *= -1;
            }

            string id        = uniqueId ?? uniqueEntity;
            string partition = GetPartitionForKey(karmaString);

            KarmaModel karmaItem = await _db.GetItemAsync(id, partition, cancellationToken);

            bool existsInDb = karmaItem != null;

            if (!existsInDb)
            {
                karmaItem = new KarmaModel
                {
                    Id        = id,
                    Entity    = uniqueEntity,
                    Partition = partition,
                    Score     = 0
                };
            }

            string replyMessage = string.Empty;

            if (deltaLength > 5)
            {
                // BUZZKILL MODE
                deltaLength   = 5;
                replyMessage += $"{Strings.BuzzkillMode} {Strings.BuzzkillModeMessage} ... ";
            }
            else if (deltaLength < -5)
            {
                deltaLength   = -5;
                replyMessage += $"{Strings.BuzzkillMode} {Strings.BuzzkillModeMessage} ... ";
            }

            string messageFormat;

            if (deltaLength > 0)
            {
                messageFormat = ReplyMessageIncreasedFormat;
            }
            else
            {
                messageFormat = ReplyMessageDecreasedFormat;
            }

            karmaItem.Score += deltaLength;
            replyMessage    += string.Format(messageFormat, entityForMessaging, karmaItem.Score);

            if (existsInDb)
            {
                await _db.UpdateItemAsync(id, karmaItem, partition, cancellationToken);
            }
            else
            {
                await _db.CreateItemAsync(karmaItem, partition, cancellationToken);
            }

            return(replyMessage);
        }
示例#6
0
        /// <summary>
        /// Accepts a single xls file that contains operation configuration.
        /// </summary>
        /// <param name="fileMetadata">Metadata associated with the file upload request.</param>
        /// <param name="authenticationHeader">Authentication header for the request.</param>
        /// <param name="requestTenantId">The selected Tenant Id from the request import the Operation Config to</param>
        /// <returns>A task that returns the result of the upload option.</returns>
        public async Task <CommandResultNoDto> Upload(FileUploadMetadataDto fileMetadata, string authenticationHeader, Guid requestTenantId)
        {
            var errors      = new List <FFErrorCode>();
            var odataHelper = new Core.Api.OData.ODataHelper();

            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                errors.Add(GeneralErrorCodes.TokenInvalid("UserId"));
            }

            if (errors.Count > 0)
            {
                return(NoDtoHelpers.CreateCommandResult(errors));
            }

            // ReSharper disable once AssignNullToNotNullAttribute
            var userIdGuid = Guid.Parse(userId);

            // Check that the Tenant Id in the request body is in the user's claim tenants
            var tenants = odataHelper.GetTenantIds(Thread.CurrentPrincipal) as List <Guid>;

            // Check user has no tenants in their claim or if the tenantid in the request body is not in the claim
            if (tenants == null || tenants.All(x => x != requestTenantId))
            {
                errors.Add(ValidationErrorCode.ForeignKeyValueDoesNotExist("TenantId"));
            }

            if (errors.Count > 0)
            {
                return(NoDtoHelpers.CreateCommandResult(errors));
            }


            // Store file in blob storage.
            var result = await _blobManager.StoreAsync(_blobStorageConnectionString, _blobStorageContainerName, fileMetadata.SavedFileName);

            // Add file metadata to documentDB to later be retrieved by request
            // An Id property is created by documentDB and in populated in the result object
            await _documentDb.CreateItemAsync(
                new UploadTransaction
            {
                OriginalFileName      = fileMetadata.OriginalFileName,
                TenantIds             = tenants,
                UploadTransactionType = fileMetadata.TransactionType,
                UserId       = userIdGuid,
                UtcTimestamp = DateTime.UtcNow
            });

            var queueMessage = new BlobQueueMessage
            {
                BlobName            = result.BlobName,
                BlobSize            = result.BlobSize,
                BlobUrl             = result.BlobUrl,
                BlobTransactionType = fileMetadata.TransactionType,
                UserId = userIdGuid,
                AuthenticationHeader = authenticationHeader,
                // TenantId should be checked by the blob processor that it matches the tenant in the Operation Config to be processed
                TenantId = requestTenantId
            };

            var msg = JsonConvert.SerializeObject(queueMessage);
            // Add message to queue.
            await _queueManager.AddAsync(_blobStorageConnectionString, _queueStorageContainerName, msg);

            return(NoDtoHelpers.CreateCommandResult(errors));
        }