public async Task <IActionResult> Index()
        {
            var users = new Test()
            {
                FirstName = "Abhishek",
                LastName  = "Verma",
                BirthDate = DateTime.Now
            };

            await _peopleRepository.InsertOneAsync(users);           //to post data

            var people = _peopleRepository.FilterBy(                 // to get by passing query
                filter => filter.FirstName != ""
                );
            var user = _peopleRepository.AsQueryable();             //To get entire data
            var byId = _peopleRepository.FindById("5ef87ab7312dc11e1097e41d");

            var userReplace = new Test()
            {
                Id        = new MongoDB.Bson.ObjectId("5ef87ab7312dc11e1097e41d"),
                FirstName = "Saurabh",
                LastName  = "Doe",
                BirthDate = DateTime.Now
            };

            _peopleRepository.ReplaceOne(userReplace);                //Update
                                                                      //var u = _peopleRepository.FindOne(Users.Equals("Saurabh"));

            _peopleRepository.DeleteById("5ef87ab7312dc11e1097e41d"); //delete

            return(View());
        }
        ServiceResponse<IList<BudgetReceipt>> ISearchEngine.FindBudgetItemDescriptions(ServiceRequest<BudgetReceipt> searchRequest)
        {
            var output = new ServiceResponse<IList<BudgetReceipt>>();

            using (var unitOfWork = RepositoryManager<BudgetReceipt>.Instance.CreateWorkUnit())
            {
                try
                {
                    var repo = new Repository<BudgetReceipt>(unitOfWork.Session);
                    var result = repo.FilterBy(x => (x.Subscriber.Id == _subscriber.Id && x.Description.StartsWith(searchRequest.Data.Description))).ToList();
                    unitOfWork.Commit();

                    output.Data = result.Distinct(new BudgetReceipt.DescriptionCompare()).ToList();
                    output.Result = Result.Successful;

                }
                catch (GenericADOException e)
                {
                    output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e);
                    _logger.Critical(output.Message, e);
                    output.Result = Result.Failure;
                }
                catch (Exception e)
                {
                    _logger.Critical(e.Message, e);
                }
            }

            return output;
        }
Example #3
0
        public IActionResult ManagePathwayPost(PathwaySteps pathwaySteps, string id)
        {
            var totalRecord    = _peopleRepository.FilterBy(e => e.PathwayId == id);
            var numberofRecord = totalRecord.Count();

            var path     = _path.FindById(id);
            var issuerid = path.IssuersId;

            if (ModelState.IsValid)
            {
                string webRootPath = _hostEnvironment.WebRootPath;
                var    files       = HttpContext.Request.Form.Files;
                if (files.Count > 0)
                {
                    string fileName   = Guid.NewGuid().ToString();
                    var    uploads    = Path.Combine(webRootPath, @"Documents");
                    var    extenstion = Path.GetExtension(files[0].FileName);
                    using (var filesStreams = new FileStream(Path.Combine(uploads, files[0].FileName), FileMode.Create))
                    {
                        files[0].CopyTo(filesStreams);
                    }
                    pathwaySteps.Documents       = files[0].FileName;
                    pathwaySteps.PathwayId       = id.ToString();
                    TempData["PathwayStepBadge"] = pathwaySteps.GetBadges;
                }
                if (numberofRecord == 0)
                {
                    pathwaySteps.count = 0;
                }
                pathwaySteps.count    = numberofRecord + 1;
                pathwaySteps.IssuerId = issuerid;
                _peopleRepository.InsertOne(pathwaySteps);
            }
            return(RedirectToAction("ManagePathway"));
        }
