コード例 #1
0
        public async Task <IHttpActionResult> PostUser(User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!db.Users.Any(u => u.Name == user.Name))
            {
                db.Users.Add(new Models.User()
                {
                    Name = user.Name, Id = Guid.NewGuid().ToString()
                });
            }

            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                if (UserExists(user.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            var returned = db.Users.FirstOrDefault(u => u.Name == user.Name);

            return(Ok(returned));
        }
コード例 #2
0
 [HttpGet] // made during testing
 public async Task deletePersonAll()
 {
     context.GroupMappers.RemoveRange(context.GroupMappers);
     context.Groups.RemoveRange(context.Groups);
     context.People.RemoveRange(context.People);
     await context.SaveChangesAsync();
 }
コード例 #3
0
        public async Task <IHttpActionResult> PostNotification(Notification notification)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (notification.NotificationType == NotificationType.Custom)
            {
                notification.Id = Guid.NewGuid().ToString();
                db.Notifications.Add(notification);
                await db.SaveChangesAsync();

                Notification.SendPushNotification(notification, Services);
            }
            else
            {
                var latestDolar           = db.CurrencyRates.OrderByDescending(x => x.LastUpdated).First(x => x.CurrencyId == 1);
                var automaticNotification = Notification.SendPushNotification(latestDolar, notification.NotificationType, Services);
                if (automaticNotification != null)
                {
                    db.AutomaticNotifications.Add(automaticNotification);
                    db.SaveChanges();
                }
            }

            return(Ok(notification));
        }
コード例 #4
0
        public async Task <IHttpActionResult> PutAgent(string id, Agent agent)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != agent.Id)
            {
                return(BadRequest());
            }

            db.Entry(agent).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AgentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #5
0
        public async Task addConnectForWholeGroup(string groupId, string personAdminId, string destinationLat, string destinationLong)
        {
            List <GroupMapper> gpmList = null;

            if (context.GroupMappers.FirstOrDefault(x => x.groupId == groupId) != null)
            {
                gpmList = context.GroupMappers.Where(x => x.groupId == groupId).ToList <GroupMapper>();
            }
            foreach (var gpm in gpmList)
            {
                Person temp = context.People.FirstOrDefault(x => x.Id == gpm.personId);
                if (temp != null && temp.isGloballyVisible && gpm.isPersonVisibleInGroup)
                {
                    if (gpm.personId == personAdminId)
                    {
                        await addConnect2(gpm.groupId, gpm.personId, true);

                        Group grp = context.Groups.FirstOrDefault(x => x.Id == groupId);
                        if (grp != null)
                        {
                            grp.destinationLatitude  = JsonConvert.DeserializeObject <double>(destinationLat);
                            grp.destinationLongitude = JsonConvert.DeserializeObject <double>(destinationLong);
                        }
                        await context.SaveChangesAsync();
                    }
                    else
                    {
                        await addConnect2(gpm.groupId, gpm.personId, false);
                    }
                }
            }
        }
コード例 #6
0
        private async Task <bool> updateLastSeenTime(string markId)
        {
            bool updateWasSuccessful = false;

            using (DbContextTransaction transaction = context.Database.BeginTransaction())
            {
                try
                {
                    UserMarkExperience userMarkExperience = await context.UserMarkExperiences.FindAsync(LoggedUserId, markId);

                    validateOwner(userMarkExperience);

                    userMarkExperience.LastSeen = DateTime.Now;

                    await context.SaveChangesAsync();

                    transaction.Commit();
                    updateWasSuccessful = true;
                }

                catch (Exception ex)
                {
                    LogTools.LogException(ex);
                    transaction.Rollback();
                    throw ex;
                }
            }

            return(updateWasSuccessful);
        }
コード例 #7
0
        public async Task <IHttpActionResult> PostUser(User item)
        {
            context.Users.Add(new User(item.Email, item.Password));
            await context.SaveChangesAsync();

            return(CreatedAtRoute("Tables", new { id = item.Id }, item));
        }
