Exemplo n.º 1
0
        public static Caregiver GetCaregiverObject(string caregiverID)
        {
            MobileServiceContext db     = new MobileServiceContext();
            Caregiver            result = db.Caregivers.Where(p => p.Id == caregiverID).FirstOrDefault();

            return(result);
        }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new AuctionItemDomainManager(context, Request);
        }
Exemplo n.º 3
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <EventLocation>(context, Request, enableSoftDelete: true);
        }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <PictureQuestionAnswer>(context, Request);
        }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <AllEventsModelsUserModels>(context, Request);
        }
        private static string CheckAddEmailToDB(string email)
        {
            string retVal;
            var ctx = new MobileServiceContext();
            var user = ctx.Users.Where(x => x.Email == email);

            if (user.Count() == 0)
            {
                var u = ctx.Users.Add(new Common.Models.User() { Id = Guid.NewGuid().ToString(), Email = email, IsEnabled = true });
                try
                {
                    ctx.SaveChanges();
                }
                catch (System.Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    //
                }

                retVal = u.Id;
            }
            else
            {
                var u = user.First();
                retVal = u.Id;
            }

            return retVal;
        }
Exemplo n.º 7
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new GenericDomainManager <CountryDto, Country>(context, Request, Services);
        }
Exemplo n.º 8
0
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <param name="controllerContext">
        /// The controller context.
        /// </param>
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            var context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <SpecialOffersSchema>(context, Request, Services);
        }
Exemplo n.º 9
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <AdviserOrganization>(context, Request);
        }
Exemplo n.º 10
0
 protected override void Initialize(HttpControllerContext controllerContext)
 {
     base.Initialize(controllerContext);
     context       = new MobileServiceContext();
     DomainManager = new SimpleMappedEntityDomainManager <AdminDTO, Admin>
                         (context, Request, Services, admin => admin.Id);
 }
Exemplo n.º 11
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            var context = new MobileServiceContext();

            this.DomainManager = new EntityDomainManager <User>(context, Request);
        }
Exemplo n.º 12
0
        private void SaveParameter(string name, int value)
        {
            using (var contextService = new MobileServiceContext())
            {
                Parameters paramChange = contextService.Parameters.FirstOrDefault(p => p.Name == name);
                if (paramChange != null)
                {
                    paramChange.Value = value;
                    contextService.Entry(paramChange).State = EntityState.Modified;
                }
                else
                {
                    contextService.Parameters.Add(new Parameters()
                    {
                        Name  = name,
                        Id    = Guid.NewGuid().ToString(),
                        Value = value
                    });
                }

                try
                {
                    contextService.SaveChanges();
                }
                catch (DbUpdateConcurrencyException e)
                {
                    Debug.WriteLine(String.Format(e.Message + "\n" + e.Entries.Single().ToString()));
                }
            }
        }
Exemplo n.º 13
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <TodoItem>(context, Request);
        }
Exemplo n.º 14
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <Event>(context, Request);
            _geo          = new GeodanHelperService();
        }
Exemplo n.º 15
0
        // GET tables/Location/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public Location[] GetKnownLocationsforPatientID(string currentPatientID)
        {
            MobileServiceContext db = new MobileServiceContext();

            Location[] knownLocations = db.Locations.Where(p => p.PatientID == currentPatientID).ToArray();

            return(knownLocations);
        }
Exemplo n.º 16
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            DomainManager = new EntityDomainManager <SharingSpace>(context, Request, enableSoftDelete: true);
            UserId        = Settings.GetUserId(User);
        }
Exemplo n.º 17
0
        // GET latest sample for a specific patientID
        public Sample GetLatestSampleForPatient(string patientID)
        {
            MobileServiceContext db      = new MobileServiceContext();
            Sample latestSamplForPatient = db.Samples.OrderByDescending(p => p.CreatedAt)
                                           .Where(p => p.PatientID == patientID).FirstOrDefault();

            return(latestSamplForPatient);
        }