Example #4
0
        public IActionResult ManagePathway(string id)
        {
            var path     = _path.FindById(id);
            var issuerid = path.IssuersId;

            List <PathwaySteps> all  = _peopleRepository.AsQueryable().ToList();
            List <PathwaySteps> list = all.Where(e => e.PathwayId == id).ToList();

            if (list == null)
            {
                ModelState.AddModelError(string.Empty, "Pathway id is null");
            }
            PathwayCreation pathwayCreation = new PathwayCreation()
            {
                GetBadgesinList = _badge.FilterBy(e => e.IssuerId == issuerid).ToList(),
                steps           = list,
                pathwayName     = path.PathwayName
            };

            return(View(pathwayCreation));
        }
        ServiceResponse<Subscriber> ISubscriptionService.Authenticate(ServiceRequest<Subscriber> request)
        {
            var output = new ServiceResponse<Subscriber>();

            using (var unitOfWork = RepositoryManager<Subscriber>.Instance.CreateWorkUnit())
            {
                try
                {
                    var repo = new Repository<Subscriber>(unitOfWork.Session);
                    var data = request.Data;

                    var subscribers = repo.FilterBy(x => x.Email == data.Email).ToList();

                    if (subscribers.Count == 0)
                    {
                        output.Result = Result.LoginFailed;
                        output.Message = "Invalid user name and password";
                        return output;
                    }

                    foreach (var subscriber in subscribers)
                    {
                        var password = Cryptography.GetMD5Hash(Cryptography.CreateInstance().Decrypt(subscriber.Password));

                        if (data.Password != password) continue;

                        var guid = Cryptography.GetMD5Hash(Guid.NewGuid().ToString());
                        output.Data = subscriber;
                        output.Data.Password = guid;
                        output.Result = Result.Successful;
                        ServiceDirectory.CacheService(CacheType.Memory).AddItem(guid, subscriber);

                        return output;
                    }

                }
                catch (GenericADOException e)
                {
                    output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e);
                    output.Result = Result.Failure;
                }
                catch (Exception e)
                {
                    _logger.Critical(e.Message, e);
                    output.Message = "Invalid username or password";
                    output.Result = Result.Failure;
                }
            }

            return output;
        }
        public async Task <IActionResult> CreateAsync(Issuers issuers)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var claimsIdentity = (ClaimsIdentity)User.Identity;
                    var claim          = claimsIdentity.Claims.ToArray();
                    var useid          = User.Claims.FirstOrDefault(c => c.Type == AppUtility.UserId).Value;    //to get userId of loggedIn user
                    var userRole       = _userRoles.AsQueryable().ToList();                                     //to get userRoleList
                    var issuerRoles    = userRole.Where(e => e.Role == AppUtility.IssuerRole).FirstOrDefault(); //find the object of issuer role

                    string webRootPath = _hostEnvironment.WebRootPath;
                    var    files       = HttpContext.Request.Form.Files;
                    if (files.Count > 0)
                    {
                        string fileName   = Guid.NewGuid().ToString();
                        var    uploads    = Path.Combine(webRootPath, @"Images\issuers");
                        var    extenstion = Path.GetExtension(files[0].FileName);
                        using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extenstion), FileMode.Create))
                        {
                            files[0].CopyTo(filesStreams);
                        }
                        issuers.Image = @"\images\issuers\" + fileName + extenstion;
                    }
                    DateTime today = DateTime.Now;
                    var      isEmailExistInUser   = _user.FilterBy(e => e.Email == issuers.Email).ToList();
                    var      isEmailExistInIssuer = collection.Find(e => e.Email == issuers.Email).ToList();
                    if (isEmailExistInIssuer.Count() > 0 || isEmailExistInUser.Count() > 0)
                    {
                        ModelState.AddModelError(string.Empty, "User with this email already exist");     //show popup if same email exists
                        return(View());
                    }

                    DigiBadges.DataAccess.Users user = new DigiBadges.DataAccess.Users()
                    {
                        CreatedBy      = claim[0].Value,
                        CreatedDate    = today,
                        Email          = issuers.Email,
                        FirstName      = issuers.Name,
                        IsUserVerified = true,
                        Password       = AppUtility.Encrypt(AppUtility.IssuerPassword),
                        RoleId         = issuerRoles.Id.ToString()
                    };
                    _user.InsertOne(user);                                             //Inserting object in issuer table

                    DigiBadges.Models.Users users = new DigiBadges.Models.Users()
                    {
                        CreatedBy      = claim[0].Value,
                        CreatedDate    = today,
                        Email          = issuers.Email,
                        FirstName      = issuers.Name,
                        IsUserVerified = true,
                        Password       = AppUtility.Encrypt(AppUtility.IssuerPassword),
                        RoleId         = issuerRoles.Id.ToString(),
                        UserId         = user.Id
                    };

                    SolrUsersModel su = new SolrUsersModel(users);
                    _solr.Add(su);                                     //Adding data in solr
                    _solr.Commit();

                    var userIdInUserTable = _user.AsQueryable().ToList();
                    var uid = userIdInUserTable.Where(e => e.Email == issuers.Email).FirstOrDefault();
                    if (user.Id != null)
                    {
                        issuers.UserId      = user.Id;     //setting the userId which we got after inserting the above data in user collection
                        issuers.CreatedDate = today;
                    }

                    collection.InsertOne(issuers);         //To post the issuer object

                    SolrIssuersModel sissuser = new SolrIssuersModel(issuers);
                    _solrIssuer.Add(sissuser);             //Adding data in solr
                    _solrIssuer.Commit();

                    await _emailSender.SendEmailAsync(issuers.Email,                     //to send email to new issuer
                                                      "Congatulations you are invited as a issuer",
                                                      $"<h4 class='m-2'>Your Email id is -{HtmlEncoder.Default.Encode(issuers.Email)}</h4></div>" +
                                                      "Your password is - Welcome@123");
                }
                catch (Exception)
                {
                    ModelState.AddModelError(string.Empty, "Please try again later.");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }

            return(View());
        }
        public IActionResult IssuersDelete(string id)
        {
            ObjectId oId    = new ObjectId(id);
            var      issuer = _i.FindById(id);

            var users        = _user.AsQueryable().ToList();
            var userToDelete = users.Where(e => e.Id == issuer.UserId).FirstOrDefault();

            DigiBadges.Models.Users usrMod = new DigiBadges.Models.Users()
            {
                CreatedBy      = userToDelete.CreatedBy,
                CreatedDate    = userToDelete.CreatedDate,
                Email          = userToDelete.Email,
                FirstName      = userToDelete.FirstName,
                IsUserVerified = userToDelete.IsUserVerified,
                Password       = userToDelete.Password,
                RoleId         = userToDelete.RoleId,
                UserId         = userToDelete.Id
            };

            DigiBadges.Models.Issuers issMod = new DigiBadges.Models.Issuers()
            {
                IssuerId    = issuer.Id,
                Image       = issuer.Image,
                Name        = issuer.Name,
                WebsiteUrl  = issuer.WebsiteUrl,
                Email       = issuer.Email,
                Description = issuer.Description,
                UserId      = issuer.UserId,
                StaffsIds   = issuer.StaffsIds,
                CreatedDate = issuer.CreatedDate
            };

            SolrUsersModel   solUserMod = new SolrUsersModel(usrMod);
            SolrIssuersModel sissuser   = new SolrIssuersModel(issMod);



            _user.DeleteById(userToDelete.Id.ToString());                        //Deleting user from user collection
            var result = collection.DeleteOne <Issuers>(e => e.IssuerId == oId); //Deleting user from issuer collection

            if (result.DeletedCount > 0)
            {
                var results = _solr.Delete(solUserMod);
                //Saving the changes
                _solr.Commit();



                _solrIssuer.Delete(sissuser);
                _solrIssuer.Commit();
            }

            var badges = _b.FilterBy(e => e.IssuerId == issuer.Id).ToList();

            if (badges != null)
            {
                _b.DeleteMany(e => e.IssuerId == issuer.Id);
            }

            return(RedirectToAction("Index"));
        }