コード例 #8
0
        // PATCH tables/Player/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public async Task <Player> PatchPlayer(string id, Delta <Player> patch)
        {
            var currentUser = User as ServiceUser;
            var item        = patch.GetEntity();

            var result = await UpdateAsync(id, patch);

            var players = context.Players.OrderByDescending(player => player.Clicks).ToList();

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]);
                player.Entity.Rank      = i + 1;
                player.Entity.OldClicks = player.Entity.Clicks;
            }

            await context.SaveChangesAsync();

            var message = new WindowsPushMessage();

            message.Headers.Add("X-WNS-Type", "wns/raw");
            message.XmlPayload = JsonConvert.SerializeObject(context.Players.ToList());

            await Services.Push.SendAsync(message);

            return(result);
        }
コード例 #9
0
        public async Task <CustomResponse> PostAsync([FromBody] TodoItem item)
        {
            using (DbContextTransaction transaction = context.Database.BeginTransaction())
            {
                try
                {
                    item.Id        = Guid.NewGuid().ToString();
                    item.UpdatedAt = DateTimeOffset.Now;
                    item.CreatedAt = DateTimeOffset.Now;
                    context.TodoItems.Add(item);
                    await context.SaveChangesAsync();

                    transaction.Commit();

                    await PushToSyncAsync("ToDoItem", item.Id);
                } catch (Exception ex)
                {
                    transaction.Rollback();
                }

                return(new CustomResponse {
                    Status = 200
                });
            }
        }