Exemplo n.º 18
0
 public InspectorController(EmailService emailService, MobileServiceContext context,
                            GeodanHelperService geodanHelper, AuthManager authManager)
 {
     _emailService = emailService;
     _context      = context;
     _geodanHelper = geodanHelper;
     _authManager  = authManager;
 }
 protected override void Initialize(HttpControllerContext controllerContext)
 {
     base.Initialize(controllerContext);
     _context               = new MobileServiceContext();
     _salesforceService     = new SalesforceService();
     _domainEmployeeManager = new EntityDomainManager <Employee>(_context, Request, Services);
     DomainManager          = new EntityDomainManager <Ride>(_context, Request, Services);
 }
Exemplo n.º 20
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();
            var softDeleteEnabled        = Convert.ToBoolean(ConfigurationManager.AppSettings["enableSoftDelete"]);

            DomainManager = new EntityDomainManager <Image>(context, Request, enableSoftDelete: softDeleteEnabled);
        }
Exemplo n.º 21
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();

            Request.Headers.Add("ZUMO-API-VERSION", "2.0.0");
            DomainManager = new EntityDomainManager <TodoItem>(context, Request);
        }
Exemplo n.º 22
0
        // POST: api/Like
        public async Task<bool> Post([FromBody]Dictionary<string,string> image)
        {
            var logic = new ImageBusinessLogic();

            var img = logic.GetImage(image["imageId"]);
            if (null != img)
            {
                var ctx = new MobileServiceContext();
                var registrations = ctx.DeviceRegistrations.Where(x => x.UserId == img.UserId);

                //Send x-plat template message to all installations in tags list
                //List<string> tags = new List<string>();
                //foreach (var registration in registrations)
                //    tags.Add(string.Format("$InstallationId:{{{0}}}", registration.InstallationId));

                //if (tags.Count > 0)
                //{
                //    var message = new Dictionary<string, string>()
                //    {
                //        { "message", string.Format("{0} has liked your image", img.User.Email)}
                //    };
                //    var res = await Notifier.Instance.SendTemplateNotification(message, tags);

                //    return res;
                //}
                //else
                //    return true;

                //Send plat-specific message to all installation one by one
                string message = string.Format("{0} has liked your image", img.User.Email);
                foreach (var registration in registrations)
                {
                    var tags = new string[1] { string.Format("$InstallationId:{{{0}}}", registration.InstallationId) };
                    switch (registration.Platform)
                    {
                        case NotificationPlatform.Wns:
                            await Notifier.Instance.sendWindowsStoreNotification(message, tags);
                            break;
                        case NotificationPlatform.Apns:
                            await Notifier.Instance.sendIOSNotification(message, tags);
                            break;
                        case NotificationPlatform.Mpns:
                            await Notifier.Instance.sendWPNotification(message, tags);
                            break;
                        case NotificationPlatform.Gcm:
                            await Notifier.Instance.sendGCMNotification(message, tags);
                            break;
                        case NotificationPlatform.Adm:
                            //NOT SUPPORTED
                            break;
                        default:
                            break;
                    }
                }
            }

            return true;
        }