Example #8
0
        private void btSave_Click(object sender, EventArgs e)
        {
            if ( ! string.IsNullOrEmpty(tbxSubject.Text)  && ! string.IsNullOrEmpty(tbxBody.Text) )
            {
                if ( dtpExpiryDate.Value < dtpPublishDate.Value )
                {
                    ShowError("Error", "Expiry date cannot be before the publish date.");
                    return;
                }
                _unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
                Repository<Guid, State> _stateRepo = new Repository<Guid, State>(_unitOfWork.Session);
                Repository<Guid, APLBackendDB.Region> _regionRepo = new Repository<Guid, APLBackendDB.Region>(_unitOfWork.Session);
                Repository<Guid, Brand> _brandRepo = new Repository<Guid, Brand>(_unitOfWork.Session);
                Repository<Guid, NewsItem> _newsItemRepo = new Repository<Guid, NewsItem>(_unitOfWork.Session);
                Repository<Guid, APLBackendDB.Image> _imageRepo = new Repository<Guid, APLBackendDB.Image>(_unitOfWork.Session);

                _newsItem = _newsItemRepo.FindBy(_newsItemId);
                if ( _newsItem == null )
                {
                    _newsItem = new NewsItem();
                }

                _newsItem.Subject = tbxSubject.Text;
                _newsItem.Active = cbxActive.Checked;
                _newsItem.Author = tbxAuthor.Text;
                _newsItem.Body = tbxBody.Text;

                APLBackendDB.Brand _brand = _brandRepo.FindBy(Guid.Parse(cbxBrand.SelectedValue.ToString()));
                if ( _brand != null )
                {
                    _newsItem.Brand = _brand;
                }
                State _state = _stateRepo.FindBy(Guid.Parse(cbxState.SelectedValue.ToString()));
                if ( _state != null )
                {
                    _newsItem.State = _state;
                }
                APLBackendDB.Region _region = _regionRepo.FindBy(Guid.Parse(cbxRegion.SelectedValue.ToString()));
                if ( _region != null )
                {
                    _newsItem.Region = _region;
                }
                _newsItem.ExpiryDate = dtpExpiryDate.Value;
                _newsItem.PublishDate = dtpPublishDate.Value;
                _newsItem.Push = cbxPush.Checked;

                //_imageRepo.AddOrUpdate(_images);
                _newsItem.Images = _images;

                if (_newsItem.Id == Guid.Empty)
                {
                    _newsItemRepo.Add(_newsItem);
                }
                else
                {
                    _newsItemRepo.Update(_newsItem);
                }

                _unitOfWork.Commit();
                _unitOfWork.Dispose();

                if ( cbxPush.Checked )
                {
                    GoogleInteraction.GCMMessage gcmMessage = new GCMMessage();
                    UnitOfWork unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));

                    Repository<Guid, UserMobileDevice> userMobileDeviceRepo = new Repository<Guid, UserMobileDevice>(unitOfWork.Session);

                    var devices = userMobileDeviceRepo.FilterBy(x => x.EnablePushNotifications == true);

                    gcmMessage.Data.Add("message", tbxSubject.Text);
                    gcmMessage.Data.Add("type", "news="+_newsItem.Id.ToString());
                    foreach (UserMobileDevice userMobileDevice in devices)
                    {
                        gcmMessage.RecipientDevices.Add(userMobileDevice.Token);
                    }
                    gcmMessage.CollapseKey = "broadcast";
                    gcmMessage.Send();

                }
            } else
            {

            }
        }
Example #9
0
        public string Authenticate(string Username, string Password)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;

            string result = "ERR - Unknown";

            string responseString = null;
            Response response = new Response();
            UnitOfWork unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
            Repository<Guid, User> userRepo = new Repository<Guid, User>(unitOfWork.Session);
            Repository<Guid, UserToken> userTokenRepo = new Repository<Guid, UserToken>(unitOfWork.Session);
            user = userRepo.FilterBy(x => x.Username == Username).FirstOrDefault();

            if (user != null && user.Id != Guid.Empty)
            {
                if (Password == user.Password)
                {
                    AuthToken token = new AuthToken();

                    if (!string.IsNullOrEmpty(user.AuthToken))
                    {
                        if (CheckToken(user.AuthToken) == null)
                        {
                            user.AuthToken = null;
                        }
                    }

                    if (string.IsNullOrEmpty(user.AuthToken))
                    {
                        result = GenerateAuthToken();
                        APLBackendDB.UserToken userToken = new UserToken();
                        userToken.CreateDate = DateTime.Now;
                        userToken.ExpiryDate = DateTime.Now.AddHours(4);
                        userToken.LastUsedDate = DateTime.Now;
                        userToken.Token = result;
                        userToken.UserId = user.Id;
                        userTokenRepo.Add(userToken);

                        user.AuthToken = result;
                        userRepo.Update(user);

                        token.Token = result;
                    }
                    else
                    {
                        token.Token = user.AuthToken;
                    }

                    response.ResponseCode = "OK";
                    response.ResponseData = token;
                }
                else
                {
                    response.ResponseCode = "ERR";
                    response.ResponseData = "Authentication failed.";
                }
            }
            else
            {
                response.ResponseCode = "ERR";
                response.ResponseData = "User not found.";
            }

            js = new JavaScriptSerializer();
            responseString = JsonConvert.SerializeObject(response, j);
            unitOfWork.Commit();
            return responseString;
        }