コード例 #10
0
        public async Task <AlbumCustomResponse> PostAsync([FromBody] Album newAlbum)
        {
            // Use a transaction to update the database
            using (DbContextTransaction transaction = context.Database.BeginTransaction())
            {
                try
                {
                    context.Albums.Add(newAlbum);
                    await context.SaveChangesAsync();

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }

            // Now generate whatever output we want.
            AlbumCustomResponse response = new AlbumCustomResponse
            {
                Status = 200
            };

            return(response);
        }
コード例 #11
0
        /// <summary>
        /// Sets the conversation identifier for the specified user.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="conversationId">The conversation identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task SetConversationIdAsync(string userId, string conversationId, CancellationToken cancellationToken)
        {
            using (var context = new MobileServiceContext())
            {
                var link = await context.UserConversations
                           .FirstOrDefaultAsync(l => l.UserId == userId, cancellationToken)
                           .ConfigureAwait(false);

                if (link == null)
                {
                    link = new UserConversation
                    {
                        Id             = Guid.NewGuid().ToString(),
                        UserId         = userId,
                        ConversationId = conversationId
                    };
                    context.UserConversations.Add(link);
                }
                else if (link.ConversationId == conversationId)
                {
                    return;
                }
                else
                {
                    link.ConversationId = conversationId;
                }

                await context
                .SaveChangesAsync(cancellationToken)
                .ConfigureAwait(false);
            }
        }
コード例 #12
0
        public async static Task <bool> InsertUserMarkExperience(this MobileServiceContext context, string userId, string markId)
        {
            bool updateWasSuccessful = false;

            using (DbContextTransaction transaction = context.Database.BeginTransaction())
            {
                try
                {
                    UserMarkExperience userMarkExperience = context.UserMarkExperiences.Create();
                    userMarkExperience.UserId       = userId;
                    userMarkExperience.MarkId       = markId;
                    userMarkExperience.HasUserRated = false;
                    userMarkExperience.LastSeen     = DateTime.Now;
                    context.UserMarkExperiences.Add(userMarkExperience);

                    await context.SaveChangesAsync();

                    transaction.Commit();
                    updateWasSuccessful = true;
                }

                catch (Exception ex)
                {
                    LogTools.LogException(ex);
                    transaction.Rollback();
                    throw ex;
                }
            }

            return(updateWasSuccessful);
        }
コード例 #13
0
        // POST tables/Travel
        public async Task <IHttpActionResult> PostTravel(Travel item)
        {
            User user = context.Users.Where(u => u.Id == item.UserId).FirstOrDefault();

            if (user != null)
            {
                user.AddTravel(item.Name, item.Date);
                await context.SaveChangesAsync();
            }
            return(CreatedAtRoute("Tables", new { id = item.Id }, item));
        }
コード例 #14
0
        // POST tables/Item
        public async Task <IHttpActionResult> PostItem(Item item)
        {
            Categorie categorie = context.Categories.Where(c => c.Id == item.CategorieId).FirstOrDefault();

            if (categorie != null)
            {
                categorie.AddItem(item.Name, item.AmountNeeded);
                await context.SaveChangesAsync();
            }
            return(CreatedAtRoute("Tables", new { id = item.Id }, item));
        }
コード例 #15
0
        // POST tables/Categorie
        public async Task <IHttpActionResult> PostCategorie(Categorie item)
        {
            Travel travel = context.Travels.Where(t => t.Id == item.TravelId).FirstOrDefault();

            if (travel != null)
            {
                travel.AddCategorie(item.Name);
                await context.SaveChangesAsync();
            }
            return(CreatedAtRoute("Tables", new { id = item.Id }, item));
        }
コード例 #16
0
        // GET api/DataRefresh
        public async Task <bool> Get()
        {
            // get all the orders
            var orders = _MobileServiceContext.Orders.ToList();

            if (orders.Count < 1)
            {
                throw new Exception("There doesn't seem to be any orders currently in the database.");
            }

            var lastUpdated = orders.First(x => x.UpdatedAt != null).UpdatedAt;

            if (lastUpdated != null)
            {
                var last = lastUpdated.Value.ToUniversalTime();

                DateTime now = DateTime.UtcNow;

                var today = DateTime.SpecifyKind(new DateTime(now.Year, now.Month, now.Day, 0, 0, 0), DateTimeKind.Utc);

                var lastUpdatedDay = DateTime.SpecifyKind(new DateTime(last.Year, last.Month, last.Day, 0, 0, 0), DateTimeKind.Utc);

                var daysElapsed = (int)(today - lastUpdatedDay).TotalDays;

                var weeksElapsed = (daysElapsed / 7);

                var daysToAdjust = weeksElapsed * 7;

                if (weeksElapsed > 0)
                {
                    foreach (var o in orders)
                    {
                        o.OrderDate  = o.OrderDate.AddDays(daysToAdjust);
                        o.DueDate    = o.DueDate.AddDays(daysToAdjust);
                        o.ClosedDate = o.ClosedDate?.AddDays(daysToAdjust);
                        o.UpdatedAt  = o.UpdatedAt?.AddDays(daysToAdjust);

                        _MobileServiceContext.Entry(o).State = EntityState.Modified;

                        await _MobileServiceContext.SaveChangesAsync();
                    }
                }
            }
            else
            {
                throw new  Exception("No orders have an UpdatedAt value. This should not happen.");
            }

            // all went well, so return a success result
            return(await Task.FromResult(true));
        }
コード例 #17
0
        public async Task <IHttpActionResult> PostAsync(Event item)
        {
            try
            {
                context.Events.Add(item);
                await context.SaveChangesAsync();

                return(StatusCode(HttpStatusCode.Created));
            }
            catch (System.Exception)
            {
                return(StatusCode(HttpStatusCode.BadRequest));
            }
        }
コード例 #18
0
ファイル: RankJob.cs プロジェクト: robertiagar/clicker
        public async override Task ExecuteAsync()
        {
            var players = context.Players.OrderByDescending(player => player.Clicks).ToList();

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]);
                player.Entity.Rank      = i + 1;
                player.Entity.OldClicks = player.Entity.Clicks;
            }

            await context.SaveChangesAsync();

            players = context.Players.OrderByDescending(player => player.Clicks).ToList();
            Player winner = null;

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]).Entity;
                if (i == 0)
                {
                    winner = player;
                    WindowsPushMessage message = new WindowsPushMessage();

                    // Define the XML paylod for a WNS native toast notification
                    // that contains the text of the inserted item.
                    message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                         @"<toast><visual><binding template=""ToastText01"">" +
                                         @"<text id=""1"">" + "Congratulations " + player.Name + "!! You are todays first player with " + player.Clicks + " clicks. " + @"</text>" +
                                         @"</binding></visual></toast>";

                    // Use a tag to only send the notification to the logged-in user.
                    var result = await Services.Push.SendAsync(message, player.UserId);
                }
                else
                {
                    WindowsPushMessage message = new WindowsPushMessage();

                    // Define the XML paylod for a WNS native toast notification
                    // that contains the text of the inserted item.
                    message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                         @"<toast><visual><binding template=""ToastText01"">" +
                                         @"<text id=""1"">" + "Sorry " + player.Name + ". You lost to " + winner.Name + ". Better luck next time." + @"</text>" +
                                         @"</binding></visual></toast>";

                    // Use a tag to only send the notification to the logged-in user.
                    var result = await Services.Push.SendAsync(message, player.UserId);
                }
            }
        }