Exemplo n.º 23
0
        public string MakeReservation(Reservation resItem)
        {
            ReservationType rtype = ReservationType.GetType(resItem.Type);

            if (rtype == ReservationType.LTWeekly || rtype == ReservationType.LTWeeklyWorkHrs)
            {
                resItem.EndDate = resItem.StartDate.AddDays(7);
            }
            else if (rtype == ReservationType.LTMonthly || rtype == ReservationType.LTMonthlyWorkHrs)
            {
                resItem.EndDate = resItem.StartDate.AddDays(30);
            }
            else
            {
                resItem.EndDate = resItem.StartDate.AddDays(1);
            }

            resItem.EndDate = resItem.EndDate.AddSeconds(-1); // 12.59.59 PM Local time on the last day of reservation

            using (var context = new MobileServiceContext())
            {
                try
                {
                    ParkingLot parkingLot = context.ParkingLots.Find(resItem.LotId);

                    string sql = "SELECT COUNT(*) FROM Reservation rr WHERE rr.LotId = @lotid and @startDt <= rr.EndDate and @endDt >= rr.StartDate";

                    SqlParameter[] parms = new SqlParameter[]
                    {
                        new SqlParameter("@lotid", resItem.LotId),
                        new SqlParameter("@startDt", resItem.StartDate),
                        new SqlParameter("@endDt", resItem.EndDate),
                    };

                    int reserved = context.Database.SqlQuery <int>(sql, parms).FirstOrDefault();

                    if (reserved >= parkingLot.Capacity)
                    {
                        return("Parking not available for the selected date(s)");
                    }

                    PriceModel priceModel = context.PriceModels.Find(resItem.PriceModelId);
                    resItem.AdvancePaid = priceModel.GetAdvanceCharge(resItem.Type);

                    Utils.CreateStripeCharge(resItem.AdvancePaid.Value, parkingLot.Name, resItem.ConfNumAdvance);

                    parkingLot.Reserved++;
                    context.Reservations.Add(resItem);
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw ServerUtils.BuildException(ex);
                }
            }

            return(null);
        }
Exemplo n.º 24
0
 public Image GetImage(string id)
 {
     using (var ctx=new MobileServiceContext())
     {
         return ctx.Images.Include("User").SingleOrDefault(x => x.Id == id);
     }
     
    
 }
        public CustomAuthController()
        {
            dbContext = new MobileServiceContext();
            string website = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");

            Audience   = $"https://{website}/";
            Issuer     = $"https://{website}/";
            SigningKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
        }
Exemplo n.º 26
0
        //Defining the controller constructor to get important keys from the backend
        public CustomAuthController()
        {
            db         = new MobileServiceContext();
            signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
            var website = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");

            audience = $"https://testingparkkl.azurewebsites.net/";
            issuer   = $"https://testingparkkl.azurewebsites.net/";
        }
Exemplo n.º 27
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            var softDeleteEnabled        = Convert.ToBoolean(ConfigurationManager.AppSettings["enableSoftDelete"]);
            MobileServiceContext context = new MobileServiceContext();

            controllerContext.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            DomainManager = new EntityDomainManager <Album>(context, Request, enableSoftDelete: softDeleteEnabled);
        }
Exemplo n.º 28
0
        // GET a specific patient's sample count
        public static int GetSampleCountforPatientID(string patientID)
        {
            MobileServiceContext db = new MobileServiceContext();
            Patient currentPatient  = PatientController.GetPatientObject(patientID);
            var     samplesArr      = db.Samples.Where(p => p.PatientID == currentPatient.Id);

            Trace.TraceInformation("Found: {0} samples for patient {1}", samplesArr.Count(), patientID);
            return(samplesArr.Count());
        }