Example #10
0
        public void SyncVenue()
        {
            ProgressUpdateArgs e = new ProgressUpdateArgs();
            // Venue Table

            _UnitOfWorkAPL = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
            _UnitOfWorkFHG = new UnitOfWork(_sessionHelper.GetSessionFactory("FHG"));

            Repository<int, CusOrgentity> _fhgVenueRepo = new Repository<int, CusOrgentity>(_UnitOfWorkFHG.Session);
            Repository<Guid, Venue> _aplVenueRepo = new Repository<Guid, Venue>(_UnitOfWorkAPL.Session);
            Repository<Guid, Region> _aplRegionRepo = new Repository<Guid, Region>(_UnitOfWorkAPL.Session);

            //IList<object[]> fhgVenue = _sessionHelper.GetStatelessSession("FHG").QueryOver<CusOrgentity>()
            //                            .Select(c => c.Orgentityid,
            //                            c => c.Active,
            //                            c => c.Name).List<object[]>();

            //IList<object[]> aplVenueResult = _sessionHelper.GetStatelessSession("APL").QueryOver<Venue>()
            //    .Select(c => c.Id,
            //    c => c.FHGVenueId,
            //    c => c.Active,
            //    c => c.Name).List<object[]>();

            var fhgVenue = _fhgVenueRepo.All().ToList();
            var aplVenueResult = _aplVenueRepo.All().ToList();

            Dictionary<int, object> aplVenues = new Dictionary<int, object>();
            foreach (Venue o in aplVenueResult)
            {
                aplVenues.Add(o.FHGVenueId, o);
            }

            // Add Missing data
            int itemCount = 1;
            foreach (CusOrgentity fhgCustOrgEntity in fhgVenue)
            {
                try
                {
                     e.TotalWorkItems = fhgVenue.Count();
                    e.CurrentWorkItem = itemCount;
                    e.StatusString = "Syncing Venues - (" + itemCount.ToString() + "/" + e.TotalWorkItems.ToString() + ")";
                    this.ProgressUpdate(e);

                    if (!aplVenues.ContainsKey(fhgCustOrgEntity.Id))
                    {
                        CusOrgentity c = fhgCustOrgEntity;
                        Venue v = new Venue();
                        v.Name = c.Name;
                        v.Active = (c.Active != null) ? (bool)c.Active : true;
                        v.FHGVenueId = c.Id;
                        if (c.Region.Count > 0)
                        {
                            v.Region = _aplRegionRepo.FilterBy(x => x.Name == c.Region[0].Regionname).FirstOrDefault();
                        }
                        _aplVenueRepo.Add(v);
                    }
                    else
                    {
                        Venue aplVenue = (Venue)aplVenues[fhgCustOrgEntity.Id];

                        if (aplVenue.Active != fhgCustOrgEntity.Active || aplVenue.Name != fhgCustOrgEntity.Name)
                        {
                            aplVenue.Name = fhgCustOrgEntity.Name;
                            aplVenue.Active = (bool)(fhgCustOrgEntity.Active.HasValue ? false : fhgCustOrgEntity.Active);
                            _aplVenueRepo.Update(aplVenue);
                        }
                    }
                    itemCount++;
                }
                catch (Exception mException)
                {
                    int x = 1;
                    continue;
                }
            }

            _UnitOfWorkAPL.Commit();
            _UnitOfWorkFHG.Commit();
        }
Example #11
0
        public IActionResult EditStaff(string id, DigiBadges.DataAccess.Users users)
        {
            var a = _u.FindById(id);

            a.FirstName = users.FirstName;
            a.LastName  = users.LastName;
            a.Email     = users.Email;


            var userid = User.Claims.FirstOrDefault(c => c.Type == AppUtility.UserId).Value;

            DigiBadges.Models.Users usr = new DigiBadges.Models.Users()
            {
                //CreatedBy = usr.CreatedBy,

                FirstName      = users.FirstName,
                LastName       = users.LastName,
                Email          = users.Email,
                UserId         = new ObjectId(id),
                RoleId         = a.RoleId,
                Password       = a.Password,
                CreatedBy      = a.CreatedBy,
                CreatedDate    = a.CreatedDate,
                IsUserVerified = a.IsUserVerified
                                 //UserId = users.Id
            };

            SolrUsersModel su = new SolrUsersModel(usr);

            _solr.Add(su);
            _solr.Commit();


            List <DataAccess.Issuers> issuerlist1 = _i.FilterBy(e => e.UserId == new ObjectId(userid)).ToList();

            DataAccess.Issuers issuers  = new DataAccess.Issuers();
            string             issuerid = "";

            foreach (var item in issuerlist1)
            {
                issuerid = item.Id.ToString();
            }

            var issuerlist = _i.FindById(issuerid);

            DataAccess.Issuers i = new DataAccess.Issuers();
            i.Staffsobject = issuerlist.Staffsobject;
            i.Id           = new ObjectId(issuerid);
            i.Image        = issuerlist.Image;
            i.Name         = issuerlist.Name;
            i.WebsiteUrl   = issuerlist.WebsiteUrl;
            i.Description  = issuerlist.Description;
            i.Email        = issuerlist.Email;
            i.UserId       = issuerlist.UserId;
            i.StaffsIds    = issuerlist.StaffsIds;
            i.CreatedDate  = issuerlist.CreatedDate;
            foreach (var j in i.Staffsobject)
            {
                if (j.Id == new ObjectId(id))
                {
                    j.FirstName = users.FirstName;
                    j.LastName  = users.LastName;
                    j.Email     = users.Email;
                    _i.ReplaceOne(i);
                }
            }

            _u.ReplaceOne(a);

            return(RedirectToAction("ViewStaff"));
        }
Example #12
0
        public string GetVenues(string token, string regionId, string stateId)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;

            Guid regionGuid;
            Guid stateGuid;

            if ( ! Guid.TryParse(regionId, out regionGuid))
            {
                regionGuid = Guid.Empty;
            }

            if ( ! Guid.TryParse(stateId, out stateGuid))
            {
                stateGuid = Guid.Empty;
            }

            string responseString = null;
            Response response = new Response();

            Repository<Guid, Venue> venueRepo = new Repository<Guid, Venue>(_sessionHelper.GetSession("APL"));

            var list = venueRepo.FilterBy(x => ( x.Active == true
                                                && ( regionGuid==Guid.Empty || x.Region.Id == regionGuid )
                                                && ( stateGuid == Guid.Empty || x.Region.State.Id == stateGuid )
                                                )).OrderBy(x => x.Name);
            response.ResponseCode = "OK";
            response.ResponseData = list;

            var serialiser = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver = new NHibernateContractResolver(),
                TypeNameHandling = TypeNameHandling.Objects,
                Formatting = Newtonsoft.Json.Formatting.Indented
            };
            StringWriter stringWriter = new StringWriter();
            JsonWriter jsonWriter = new JsonTextWriter(stringWriter);
            serialiser.Serialize(jsonWriter, response);
            responseString = stringWriter.ToString();

            return responseString;
        }
Example #13
0
        public string GetRegions(string token, string brandId, string stateId)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;

            string responseString = null;
            Response response = new Response();
            Guid brandID = Guid.Empty;
            if (! Guid.TryParse(brandId, out brandID))
            {
                brandID = Guid.Empty;
            }

            Guid stateID = Guid.Empty;
            if (!Guid.TryParse(stateId, out stateID))
            {
                brandID = Guid.Empty;
            }

            Repository<Guid, Region> _regionRepo = new Repository<Guid, Region>(_sessionHelper.GetSession("APL"));

            var list = _regionRepo.FilterBy((p => (
                            (brandID==Guid.Empty|| p.Brand.Id==brandID )
                            && p.Active == true
                            && (stateID==Guid.Empty || p.State.Id == stateID)))).OrderBy(p=>p.Name);

            response.ResponseCode = "OK";
            response.ResponseData = list;
            var serialiser = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new NHibernateContractResolver(), TypeNameHandling = TypeNameHandling.Objects, Formatting = Newtonsoft.Json.Formatting.Indented };
            StringWriter stringWriter = new StringWriter();
            JsonWriter jsonWriter = new JsonTextWriter(stringWriter);
            serialiser.Serialize(jsonWriter, response);

            responseString = stringWriter.ToString();

            return responseString;
        }
Example #14
0
        public string GetNewsItems(string token)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.ContractResolver = new NHibernateContractResolver();
            j.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;

            string responseString = null;
            Response response = new Response();

            Repository<Guid, NewsItem> newsItemRepo = new Repository<Guid, NewsItem>(_sessionHelper.GetSession("APL"));

            var list = newsItemRepo.FilterBy(x => x.Active == true && x.ExpiryDate >= DateTime.Today).OrderBy(x=>x.Importance).OrderByDescending(x => x.PublishDate);
            response.ResponseCode = "OK";
            response.ResponseData = list;

            responseString = JsonConvert.SerializeObject(response, j);

            return responseString;
        }
Example #15
0
        public string GetGameList(string token, string stateId, string brandId, string regionId, string venueId, int daysInAdvance)
        {
            Guid stateID = Guid.Empty;
            Guid brandID = Guid.Empty;
            Guid regionID = Guid.Empty;
            Guid venueID = Guid.Empty;

            Repository<Guid, Game> gameRepo = new Repository<Guid, Game>(_sessionHelper.GetSession("APL"));

            // Parse out the Guids.

            if (!Guid.TryParse(stateId, out stateID))
            {
                stateID = Guid.Empty;
            }
            if (!Guid.TryParse(brandId, out brandID))
            {
                brandID = Guid.Empty;
            }
            if (!Guid.TryParse(regionId, out regionID))
            {
                regionID = Guid.Empty;
            }
            if (!Guid.TryParse(venueId, out venueID))
            {
                venueID = Guid.Empty;
            }

            Response response = new Response();

            var g = gameRepo.FilterBy(x => (
                                                (stateID == Guid.Empty || x.Venue.Region.State.Id == stateID)
                                                && (brandID == Guid.Empty || x.Venue.Region.Brand.Id == brandID)
                                                && (regionID == Guid.Empty || x.Venue.Region.Id == regionID)
                                                && (venueID == Guid.Empty || x.Venue.Id == venueID)
                                                && (x.GameDate >= DateTime.Today && x.GameDate <= DateTime.Today.AddDays(daysInAdvance) )
                                                && (x.Active == true )
                                                && (x.Venue.Active == true )
                                                && (x.Venue.Region.Active == true )
                                                )
            ).OrderBy(x=>x.GameDate);

            if (g != null && g.Count() > 0)
            {
                response.ResponseCode = "OK";
                response.ResponseData = g;
            }
            else
            {
                response.ResponseCode = "ERR";
                response.ResponseData = "No events returned";
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;
            var serialiser = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new NHibernateContractResolver(), TypeNameHandling = TypeNameHandling.Objects, Formatting = Newtonsoft.Json.Formatting.Indented };
            StringWriter stringWriter = new StringWriter();
            JsonWriter jsonWriter = new JsonTextWriter(stringWriter);
            serialiser.Serialize(jsonWriter, response);

            string responseString = stringWriter.ToString();
            return responseString;
        }
        ServiceResponse<IList<BudgetItem>> IBudgetService.BudgetItemList(String budgetId)
        {
            var output = new ServiceResponse<IList<BudgetItem>>();

            using (var unitOfWork = RepositoryManager<BudgetItem>.Instance.CreateWorkUnit())
            {
                try
                {
                    var repo = new Repository<BudgetItem>(unitOfWork.Session);
                    List<BudgetItem> result;

                    result = String.IsNullOrEmpty(budgetId)
                        ? repo.FilterBy(x => x.Subscriber.Id == _subscriber.Id).ToList()
                        : repo.FilterBy(x => (x.Subscriber.Id == _subscriber.Id && x.Budget.Id == budgetId)).ToList();

                    unitOfWork.Commit();

                    foreach (var item in result)
                    {
                        if (item.ReceiptList == null)
                        {
                            continue;
                        }

                        foreach (var receipt in item.ReceiptList.Where(receipt => !receipt.BudgetPeriod.EndDate.HasValue))
                        {
                            item.CurrentPeriod = receipt.BudgetPeriod;
                        }

                    }

                    output.Data = result;
                    output.Result = Result.Successful;

                }
                catch (GenericADOException e)
                {
                    output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e);
                    _logger.Critical(output.Message, e);
                    output.Result = Result.Failure;
                }
                catch (Exception e)
                {
                    _logger.Critical(e.Message, e);
                }
            }

            return output;
        }
        ServiceResponse<IList<ExpenseGroup>> IBudgetService.ExpenseGroupList()
        {
            var output = new ServiceResponse<IList<ExpenseGroup>>();

            using (var unitOfWork = RepositoryManager<ExpenseGroup>.Instance.CreateWorkUnit())
            {
                try
                {
                    var repo = new Repository<ExpenseGroup>(unitOfWork.Session);
                    var result = repo.FilterBy(x => x.Subscriber.Id == _subscriber.Id).ToList();
                    unitOfWork.Commit();

                    output.Data = result;
                    output.Result = Result.Successful;

                }
                catch (GenericADOException e)
                {
                    output.Message = MessageFactory.CreateGenerator(RepositoryType.Postgres).GenerateErrorMessage(e);
                    _logger.Critical(output.Message, e);
                    output.Result = Result.Failure;
                }
                catch (Exception e)
                {
                    _logger.Critical(e.Message, e);
                }
            }

            return output;
        }
Example #18
0
        public void SyncGame()
        {
            ProgressUpdateArgs e = new ProgressUpdateArgs();
            e.StatusString = "Syncing Games - Reading data";
            this.ProgressUpdate(e);

            _UnitOfWorkAPL = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
            _UnitOfWorkFHG = new UnitOfWork(_sessionHelper.GetSessionFactory("FHG"));

            // Customer/Memeber Table
            Repository<int, EvtEvent> _fhgEventRepo = new Repository<int, EvtEvent>(_UnitOfWorkFHG.Session);
            Repository<Guid, EvtGame> _fhgEvtGameRepo = new Repository<Guid, EvtGame>(_UnitOfWorkFHG.Session);
            Repository<Guid, Game> _aplGameRepo = new Repository<Guid, Game>(_UnitOfWorkAPL.Session);
            Repository<Guid, Venue> _aplVenueRepo = new Repository<Guid, Venue>(_UnitOfWorkAPL.Session);
            Repository<Guid, GameType> _aplGameTypeRepo = new Repository<Guid, GameType>(_UnitOfWorkAPL.Session);

            IList<object[]> fhgEvents = _UnitOfWorkFHG.Session.QueryOver<EvtEvent>()
                .Select(x => x.Eventid,
                x => x.Updateversion).Where(x => x.Eventdate >= DateTime.Today.AddDays(-7)).List<object[]>();

            IList<object[]> aplGames = _UnitOfWorkAPL.Session.QueryOver<Game>()
                .Select(c => c.Id,
                c => c.FHGEventId,
                c => c.FHGUpdateVersion).List<object[]>();

            Dictionary<int, object> aplGameList = new Dictionary<int, object>();
            foreach (object[] o in aplGames)
            {
                aplGameList.Add(int.Parse(o[1].ToString()), o);
            }

            int itemCount = 1;

            foreach (object[] fhgEventObject in fhgEvents)
            {
                try
                {
                    e.TotalWorkItems = fhgEvents.Count();
                    e.CurrentWorkItem = itemCount;
                    e.StatusString = "Syncing Games - (" + itemCount.ToString() + "/" + e.TotalWorkItems.ToString() + ")";
                    this.ProgressUpdate(e);

                    int fhgEventId = int.Parse(fhgEventObject[0].ToString());
                    Guid fhgUpdateVersion = Guid.Parse(fhgEventObject[1].ToString());

                    if (!aplGameList.ContainsKey(fhgEventId))
                    {

                        EvtEvent curEvent = _fhgEventRepo.FindBy(fhgEventId);

                        // Skip events which don't have a venue assigned.  Why??
                        if (!curEvent.Orgentityid.HasValue)
                        {
                            continue;
                        }

                        EvtGame curEventGame = curEvent.EvtGame[0];

                        Venue gameVenue = _aplVenueRepo.FilterBy(x => x.FHGVenueId == curEvent.Orgentityid).FirstOrDefault();
                        GameType gameType = _aplGameTypeRepo.FilterBy(x => x.FhgDivisionId == curEventGame.Divisionid).FirstOrDefault();

                        Game newGame = new Game();
                        newGame.FHGEventId = fhgEventId;
                        newGame.FHGUpdateVersion = curEvent.Updateversion;
                        newGame.Description = (!string.IsNullOrEmpty(curEventGame.Gamedescription)) ? curEventGame.Gamedescription : curEvent.Eventdescription;
                        newGame.GameDate = curEvent.Eventdate;
                        newGame.Name = curEvent.Eventname;
                        newGame.RegoTime = DateTime.Parse(curEvent.Eventdate.Value.ToShortDateString() + " " + curEvent.Registrationtime);
                        newGame.StartTime = DateTime.Parse(curEvent.Eventdate.Value.ToShortDateString() + " " + curEvent.Starttime);
                        newGame.Venue = gameVenue;
                        newGame.GameType = gameType;
                        newGame.Active = !curEvent.Archived.HasValue ? false : !(bool)curEvent.Archived;
                        newGame.BuyIn = curEventGame.Playerentryfee != null ? (float)curEventGame.Playerentryfee : 0;

                        _aplGameRepo.Add(newGame);

                    }
                    else
                    {
                        object[] aplComparison = (object[])aplGameList[fhgEventId];
                        Guid aplGameId = Guid.Parse(aplComparison[0].ToString());
                        int aplfhgGameId = int.Parse(aplComparison[1].ToString());
                        Guid aplfhgGameUpdateVersion = Guid.Parse(aplComparison[2].ToString());
                        // Check for updates.
                        if (fhgUpdateVersion != aplfhgGameUpdateVersion)
                        {
                            Game aplGame = _aplGameRepo.FindBy(aplGameId);
                            EvtEvent curEvent = _fhgEventRepo.FindBy(fhgEventId);
                            EvtGame curEventGame = curEvent.EvtGame[0];
                            Venue gameVenue = _aplVenueRepo.FilterBy(x => x.FHGVenueId == curEvent.Orgentityid).FirstOrDefault();
                            GameType gameType = _aplGameTypeRepo.FilterBy(x => x.FhgDivisionId == curEventGame.Divisionid).FirstOrDefault();
                            aplGame.FHGEventId = fhgEventId;
                            aplGame.FHGUpdateVersion = curEvent.Updateversion;
                            aplGame.Description = (!string.IsNullOrEmpty(curEventGame.Gamedescription)) ? curEventGame.Gamedescription : curEvent.Eventdescription;
                            aplGame.GameDate = curEvent.Eventdate;
                            aplGame.Name = curEvent.Eventname;
                            aplGame.RegoTime = DateTime.Parse(curEvent.Eventdate.Value.ToShortDateString() + " " + curEvent.Registrationtime);
                            aplGame.StartTime = DateTime.Parse(curEvent.Eventdate.Value.ToShortDateString() + " " + curEvent.Starttime);
                            aplGame.Venue = gameVenue;
                            aplGame.GameType = gameType;
                            aplGame.Active = !curEvent.Archived.HasValue ? false : !(bool)curEvent.Archived;
                            aplGame.BuyIn = curEventGame.Playerentryfee != null ? (float)curEventGame.Playerentryfee : 0;

                            _aplGameRepo.Update(aplGame);

                        }
                    }
                }
                catch (Exception mException)
                {
                    int x = 1;
                }
                finally
                {
                    itemCount++;
                }
            }
        }
Example #19
0
        private User CheckToken(string token)
        {
            UnitOfWork unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
            Repository<Guid, User> userRepo = new Repository<Guid, User>(unitOfWork.Session);
            User check_user = userRepo.FilterBy(x => x.AuthToken == token).FirstOrDefault();
            if (check_user != null)
            {
                UserToken currentUt = null;

                if (check_user.AuthTokens.Count > 0)
                {
                    IList<UserToken> utList = check_user.AuthTokens;
                    foreach (UserToken ut in utList)
                    {
                        if (ut.Token == token)
                        {
                            currentUt = ut;
                            break;
                        }
                    }
                }

                if (currentUt != null)
                {
                    if (currentUt.ExpiryDate < DateTime.Now)
                    {
                        check_user.AuthTokens.Remove(currentUt);
                        check_user.AuthToken = null;
                        userRepo.Update(check_user);
                    }
                    else
                    {
                        check_user.AuthTokens.Remove(currentUt);
                        currentUt.LastUsedDate = DateTime.Now;
                        check_user.AuthTokens.Add(currentUt);
                        userRepo.Update(check_user);
                    }
                }
            }
            unitOfWork.Commit();
            return check_user;
        }