コード例 #19
0
        public async Task <Group> createGroup(string groupStr, string personsListStr)// Modified during Testing
        {
            Group         group   = JsonConvert.DeserializeObject <Group>(groupStr);
            List <Person> persons = JsonConvert.DeserializeObject <List <Person> >(personsListStr);

            group.Id = Guid.NewGuid().ToString();

            foreach (Person p in persons)
            {
                if (context.People.FirstOrDefault(x => x.Id == p.Id) == null)
                {
                    return(group);
                }
            }
            if (await context.Groups.FindAsync(group.Id) == null)
            {
                await PostGroup(group);

                foreach (Person tempPerson in persons)
                {
                    Person person = await context.People.FindAsync(tempPerson.Id);

                    if (person != null)
                    {
                        context.GroupMappers.Add(new GroupMapper
                        {
                            Id       = Guid.NewGuid().ToString(),
                            groupId  = group.Id,
                            personId = person.Id,
                            isPersonVisibleInGroup = person.isGloballyVisible
                        });
                    }
                }
                await context.SaveChangesAsync();
            }
            return(group);
        }
コード例 #20
0
 public async Task <ActionResult> Create([Bind(Include = "Text")] TodoItem item)
 {
     try
     {
         if (ModelState.IsValid)
         {
             item.Id = Guid.NewGuid().ToString("N");
             context.TodoItems.Add(item);
             await context.SaveChangesAsync();
         }
     }
     catch (DataException)
     {
         ModelState.AddModelError("", "Unable to save changes.");
     }
     return(RedirectToAction("Index"));
 }
コード例 #21
0
        private async Task <bool> updateMarkRating(string markId, float?rating)
        {
            bool updateWasSuccessful = false;

            using (DbContextTransaction transaction = context.Database.BeginTransaction())
            {
                try
                {
                    UserMarkExperience userMarkExperience = await context.UserMarkExperiences.FindAsync(LoggedUserId, markId);

                    validateOwner(userMarkExperience);

                    userMarkExperience.Mark.RatingsSum -= userMarkExperience.UserRating;
                    userMarkExperience.Mark.RatingsSum += rating.Value;
                    userMarkExperience.UserRating       = rating.Value;
                    userMarkExperience.LastSeen         = DateTime.Now;

                    if (!userMarkExperience.HasUserRated)
                    {
                        userMarkExperience.Mark.RatingsCount++;
                        userMarkExperience.HasUserRated = true;
                    }

                    userMarkExperience.Mark.UpdateRating();
                    await context.SaveChangesAsync();

                    transaction.Commit();
                    updateWasSuccessful = true;
                }

                catch (Exception ex)
                {
                    LogTools.LogException(ex);
                    transaction.Rollback();
                    throw ex;
                }
            }

            return(updateWasSuccessful);
        }
コード例 #22
0
        public async override Task ExecuteAsync()
        {
            try
            {
                var orderList = _MobileServiceContext.Orders as IList <Order> ?? _MobileServiceContext.Orders.ToList();

                var oldestUpdatedOrder = orderList.OrderBy(o => o.UpdatedAt).FirstOrDefault();

                if (oldestUpdatedOrder?.UpdatedAt != null)
                {
                    DateTime lastUpdatedDate = oldestUpdatedOrder.UpdatedAt.Value.UtcDateTime;

                    int daysSinceUpdate = (DateTime.UtcNow - lastUpdatedDate).Days;

                    foreach (var o in orderList)
                    {
                        o.OrderDate  = o.OrderDate.AddDays(daysSinceUpdate);
                        o.DueDate    = o.DueDate.AddDays(daysSinceUpdate);
                        o.ClosedDate = o.ClosedDate?.AddDays(daysSinceUpdate);

                        _MobileServiceContext.Entry(o).State = EntityState.Modified;

                        await _MobileServiceContext.SaveChangesAsync();
                    }

                    Services.Log.Info($"Orders successfully refreshed. Total orders: {orderList.Count}");
                    await Task.FromResult(true);
                }
                else
                {
                    Services.Log.Warn("None of the orders seem to have an UpdatedAt value. This may mean there's no orders at all in the database.");
                    await Task.FromResult(false);
                }
            }
            catch (Exception ex)
            {
                Services.Log.Error($"Orders failed to refresh refresh: {ex.Message}");
                throw;
            }
        }
コード例 #23
0
        async Task <Challenge> AcceptChallenge(Challenge challenge)
        {
            if (challenge == null)
            {
                throw "This challenge no longer exists".ToException(Request);
            }

            _authController.EnsureHasPermission(challenge.ChallengeeAthlete, Request);
            challenge.DateAccepted = DateTime.UtcNow;
            await _context.SaveChangesAsync();

            var league     = _context.Leagues.SingleOrDefault(l => l.Id == challenge.LeagueId);
            var challengee = _context.Athletes.SingleOrDefault(a => a.Id == challenge.ChallengeeAthleteId);
            var message    = "{0}: Your challenge with {1} has been accepted!".Fmt(league.Name, challengee.Alias);
            var payload    = new NotificationPayload
            {
                Action  = PushActions.ChallengeAccepted,
                Payload = { { "challengeId", challenge.Id }, { "leagueId", challenge.LeagueId } }
            };

            await _notificationController.NotifyByTag(message, challenge.ChallengerAthleteId, payload);

            return(challenge);
        }