Exemplo n.º 29
0
 private static void AddOrUpdateSpecialOffersSchemas(MobileServiceContext context)
 {
     context.SpecialOffersSchemas.AddOrUpdate(p => p.Id,
                                              new SpecialOffersSchema
     {
         Id       = Guid.NewGuid().ToString(),
         Title    = "Daily menu special",
         Dessert1 = "orem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis rutrum quam.",
         Main1    = "Cras porttitor est justo, sit amet rutrum orci facilisis ac. Quisque sagittis a a" +
                    "rcu at dictum. Suspendisse viverra diam at felis vehicula gravida. Phasellus non" +
                    " cursus magna. Phasellus nunc nisl, congue et pharetra eu, dictum a nisi. ",
         Starter1 = "Quisque consequat auctor urna tincidunt bibendum. Quisque vitae commodo neque. Ut" +
                    " vitae eleifend dolor, nec elementum nibh. ",
         Subtitle = "Price: $10",
     },
                                              new SpecialOffersSchema
     {
         Id       = Guid.NewGuid().ToString(),
         Title    = "Kids menu",
         Dessert1 = "Vivamus sagittis purus vel elementum suscipit. Nulla lectus ligula, dapibus sit a" +
                    "met elit vel, facilisis bibendum libero. ",
         Main1 = "molestie vitae metus. Sed velit velit, condimentum porta congue id, varius ac era" +
                 "t. Quisque eu justo non felis luctus rhoncus sed ut risus. Nulla sed erat dui. I" +
                 "nteger facilisis sapien non turpis volutpat viverra.",
         Starter1 = "Duis consectetur sit amet neque in posuere. Vestibulum vitae sagittis ipsum. Null" +
                    "a non ante sit amet eros dictum bibendum. Donec et convallis urna. Morbi id vene" +
                    "natis nunc.",
         Subtitle = "Price: $5",
     },
                                              new SpecialOffersSchema
     {
         Id       = Guid.NewGuid().ToString(),
         Title    = "Menu for two",
         Dessert1 = "Praesent sagittis imperdiet vulputate. In hac habitasse platea dictumst. Donec ul" +
                    "lamcorper vehicula imperdiet. ",
         Main1 = "Nam porttitor accumsan posuere. Morbi vehicula lorem et mi eleifend luctus eu qui" +
                 "s quam. Nullam ut tellus vel purus luctus ornare. ",
         Starter1 = " Phasellus at odio vitae ante luctus facilisis. Fusce imperdiet viverra aliquam. " +
                    "Sed ac nibh commodo, blandit arcu a, facilisis metus. Phasellus vehicula ultrici" +
                    "es elementum. Aenean eros ligula, vestibulum vitae felis vel, commodo volutpat a" +
                    "ugue. ",
         Subtitle = "Price: $18",
     },
                                              new SpecialOffersSchema
     {
         Id       = Guid.NewGuid().ToString(),
         Title    = "Menu for four",
         Dessert1 = "Curabitur accumsan tortor nibh, id viverra ante egestas non. Phasellus tortor mau" +
                    "ris, ornare vitae ultricies quis,[Enter name]",
         Main1 = " Duis sodales elementum lacus id suscipit. Nunc eget justo porttitor, faucibus te" +
                 "llus eu, rhoncus risus. Suspendisse potenti. ",
         Starter1 = "Nulla facilisi. Mauris neque odio, egestas ac scelerisque a, ullamcorper id nibh." +
                    " Fusce ut mollis massa. Nunc venenatis nisi sed consequat pulvinar. ",
         Subtitle = "Price: $35",
     });
 }
Exemplo n.º 30
0
        // GET a specific patient's caregivers
        public List <Caregiver> GetCaregiversforPatientID(string patientID)
        {
            MobileServiceContext db = new MobileServiceContext();
            Patient currentPatient  = PatientController.GetPatientObject(patientID);
            var     caregiversArr   = db.Caregivers.Where(p => p.GroupID == currentPatient.GroupID);

            Trace.TraceInformation("Number of caregivers found: {0}", caregiversArr.Count());

            return(caregiversArr.ToList <Caregiver>());
        }
        private static void AddUser(string identifier, MobileServiceContext ctx)
        {
            var u =
                ctx.Users.Add(
                    new User {
                        Id = identifier,
                    });

            ctx.SaveChanges();
        }
Exemplo n.º 32
0
        /// <summary>
        /// Gets the conversation id for the specified user.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <string> GetConversationByUserIdAsync(string userId, CancellationToken cancellationToken)
        {
            using (var context = new MobileServiceContext())
            {
                var link = await context.UserConversations
                           .FirstOrDefaultAsync(l => l.UserId == userId, cancellationToken)
                           .ConfigureAwait(false);

                return(link?.ConversationId);
            }
        }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            _context      = new MobileServiceContext();
            DomainManager = new EntityDomainManager <Employee>(_context, Request, Services);

            // Create cache connection
            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisCache"].ToString());

            _cache = connection.GetDatabase();
        }