Example #20
0
        public string RegisterDevice(string token, string deviceType, string deviceId)
        {
            UnitOfWork unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));

            Repository<Guid, User> userRepo = new Repository<Guid, User>(unitOfWork.Session);

            JavaScriptSerializer js = new JavaScriptSerializer();
            JsonSerializerSettings j = new JsonSerializerSettings();
            j.TypeNameHandling = TypeNameHandling.Objects;
            j.Formatting = Newtonsoft.Json.Formatting.Indented;

            string responseString = null;
            Response response = new Response();

            user = CheckToken(token);
            if (user.AuthToken == null || user.AuthToken != token)
            {
                user.AuthToken = token;
                userRepo.Update(user);
            }

            if (!string.IsNullOrEmpty(user.AuthToken))
            {
                if (CheckToken(user.AuthToken) == null)
                {
                    user.AuthToken = null;
                }
            }

            if (user != null)
            {
                if (DEVICE_TYPES.Contains(deviceType.ToLower()))
                {
                    UserMobileDevice userMobileDevice = new UserMobileDevice();
                    Repository<Guid, UserMobileDevice> userMobileDevRepo = new Repository<Guid, UserMobileDevice>(unitOfWork.Session);
                    userMobileDevice = userMobileDevRepo.FilterBy(x => x.Token == deviceId).FirstOrDefault();
                    if (userMobileDevice != null && userMobileDevice.Id != Guid.Empty)
                    {
                        if (userMobileDevice.MobileDeviceType.ToLower() == deviceType.ToLower() && userMobileDevice.User.Id == user.Id)
                        {
                            response.ResponseCode = "OK";
                            response.ResponseData = "Device registered.";
                        }
                        else
                        {
                            response.ResponseCode = "ERR";
                            response.ResponseData = "Invalid device registration";
                        }

                    }
                    else
                    {
                        userMobileDevice = new UserMobileDevice();
                        userMobileDevice.MobileDeviceType = deviceType.ToLower();
                        userMobileDevice.Token = deviceId;
                        userMobileDevice.User = user;
                        userMobileDevice.EnablePushNotifications = true;
                        user.MobileDevices.Add(userMobileDevice);
                        userMobileDevRepo.Add(userMobileDevice);
                        response.ResponseCode = "OK";
                        response.ResponseData = "Device registered.";
                    }
                }
                else
                {
                    response.ResponseCode = "ERR";
                    response.ResponseData = "Unknown DeviceType";
                }

            }
            else
            {
                response.ResponseCode = "ERR";
                response.ResponseData = "Authentication required.";
            }
            unitOfWork.Commit();

            js = new JavaScriptSerializer();
            responseString = JsonConvert.SerializeObject(response, j);
            return responseString;
        }
Example #21
0
        public void SyncRegion()
        {
            ProgressUpdateArgs e = new ProgressUpdateArgs();
            // Region Table
            //
            // Select data from FHGLocal
            // Select data from Local DB
            // Compare and update/insert.

            _UnitOfWorkAPL = new UnitOfWork(_sessionHelper.GetSessionFactory("APL"));
            _UnitOfWorkFHG = new UnitOfWork(_sessionHelper.GetSessionFactory("FHG"));

            DataLayer.Repository<int, CusRegion> _fhgRegionRepo = new Repository<int, CusRegion>(_UnitOfWorkFHG.Session);
            Repository<Guid, Region> _aplRegionRepo = new Repository<Guid, Region>(_UnitOfWorkAPL.Session);
            Repository<Guid, State> _aplStateRepo = new Repository<Guid, State>(_UnitOfWorkAPL.Session);
            Repository<Guid, Brand> _aplBrandRepo = new Repository<Guid, Brand>(_UnitOfWorkAPL.Session);

            var regionAPLDB = _aplRegionRepo.All().ToList();
            var regionFHG = _fhgRegionRepo.All().ToList();
            int itemCount = 1;
            // Add Missing data
            foreach (CusRegion c in regionFHG)
            {
                e.TotalWorkItems = regionFHG.Count();
                e.CurrentWorkItem = itemCount;
                e.StatusString = "Syncing Regions - (" + itemCount.ToString() + "/" + e.TotalWorkItems.ToString() + ")";
                this.ProgressUpdate(e);

                bool found = false;
                foreach (Region s in regionAPLDB)
                {
                    if (s.Name == c.Regionname)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    Region r = new Region();
                    r.Name = c.Regionname;
                    r.Active = !c.Archived.HasValue ? false : !(bool)c.Archived;
                    r.State = _aplStateRepo.FilterBy(s => s.Name == c.CusState.Fullname).FirstOrDefault();
                    r.Brand = _aplBrandRepo.FilterBy(x => x.FhgBrandId == c.Brandid).FirstOrDefault();
                    _aplRegionRepo.Add(r);
                }
                itemCount++;
            }

            // Remove extra data.
            foreach (Region r in regionAPLDB)
            {
                bool found = false;
                foreach (CusRegion cr in regionFHG)
                {
                    if (r.Name == cr.Regionname)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    _aplRegionRepo.Delete(r);
                }
            }

            _UnitOfWorkAPL.Commit();
            _UnitOfWorkFHG.Commit();
        }