コード例 #24
0
        private async Task <IHttpActionResult> ProcessScanBarcode(string id, decimal latitude, decimal longitude, string retailerId)
        {
            long ean_upc;

            long.TryParse(id, out ean_upc);
            if (ean_upc == 0)
            {
                ean_upc = 999999999;
            }

            var product = await db.Products.FirstOrDefaultAsync(i => i.EAN_UPC == ean_upc);

            var retailer = await db.Retailers.FirstOrDefaultAsync(r => r.Id == retailerId);

            var countryCode        = Common.GetCountryCode(latitude, longitude);
            var notifcationMessage = string.Empty;
            var isValidProduct     = true;

            if (product == null)
            {
                var failScanResult = new ScanResult
                {
                    Id               = Guid.NewGuid().ToString(),
                    BarcodeValue     = ean_upc,
                    isProcessed      = true,
                    ScanDate         = DateTime.Now,
                    ScanLocationLat  = latitude,
                    ScanLocationLong = longitude,
                    isAgentNotified  = true,
                    isValid          = false,
                    CountryCode      = countryCode
                };

                if (retailer != null)
                {
                    var response = (ean_upc == 999999999) ? "Invalid Product Code - Non Numeric" : "Invalid Product Code";
                    failScanResult.ValidationResponse = response;
                    failScanResult.RetailerID         = retailer.Id;
                    failScanResult.AgentID            = retailer.AgentID;
                    db.ScanResults.Add(failScanResult);
                    await db.SaveChangesAsync();

                    notifcationMessage = "Invalid Product: " + id + " scanned by retailer: " + retailer.Name;
                    isValidProduct     = false;
                }

                await SendNotifcation(retailer.AgentID, notifcationMessage, isValidProduct);

                return(Content(HttpStatusCode.OK, "Product Not Found"));
            }

            //Validate the product against the country code.
            //if not valid insert record in db
            // + send notification to agent

            //Insert new scan result information in the table
            ScanResult scanResult = new ScanResult
            {
                Id           = Guid.NewGuid().ToString(),
                ProductID    = product.Id,
                BarcodeValue = ean_upc,
                RetailerID   = retailer.Id,
                AgentID      = retailer.AgentID,

                ScanDate         = DateTime.Now,
                ScanLocationLat  = latitude,
                ScanLocationLong = longitude
            };

            scanResult.CountryCode = countryCode;

            if (countryCode.ToLower() == product.CountryCode.ToLower())
            {
                //valid product
                scanResult.isAgentNotified    = false;
                scanResult.isValid            = true;
                scanResult.ValidationResponse = "Valid Product code";
                scanResult.isProcessed        = true;
                isValidProduct = true;

                db.ScanResults.Add(scanResult);
                await db.SaveChangesAsync();

                return(Ok(product));
            }
            else
            {
                //invalid product
                scanResult.isAgentNotified    = true;
                scanResult.isValid            = false;
                scanResult.isProcessed        = true;
                scanResult.ValidationResponse = "Invalid Country Code. - Product Location Code: " + product.CountryCode + ", Scan Location :" + countryCode;
                isValidProduct     = false;
                notifcationMessage = "Invalid Country code scanned by retailer " + retailer.Name + "  – Product Location Code: " + product.CountryCode + ", Scan Location: + " + countryCode + " Product Desc: " + product.description + " , Barcode: " + id;

                await SendNotifcation(retailer.AgentID, notifcationMessage, isValidProduct);

                db.ScanResults.Add(scanResult);
                await db.SaveChangesAsync();

                return(Content(HttpStatusCode.OK, "Product Not Found"));
            }
        }
コード例 #25
0
        // POST: api/User
        public async Task <IHttpActionResult> Post(List <BatchScan> scanResults)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                int    batchId    = 0;
                string retailerId = null;

                foreach (var scanResult in scanResults)
                {
                    long ean_upc;
                    long.TryParse(scanResult.BarcodeValue, out ean_upc);
                    if (ean_upc == 0)
                    {
                        ean_upc = 999999999;
                    }

                    //Create new scan object to add in table

                    var scanObject = new ScanResult()
                    {
                        Id                 = Guid.NewGuid().ToString(),
                        BarcodeValue       = ean_upc,
                        AgentID            = scanResult.AgentID,
                        RetailerID         = scanResult.RetailerID,
                        ValidationResponse = scanResult.ValidationResponse,
                        isValid            = false,
                        isAgentNotified    = false,
                        ScanDate           = scanResult.ScanDate,
                        ScanLocationLat    = scanResult.ScanLocationLat,
                        ScanLocationLong   = scanResult.ScanLocationLong,
                        BatchID            = scanResult.BatchID,
                        isProcessed        = false,
                    };

                    db.ScanResults.Add(scanObject);
                    if (batchId == 0)
                    {
                        batchId = Convert.ToInt32(scanResult.BatchID);
                    }
                    if (retailerId == null)
                    {
                        retailerId = scanResult.RetailerID;
                    }
                }

                try
                {
                    await db.SaveChangesAsync();

                    //Insert Message in Queue
                    StorageCredentials  credentails = new StorageCredentials(accountName, accountkey);
                    CloudStorageAccount account     = new CloudStorageAccount(credentails, true);
                    CloudQueueClient    queueCLient = account.CreateCloudQueueClient();
                    CloudQueue          queue       = queueCLient.GetQueueReference("proscanqueue");
                    queue.CreateIfNotExists();

                    CloudQueueMessage message = new CloudQueueMessage(batchId + "&" + retailerId);
                    queue.AddMessage(message);
                }
                catch (DbUpdateException dbex)
                {
                    return(Ok(dbex.Message));
                }

                return(Ok("Scan table successfully updated"));
            }
            catch (Exception ex)
            {
                return(Ok(ex.Message));
            }
        }
コード例 #26
0
        // POST: tables/Contact
        /// <summary>
        /// Creates new user row in Contact, ContactInfo, and Address Tables
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> PostAsync(User user)
        {
            //if (!Request.Content.IsMimeMultipartContent())
            //{
            //    return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The request doesn't contain valid content!");
            //}
            try
            {
                if (user != null)
                {
                    var provider = new MultipartMemoryStreamProvider();
                    await Request.Content.ReadAsMultipartAsync(provider);

                    foreach (var file in provider.Contents)
                    {
                        var photoByteArray = await file.ReadAsByteArrayAsync();

                        user.contact.ProfileImageId = photoByteArray;

                        var addressId = Guid.NewGuid().ToString();
                        var contactId = Guid.NewGuid().ToString();

                        //setup PK/FK relationship
                        user.address.Id        = addressId;
                        user.contact.Id        = contactId;
                        user.contact.AddressId = addressId;
                        user.info.ContactId    = contactId;

                        //add payload to DB
                        context.Addresses.Add(user.address);
                        context.Contacts.Add(user.contact);
                        context.ContactInfo.Add(user.info);

                        //async save changes to DB
                        await context.SaveChangesAsync();

                        var response = Request.CreateResponse(HttpStatusCode.OK);
                        response.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain");
                        response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"text/html");
                        return(response);
                    }
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No contact to add!"));
                }
            }
            catch (Exception e)
            {
                //still add contact row to DB even if issue with photo upload request
                try
                {
                    context.Contacts.Add(user.contact);
                    await context.SaveChangesAsync();
                }
                catch (Exception err)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, err.Message));
                }
            }
            return
                (Request.CreateResponse(HttpStatusCode.OK, user));
        }
コード例 #27
0
        public async Task <string> PostAddUser(MessageAttachments model)
        {
            int counter      = 0;
            var personGroups = await FaceAnalyzer.faceServiceClient.ListPersonGroupsAsync();

            var xamGroup = personGroups.Where(x => x.Name == "Xamarin").FirstOrDefault();

            foreach (var user in model.Users)
            {
                CreatePersonResult person;
                var bytes = user.GetByteArray();

                var detectedFaceResults = await FaceAnalyzer.DetectFaceAsync(bytes);

                if (detectedFaceResults.Success)
                {
                    var isUserInDatabase = context.IdentifiedUsers.Where(usr => usr.Id == detectedFaceResults.FaceId.ToString()).ToList().FirstOrDefault();

                    if (isUserInDatabase == null)
                    {
                        context.IdentifiedUsers.Add(new IdentifiedUser {
                            Id = detectedFaceResults.FaceId.ToString(), Email = user.UserEmail
                        });
                    }
                    else
                    {
                        return($"User {isUserInDatabase.Email} is already in the database");
                    }
                }
                else
                {
                    //Check if CognitiveServices XamarinGroup doesn't know of our user
                    if (detectedFaceResults.Error == "Unable to Identify User")
                    {
                        using (Stream imageFileStream = new MemoryStream(bytes))
                        {
                            person = await FaceAnalyzer.faceServiceClient.CreatePersonAsync(xamGroup.PersonGroupId, user.UserEmail);

                            await FaceAnalyzer.faceServiceClient.AddPersonFaceAsync(xamGroup.PersonGroupId, person.PersonId, imageFileStream);

                            await FaceAnalyzer.faceServiceClient.TrainPersonGroupAsync(xamGroup.PersonGroupId);

                            context.IdentifiedUsers.Add(new IdentifiedUser {
                                Id = person.PersonId.ToString(), Email = user.UserEmail
                            });
                        }
                    }
                    //If it doesn't know about our user, then there was some error i.e. multiple faces, glasses
                    else
                    {
                        return(detectedFaceResults.Error);
                    }
                }

                counter++;
            }

            await context.SaveChangesAsync();

            return($"Saved {counter} users out of {model.Users.Count} total users");
        }