Exemplo n.º 34
0
        private static void AddOrUpdateStartersSchemas(MobileServiceContext context)
        {
            context.StartersSchemas.AddOrUpdate(p => p.Id, new StartersSchema
            {
                Id       = Guid.NewGuid().ToString(),
                Subtitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis rutrum quam. " +
                           "",
                Title = "Praesent sagittis imperdiet vulputate. In hac habitasse platea dictumst. Donec ul" +
                        "lamcorper vehicula imperdiet. ",
                Image       = "/Assets/DataImages/Item-d3de8689-45e1-4f9c-b07b-8b82680e103d.jpg",
                Description =
                    @"uisque consequat auctor urna tincidunt bibendum. Quisque vitae commodo neque. Ut vitae eleifend dolor, nec elementum nibh.

Duis consectetur sit amet neque in posuere. Vestibulum vitae sagittis ipsum. Nulla non ante sit amet eros dictum bibendum. Donec et convallis urna. Morbi id venenatis nunc. Phasellus at odio vitae ante luctus facilisis. Fusce imperdiet viverra aliquam. Sed ac nibh commodo, blandit arcu a, facilisis metus. ",
            },
                                                new StartersSchema
            {
                Id       = Guid.NewGuid().ToString(),
                Subtitle = "Cras porttitor est justo, sit amet rutrum orci facilisis ac. Quisque sagittis a a" +
                           "rcu at dictum. Suspendisse viverra diam at felis vehicula gravida.",
                Title = "Curabitur accumsan tortor nibh, id viverra ante egestas non. Phasellus tortor mau" +
                        "ris, ornare vitae ultricies quis, molestie vitae metus. Sed velit velit, condime" +
                        "ntum porta congue id, varius ac erat.",
                Image       = "/Assets/DataImages/Item-ca3c4a86-0c71-47ca-af18-f02a12e86b25.jpg",
                Description = "Phasellus vehicula ultricies elementum. Aenean eros ligula, vestibulum vitae feli" +
                              "s vel, commodo volutpat augue.\n\nNulla facilisi. Mauris neque odio, egestas ac sc" +
                              "elerisque a, ullamcorper id nibh. Fusce ut mollis massa. ",
            },
                                                new StartersSchema
            {
                Id       = Guid.NewGuid().ToString(),
                Subtitle = "Phasellus non cursus magna. Phasellus nunc nisl, congue et pharetra eu, dictum a " +
                           "nisi.",
                Title =
                    @"Quisque eu justo non felis luctus rhoncus sed ut risus. Nulla sed erat dui. Integer facilisis sapien non turpis volutpat viverra. Nam porttitor accumsan posuere. Morbi vehicula lorem et mi eleifend luctus eu quis quam. Nullam ut tellus vel purus luctus orn",
                Image       = "/Assets/DataImages/Item-10dc3d9e-5320-4a8f-89c1-93dc9834460f.jpg",
                Description = "Nunc venenatis nisi sed consequat pulvinar. Maecenas volutpat tincidunt ante, qui" +
                              "s ornare massa euismod nec. Etiam euismod sapien justo, vel tincidunt massa pulv" +
                              "inar vel. Morbi auctor risus eget suscipit sodales.",
            },
                                                new StartersSchema
            {
                Id       = Guid.NewGuid().ToString(),
                Subtitle = "Vivamus sagittis purus vel elementum suscipit. Nulla lectus ligula, dapibus sit a" +
                           "met elit vel, facilisis bibendum libero. ",
                Title = "Duis sodales elementum lacus id suscipit. Nunc eget justo porttitor, faucibus tel" +
                        "lus eu, rhoncus risus. Suspendisse potenti. ",
                Image       = "/Assets/DataImages/Item-a4af80ef-45ce-461c-a008-0a803c8ebb13.jpg",
                Description = " Aliquam erat volutpat. Sed non metus purus. Donec dignissim tincidunt justo a ma" +
                              "lesuada.\n\nSed sodales sagittis feugiat. Proin sit amet suscipit orci. In non sag" +
                              "ittis mi. Integer sollicitudin fermentum suscipit. Etiam ut condimentum nunc. ",
            });
        }
        // GET api/ManageUser
        public async Task<string> Get()
        {
            string username = await GetUserId(Request, this.User);

            Debug.WriteLine($"Username is: {username}");

            using (var ctx = new MobileServiceContext()) {
                var user = ctx.Users.Find(username);

                if (user == null) {
                    AddUser(username, ctx);
                }

                return username;
            }
        }
        // GET api/PushRegistration
        public async Task Post([FromBody] DeviceInstallationInfo deviceInstallInfo)
        {
            bool isChanged = false;
            var ctx = new MobileServiceContext();
            var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId);

            if (registration.Count() == 0)
            {
                NotificationPlatform? plat = await GetNotificationPlatform(deviceInstallInfo.InstallationId);

                if (null != plat)
                {
                    var newRegistration = new Common.Models.DeviceRegistration() {
                        Id = Guid.NewGuid().ToString(),
                                                                                         InstallationId = deviceInstallInfo.InstallationId,
                                                                                         UserId = deviceInstallInfo.UserId,
                        Platform = plat.Value
                    };

                    ctx.DeviceRegistrations.Add(newRegistration);
                    isChanged = true;
                }
            }
            else
            {
                var reg = registration.First();

                if (reg.UserId != deviceInstallInfo.UserId)
                {
                    reg.UserId = deviceInstallInfo.UserId;
                    isChanged = true;
                }
            }

            try
            {
                if (isChanged)
                    ctx.SaveChanges();
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 37
0
        // POST: api/Like
        public async Task<bool> Post([FromBody]Dictionary<string, string> imageInfo)
        {
            using (var ctx = new MobileServiceContext()) {
                var imageId = imageInfo["imageId"]; // resolve imageId to a value before using it in a LINQ expression
                var image = ctx.Images.Include("User").SingleOrDefault(x => x.Id == imageId);

                if (image != null) {
                    var registrations = ctx.DeviceRegistrations.Where(x => x.UserId == image.UserId);

                    //Send plat-specific message to all installation one by one
                    string message = "Someone has liked your image";
                    foreach (var registration in registrations) {
                        await SendPush(message, registration);
                    }

                    return true;
                }

                return false;
            }
        }
Exemplo n.º 38
0
 public Image AddImageToDB(string AlbumId, string UserId, string containerName, string fileName, string UploadFormat)
 {
     ContosoStorage cs = new ContosoStorage();
     var ctx = new MobileServiceContext();
     var img = new Image
     {
         Album = ctx.Albums.Where(x => x.Id == AlbumId).FirstOrDefault(),
         User = ctx.Users.Where(x => x.Id == UserId).FirstOrDefault(),
         Id = Guid.NewGuid().ToString(),
         UploadFormat = UploadFormat,
         ContainerName = AppSettings.StorageWebUri + containerName,
         FileName = fileName,
         
       
     };
     ctx.Images.Add(img);
     try
     {
        ctx.SaveChanges();
        return img;
     }
     catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
     {
         Exception raise = dbEx;
         foreach (var validationErrors in dbEx.EntityValidationErrors)
         {
             foreach (var validationError in validationErrors.ValidationErrors)
             {
                 string message = string.Format("{0}:{1}",
                     validationErrors.Entry.Entity.ToString(),
                     validationError.ErrorMessage);
                 // raise a new exception nesting
                 // the current instance as InnerException
                 raise = new InvalidOperationException(message, raise);
             }
         }
         throw raise;
     }
 }
        public async Task Delete([FromBody] DeviceInstallationInfo deviceInstallInfo)
        {
            var ctx = new MobileServiceContext();
            var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId);

            if (registration.Count() > 0)
            {
                var reg = registration.First();

                await Notifier.Instance.RemoveRegistration(deviceInstallInfo.InstallationId);

                ctx.DeviceRegistrations.Remove(reg);

                try
                {
                    ctx.SaveChanges();
                }
                catch (System.Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }