コード例 #1
0
        public AccessAttribute(params string[] permissions)
        {
            Membership.GetUser();

            _permissions = permissions;
            _session     = new MongoSession(MongoMembershipProvider.ConnectionString);
        }
コード例 #2
0
        public AccessAttribute(params string[] permissions)
        {
            Membership.GetUser();

            _permissions = permissions;
            _session = new MongoSession(MongoMembershipProvider.ConnectionString);
        }
コード例 #3
0
 //
 // GET: /SC/Question/Details/5
 public ActionResult Details(int id)
 {
     using (var s = new MongoSession())
     {
         return View(s.Query<Question>().Single(q => q.Number == id));
     }
 }
コード例 #4
0
        public static void InitializeRoles(Type r, string connectionString)
        {
            var session = new MongoSession(connectionString);
            List<MembershipRole> roles = new List<MembershipRole>();
            List<MembershipPermission> permissions = session.Permissions.ToList();
            List<string> dbRoles = session.Roles.Select(x => x.RoleName).ToList();

            foreach (FieldInfo field in r.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public))
            {
                string value = field.GetRawConstantValue().ToString();
                if (!dbRoles.Contains(value))
                {
                    MembershipRole role = new MembershipRole { RoleName = value };

                    if (value == DefaultRoles.Admin)
                    {
                        foreach (var p in permissions)
                        {
                            role.Permissions.Add(p.Name);
                        }
                    }

                    session.Save(role);
                }

            }
        }
コード例 #5
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        public IActionResult Radio([FromBody] Podcast podcast)
        {
            var session = new MongoSession <Podcast>();
            var name    = podcast.Name.ToLower().Trim();

            var pod = new Podcast();

            pod.Host     = "slovo.io";
            pod.Title    = podcast.Title;
            pod.Name     = CleanName(name);
            pod.Link     = "http://" + pod.Host + "/l/" + pod.Name;
            pod.Category = "Radio (NEW)";
            pod.Keywords = new List <string> {
                "radio"
            };
            pod.Podcasts = podcast.Podcasts;
            pod.Image    = podcast.Image;
            pod.PubDate  = Utils.ConvertToPubDate(DateTime.UtcNow);
            //pod.HumanId = podcast.HumanId;
            pod.HumanFullName     = podcast.HumanFullName;
            pod.HumanName         = podcast.HumanName;
            pod.HumanId           = podcast.HumanId;
            pod.CreationTimestamp = DateTime.UtcNow;
            //pod.BuildTimestamp = DateTime.UtcNow;
            pod.Author    = podcast.HumanName;
            pod.Copyright = podcast.HumanName;
            pod.Items     = new List <Item>();

            session.Save(pod);

            return(Json(pod));
        }
コード例 #6
0
ファイル: BugController.cs プロジェクト: Itslet/BugBase
        public ActionResult Create(Bug bug)
        {
            var BugSession = new MongoSession<Bug>();
            var UserSession = new MongoSession<User>();
            var ProjectSession = new MongoSession<BugProject>();

            var gebr = UserSession.Queryable.AsEnumerable();
            var bugpr = ProjectSession.Queryable.AsEnumerable();
            string id = "51495c0264489c9010010000";
            var bp = bugpr.Where(ps => ps.Id == (Norm.ObjectId)id).FirstOrDefault();

            var thisuser = UserSession.Queryable.AsEnumerable().Where(u => u.Email == User.Identity.Name).FirstOrDefault();

            bug.BugSubmitter = thisuser;
            bug.BugProject = bp;

            BugSession.Save(bug);

            if (Request.IsAjaxRequest())
            {
                return Json(bug);
            }

            return new RedirectResult("Create");
        }
コード例 #7
0
 public MembershipController(IRepository <Company> repository, IMembershipService membership, IRepository <UserPreference> preferences)
     : base(repository)
 {
     _membership  = membership;
     _preferences = preferences;
     _session     = new MongoSession(ConfigurationManager.ConnectionStrings["MongoServerSettings"].ConnectionString);
 }
コード例 #8
0
ファイル: BugController.cs プロジェクト: Itslet/BugBase
        //
        // GET: /Bug/
        public ActionResult Index(object id)
        {
            string identifier = id.ToString();
            var BugSession = new MongoSession<Bug>();
            try

            {
                var bugsies = BugSession.Queryable.AsEnumerable();
                var dezebugs = bugsies.Where(p => p.BugProject.Id == (Norm.ObjectId)identifier);
                var bug = bugsies.Where(p => p.BugProject.Id == (Norm.ObjectId)identifier).FirstOrDefault();

                ViewData["Name"] = bug.BugProject.ProjectName;

                int k = dezebugs.Count();

                if ( k != 0)
                {
                    return View(dezebugs);
                }
                else
                {
                    ViewData["Error"] = "No bugs submitted for this project";
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Error"] = "Error: " + ex.Message;
                return View();
            }
        }
コード例 #9
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        private Podcast UpdatePodcastItems(Podcast podcast, MongoSession <Podcast> session)
        {
            if (DateTime.UtcNow.Subtract(podcast.BuildTimestamp).TotalMinutes > 30)
            {
                var items = new List <Item>();
                if (podcast.Podcasts != null && podcast.Podcasts.Count > 0)
                {
                    var podcasts = new List <Podcast>();
                    var pods     = podcast.Podcasts.Select(pod => session.Get(_ => _.Id == pod).FirstOrDefault());
                    foreach (var pod in pods)
                    {
                        if (pod == null)
                        {
                            continue;
                        }
                        var p = UpdatePodcastItems(pod, session);
                        podcasts.Add(p);
                    }
                    // HACK
                    items = podcasts.SelectMany(p => p.Items).OrderByDescending(p => Utils.ConvertFromPubDate(p.PubDate)).ToList();
                }
                else
                {
                    items = Parsers.GetParser(podcast.Host).Parse(podcast.Link).Items;
                }

                podcast.Items          = items;
                podcast.BuildTimestamp = DateTime.UtcNow;
                session.Save(podcast);
            }

            return(podcast);
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
 public static User findUser(string email)
 {
     var UserSession = new MongoSession<User>();
     var users = UserSession.Queryable.AsEnumerable();
     User user = users.Where(u => u.Email == email).FirstOrDefault();
     return user;
 }
コード例 #11
0
ファイル: Utils.cs プロジェクト: nakedslavin/slovo
        public static string MediaUrlEncode(string url, string mime)
        {
            if (!url.Contains("&"))
            {
                return(url);
            }
            var hash   = MD5Hash(url);
            var client = new MongoSession <EnclosureLink>();
            var stored = client.Get(_ => _.ShortUrl == hash).FirstOrDefault();

            if (stored == null)
            {
                var linkObject = new EnclosureLink {
                    RealUrl = url, ShortUrl = hash
                };
                client.Save(linkObject);
                stored = linkObject;
            }
            string ext = ".mp3";

            if (mime == "audio/aac")
            {
                ext = ".aac";
            }
            if (mime == "audio/ogg")
            {
                ext = ".ogg";
            }

            var link = "http://slovo.io/a/" + stored.ShortUrl + ext;

            return(link);
        }
コード例 #12
0
        public static bool HasPermission(this IPrincipal user, params string[] currentPermissions)
        {
            var session    = new MongoSession(MongoMembershipProvider.ConnectionString);
            var userEntity = session.Users.FirstOrDefault(x => x.UserName == user.Identity.Name);

            return(AuthorizeHelper.CheckUser(userEntity, session.Roles, session.Permissions, currentPermissions));
        }
コード例 #13
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string companyId = null;

            if (!WebSecurity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
            if (Roles.IsUserInRole(RoleName.Admin))
            {
                companyId = (string)filterContext.HttpContext.Session[SessionKey.AdminCurrentCompany];
            }
            else
            {
                var session =
                    new MongoSession(ConfigurationManager.ConnectionStrings["MongoServerSettings"].ConnectionString);
                var user  = session.Users.Single(x => x.UserId == WebSecurity.CurrentUserId);
                var value = user.GetValue("Company", default(BsonString));
                companyId = value == null ? null : value.ToString();
            }

            if (companyId == null)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else
            {
                filterContext.RouteData.Values["companyId"] = companyId;
            }
        }
コード例 #14
0
ファイル: QuestionTest.cs プロジェクト: ningliaoyuan/Ant
        public void TestAddQuestion()
        {
            using (var s = new MongoSession())
            {
                Question q = new Question();
                q.Content = "ContentTest123";
                q.Ask = "Ask";
                q.Number = 100;
                q.Rate = 3;
                q.Source = "GWD";

                s.Add(q);
            }

            using (var s = new MongoSession())
            {
                var q2 = s.Query<Question>().FirstOrDefault(q=> q.Number==100);
                Assert.IsNotNull(q2);
                Assert.AreEqual(q2.Content, "ContentTest123");
            }
            using (var s = new MongoSession())
            {
                s.GetCollection<Question>().Delete(new { Number = 100 });
            }
            using (var s = new MongoSession())
            {
                var q2 = s.Query<Question>().FirstOrDefault(q => q.Number == 100);
                Assert.IsNull(q2);
            }
        }
コード例 #15
0
        public void Demonstrate_ComplexPersistance()
        {
            var patient = new Patient {
                FirstName = "John",
                LastName = "Doe",
                DateOfBirth = new DateTime(1980, 1, 1),
                Prescriptions = new List<Prescription> {
                    new Prescription {
                        DatePrescribed = DateTime.Now,
                        Medication = "Asprin",
                        Dosage = "200mg",
                        NumberOfRefils = 1000
                    }
                },
                Visits = new List<ProviderVisit> {
                    new ProviderVisit {
                        DateOfVisit = DateTime.Now,
                        ProviderName = "Townsville Healthcare",
                        ProviderNotes = "Patient is a pain in the arse."
                    }
                }
            };

            var session = new MongoSession();
            session.Save(patient);

            var fetched = session.Query<Patient>()
                .Where(x => x.LastName == "Doe");

            Assert.IsNotNull(fetched.First());
        }
コード例 #16
0
 public ActionResult Salvar(Usuario usuario)
 {
     using (var session = new MongoSession()) {
         session.Add(usuario);
     }
     return(View(usuario));
 }
コード例 #17
0
        public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager   = userManager;
            SignInManager = signInManager;

            sessionContractor = new MongoSession <Contractor>();
            sessionClient     = new MongoSession <Client>();
        }
コード例 #18
0
ファイル: FilialController.cs プロジェクト: xdougx/menufacil
 public ActionResult Salvar(Filial filial)
 {
     using (var session = new MongoSession())
     {
         session.Add(filial);
     }
     return(View(filial));
 }
コード例 #19
0
 public ActionResult Salvar(Preco preco)
 {
     using (var session = new MongoSession())
     {
         session.Add(preco);
     }
     return(View(preco));
 }
コード例 #20
0
ファイル: FilialController.cs プロジェクト: xdougx/menufacil
        public ActionResult Index()
        {
            using (var session = new MongoSession())
            {
                ViewBag.filiais = session.All <Filial>();
            }

            return(View());
        }
コード例 #21
0
        public ActionResult AgregarVoto(int id2)
        {
            var category = new Category {IdDestino = id2, Nickname = Session["data"] as string, Voto = "1"};

            using (var session = new MongoSession<Category>())
            {
                session.Save(category);
                return RedirectToAction("Index", "Destino", new { idViaje = Session["idViaje"] });
            }
        }
コード例 #22
0
 public MongoTab(MongoSession session) : base(session.ToString())
 {
     Session    = session;
     ImageIndex = (int)Session.Status.CurrentState;
     Controls.Add(new MongoSessionPanel(this));
     session.Status.StateChanged += () => Invoke((MethodInvoker) delegate
     {
         this.Text = session.ToString( );
     });
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
        public static bool Authenticate(string naam, string password)
        {
            var UserSession = new MongoSession<User>();
            var users = UserSession.Queryable.AsEnumerable();

            if (users.Where(u => u.UserName == naam && u.Password == password).Count() != 0)
            {
                return true;
            }
            else { return false; }
        }
コード例 #24
0
        public void CreateProfile(TEntity entity)
        {
            int userId = 0;

            using (var session = new MongoSession(_connectionString))
            {
                userId = session.GetNextSequence("user_id");
            }
            entity.UserId = userId;
            Save(entity);
        }
コード例 #25
0
        //=================================================================================
        //
        //  PUBLIC METHODS
        //
        //=================================================================================

        public void Add(MongoSession newSession)
        {
            var tab = new MongoTab(newSession);

            TabPages.Add(tab);
            SelectTab(tab);

            if (NumTabsChanged != null)
            {
                NumTabsChanged( );
            }
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
        public static void createMap()
        {
            Mapper.CreateMap<BugProject, ProjectViewModel>();

            var sessie = new MongoSession<BugProject>();
            var projects = sessie.Queryable.AsEnumerable();

            var theproject = projects.Where(p => p.ProjectName == "Example Project").First();
            var viewmodel = Mapper.Map<BugProject, ProjectViewModel>(theproject);

            System.Console.WriteLine(viewmodel.ProjectName + viewmodel.ProjectOwner.Email + viewmodel.Bugs.FirstOrDefault());
        }
コード例 #27
0
        public JsonResult GetUserName(string query)
        {
            var provider = new MongoSession();
            var role     = provider.Roles.ToList().FirstOrDefault(s => string.Equals(s.RoleName, "User", StringComparison.InvariantCultureIgnoreCase));
            var source   = provider.Users.Where(s => s.Roles.Contains(role));

            Func <MembershipAccount, bool> condition = n => n.UserName.Contains(query);
            var filteredSource = (from q in source.Where(condition)
                                  orderby q.CreationDate descending
                                  select q.UserName);

            return(Json(filteredSource.ToArray(), JsonRequestBehavior.AllowGet));
        }
コード例 #28
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
 public IActionResult Delete([FromBody] Podcast podcast)
 {
     if (!string.IsNullOrWhiteSpace(podcast.Id))
     {
         var session = new MongoSession <Podcast>();
         var stored  = session.Get(_ => _.Id == podcast.Id).FirstOrDefault();
         if (stored != null)
         {
             session.Delete(stored);
             return(new StatusCodeResult(200));
         }
     }
     return(new StatusCodeResult(400));
 }
コード例 #29
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        public IActionResult Audio(string fileName, string fileExtensionWithoutDot)
        {
            var client = new MongoSession <EnclosureLink>();
            var url    = client.Get(_ => _.ShortUrl == fileName).FirstOrDefault();

            if (url == null)
            {
                return(new StatusCodeResult(404));
            }
            else
            {
                var realUrl = url.RealUrl;
                return(Redirect(url.RealUrl));
            }
        }
コード例 #30
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
 // s
 public IActionResult Show(string id)
 {
     if (!string.IsNullOrWhiteSpace(id))
     {
         var session = new MongoSession <Podcast>();
         var podcast = session.Get(p => p.Name == id.ToLower().Trim()).FirstOrDefault();
         if (podcast == null)
         {
             return(new StatusCodeResult(404));
         }
         podcast = UpdatePodcastItems(podcast, session);
         return(Json(podcast));
     }
     return(new StatusCodeResult(200));
 }
コード例 #31
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        public IActionResult Send()
        {
            string note = null;

            using (var sr = new StreamReader(Request.Body))
                note = sr.ReadToEnd();
            if (!string.IsNullOrWhiteSpace(note) && note.Length > 5)
            {
                var msg = new Message();
                msg.Text = note;
                var session = new MongoSession <Message>();
                session.Save(msg);
            }
            return(new StatusCodeResult(200));
        }
コード例 #32
0
        public virtual void Save(TDomain entity)
        {
            var collection = GetDefaultCollection();

            if (entity.UserId == 0)
            {
                int userId  = 0;
                var session = new MongoSession(_connectionString);
                userId = session.GetNextSequence("user_id");

                entity.UserId = userId;
            }

            collection.Save(entity);
        }
コード例 #33
0
        public static void InitializePermissions(Type p, string connectionString)
        {
            var session = new MongoSession(connectionString);
            List<MembershipPermission> permissions = new List<MembershipPermission>();
            List<string> dbPermission = session.Permissions.Select(x => x.Name).ToList();

            foreach (FieldInfo field in p.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public))
            {
                string value = field.GetRawConstantValue().ToString();
                if (!dbPermission.Contains(value))
                {
                    session.Save(new MembershipPermission { Name = value });
                }
            }
        }
コード例 #34
0
        public static void SendEmail(string oldStat, string newStat, MongoSession session, DateTime date, string company,
                                     string note, string poNumber)
        {
            var isDisabled = (bool)new AppSettingsReader().GetValue("DisableEmailNotification", typeof(bool));

            if (isDisabled)
            {
                return;
            }

            if (oldStat != newStat)
            {
                var users  = session.Users;
                var emails = new List <string>();
                foreach (var user in users)
                {
                    emails.AddRange(from userrole in user.Roles where userrole.RoleName == "admin" select user.UserName);
                }

                try
                {
                    var subject = String.Format("{0} status has changed to {1}.", company,
                                                newStat);
                    var body = String.Format("Status change for {0} on {1}. Status changed from {2} to {3}. {4} ",
                                             company, date, oldStat, newStat, note);

                    if (string.IsNullOrWhiteSpace(poNumber))
                    {
                        body += System.Environment.NewLine + "No purchase order in customer portal for this company.";
                    }
                    else
                    {
                        body += System.Environment.NewLine + "PO #" + poNumber;
                    }


                    foreach (var email in emails)
                    {
                        WebMail.Send(email, subject, body);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
コード例 #35
0
        public void PutSession(string id, Session session)
        {
            var mongoSession = new MongoSession
            {
                SpeakerName  = session.SpeakerName,
                Bio          = session.Bio,
                Email        = session.Email,
                ProposalId   = session.ProposalId,
                Title        = session.Title,
                Description  = session.Description,
                Room         = session.Room,
                StandardTime = session.StandardTime,
                Break        = session.Break
            };

            sessionsCollection.PutSession(id, mongoSession);
        }
コード例 #36
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        public IActionResult List(string filter, string sort = "{_id : 1 }")
        {
            var podcasts = new List <Podcast>();
            var session  = new MongoSession <Podcast>();

            if (!string.IsNullOrWhiteSpace(filter))
            {
                podcasts = session.Get(filter, sort);
            }
            else
            {
                podcasts = session.Get(_ => true)
                           .OrderByDescending(_ => _.BuildTimestamp)
                           .ToList();
            }
            return(Json(podcasts));
        }
コード例 #37
0
ファイル: UnitPriceDAL.cs プロジェクト: acnice/purplebricks
        public List <UnitPrice> GetAllPrices()
        {
            using (var session = new MongoSession <UnitPrice>())
            {
                if (AllPrices != null && AllPrices.Count() > 0)
                {
                    return(AllPrices);
                }

                try
                {
                    var collection = session.FindAll <UnitPrice>();
                    AllPrices = collection.Find(new BsonDocument()).ToList();
                }
                catch (TimeoutException) { }
                return(AllPrices);
            }
        }
コード例 #38
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
        public static void initializeBugBase()
        {
            newUser("Jacqueline", "*****@*****.**", "12345");
            // User jp = findUser("*****@*****.**");

            //NIEUW BUGPROJECT
             User u = findUser("*****@*****.**");
             BugProject bp = newBugProject(u, "Example Project", "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam");

            //nieuwe bug

             Bug bug = new Bug();
             bug.BugProject = bp;
             bug.BugSubmitter = u;
             bug.Description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
             bug.Name = "Example name";

             var BugSession = new MongoSession<Bug>();
             BugSession.Save(bug);
        }
コード例 #39
0
        public JsonResult UserList(JQueryDataTableParamModel param, DateTimeRange periodtime, string keyword = "")
        {
            var provider = new MongoSession();
            var role     = provider.Roles.ToList().FirstOrDefault(s => string.Equals(s.RoleName, "User", StringComparison.InvariantCultureIgnoreCase));
            var source   = provider.Users.Where(s => s.Roles.Contains(role));

            //var all = Roles.GetUsersInRole("User");
            //var source = new List<MembershipUser>();
            //var provider = Membership.Provider as WebMatrix.WebData.ExtendedMembershipProvider;


            //foreach (var item in all)
            //{
            //    var user = provider.GetUser(item);
            //    source.Add(user);
            //}
            Func <MembershipAccount, bool> condition = n => Roles.IsUserInRole(n.UserName, "User") && (n.UserName.Contains(keyword) && (periodtime.GetDateTimeCondition(n)));

            var filteredSource = (from q in source.Where(condition)
                                  orderby q.CreationDate descending
                                  select q);

            var result = filteredSource.Skip(param.iDisplayStart).Take(param.iDisplayLength);

            return(Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = source.Count(),
                iTotalDisplayRecords = result.Count(),
                aaData = result.Select(s => new
                {
                    CheckBox = string.Format("<label><input name=\"sId\" value=\"{0}\" type=\"checkbox\" /><span class=\"lbl\"></span></label>", s.UserId),
                    Title = string.Format("<a title=\"编辑\" href=\"javascript:op.edit({0})\">{1}</a>", s.UserId, s.UserName),
                    Level = new UserLevelManager(s.UserId.ToString()).GetLevelName(),
                    UserId = s.UserId,
                    CreationDate = s.CreationDate.Value.ToString("yyyy/MM/dd HH:mm:ss"),
                    LastLoginDate = s.LastLoginDate.HasValue ? s.LastLoginDate.Value.ToString("yyyy/MM/dd HH:mm:ss") : "",
                    Operate = string.Format("<a href=\"/System/UrlList?u={0}\">短址</a> <a href=\"/System/WithdrawalsList?u={0}\">提现</a> <a href=\"/System/UserIntegral?u={0}\">积分</a>", s.UserName)
                })
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #40
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
        public IActionResult Index([FromBody] JObject obj)
        {
            var session = new MongoSession <Podcast>();

            var address  = obj["address"].ToString().Trim().TrimEnd('/');
            var name     = obj["name"].ToString().ToLower().Trim();
            var category = obj["category"].ToString();

            if (Uri.TryCreate(address, UriKind.Absolute, out Uri uri))
            {
                var     storedCasts = session.Get(p => p.Link == address || p.Name == name);
                Podcast podcast;
                if (storedCasts.Count != 0)
                {
                    podcast = storedCasts.First();
                }
                else
                {
                    string host = uri.Host;
                    if (uri.Host == "youtu.be" || uri.Host == "youtube.com")
                    {
                        host = "www.youtube.com";
                    }

                    podcast          = Parsers.GetParser(host).Parse(address);
                    podcast.Category = category;
                    podcast.Name     = CleanName(name);

                    session.Save(podcast);
                }

                //string xmlPodcast = XmlParser.Parse(podcast);
                return(Json(podcast));
            }
            else
            {
                return(Json(null));
            }
        }
コード例 #41
0
        public void AddUsersToRoles(string[] usernames, params Guid[] roleIds)
        {
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 256, "usernames");
            var session = new MongoSession(MongoMembershipProvider.ConnectionString);

            try
            {
                List<string> _usernames = usernames.ToList();
                List<Guid> _roleNames = roleIds.ToList();

                var users = (from u in session.Users
                             where _usernames.Contains(u.UserName)
                             select u).ToList();

                var roles = (from r in session.Roles
                             where _roleNames.Contains(r.RoleId)
                             select r).ToList();

                foreach (var userEntity in users)
                {
                    if (userEntity.Roles.Any())
                    {
                        var newRoles = roles.Except(userEntity.Roles);
                        userEntity.Roles.AddRange(newRoles);
                    }
                    else
                    {
                        userEntity.Roles.AddRange(roles);
                    }

                    session.Save(userEntity);
                }
            }
            catch
            {
                throw;
            }
        }
コード例 #42
0
 public ActionResult Create(Question q)
 {
     try
     {
         // TODO: Add insert logic here
         using (var s = new MongoSession())
         {
             q.Number = new IDProvider().GetNewID("Question");
             q.Info = new EntityInfo()
             {
                 CrTime = DateTime.Now,
                 CrUser = "******",
                 LastModified = DateTime.Now
             };
             s.Add(q);
         }
         return RedirectToAction("Index");
     }
     catch
     {
         return View();
     }
 }
コード例 #43
0
ファイル: HomeController.cs プロジェクト: nakedslavin/slovo
 public IActionResult Update([FromBody] Podcast podcast)
 {
     if (!string.IsNullOrWhiteSpace(podcast.Id))
     {
         var session = new MongoSession <Podcast>();
         var stored  = session.Get(_ => _.Id == podcast.Id).FirstOrDefault();
         if (stored != null)
         {
             stored.Name        = CleanName(podcast.Name);
             stored.Title       = podcast.Title;
             stored.Description = podcast.Description;
             stored.Copyright   = podcast.Copyright;
             stored.Author      = podcast.Author;
             stored.Link        = podcast.Link;
             stored.Image       = podcast.Image;
             stored.Language    = podcast.Language;
             stored.Category    = podcast.Category;
             session.Save(stored);
             return(new StatusCodeResult(200));
         }
     }
     return(new StatusCodeResult(400));
 }
コード例 #44
0
        public void Demonstrate_DbReference()
        {
            var session = new MongoSession();

            var supplier = new Supplier { Name = "Acme" };
            session.Save(supplier);

            var product = new Product {
                Name = "Shovel",
                Price = "17.50",
                Sku = "a3k4j22je9",
                Weight = "11",
                Supplier = new DbReference<Supplier>(supplier.Id)
            };
            session.Save(product);

            var fetched = session.Query<Product>().Where(x => x.Sku == product.Sku);

            Assert.AreEqual(fetched.First().Supplier.Id, supplier.Id);

            var fetchedSupplier = fetched.First().Supplier.Fetch(() => session.GetDb());

            Assert.AreEqual(fetchedSupplier.Name, supplier.Name);
        }
コード例 #45
0
        public void RemoveUsersFromRoles(string[] usernames, params Guid[] roleIds)
        {
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 256, "usernames");
            var session = new MongoSession(MongoMembershipProvider.ConnectionString);

            try
            {
                List<string> _usernames = usernames.ToList();
                List<Guid> _roleIds = roleIds.ToList();

                var users = (from u in session.Users
                             where _usernames.Contains(u.UserName)
                             select u).ToList();

                var roles = (from r in session.Roles
                             where _roleIds.Contains(r.RoleId)
                             select r).ToList();

                foreach (var userEntity in users)
                {
                    if (userEntity.Roles.Any())
                    {
                        int oldCount = userEntity.Roles.Count;
                        var matchedRoles = roles.Intersect(userEntity.Roles, new RoleComparer());

                        foreach (var matchedRole in matchedRoles)
                            userEntity.Roles.Remove(matchedRole);

                        if (oldCount != userEntity.Roles.Count)
                            session.Save(userEntity);
                    }
                }

            }
            catch
            {
                throw;
            }
        }
コード例 #46
0
 public MvcHtmlString YaHiceUnVoto(int idDestino)
 {
     using (var session = new MongoSession<Category>())
     {
         IQueryable<Category> categorias = session.Queryable
             .Where(c => c.Nickname == Session["data"] as string);
         foreach (var categoria in categorias)
         {
             if (categoria.IdDestino == idDestino)
                 return MvcHtmlString.Create("true");
         }
         return MvcHtmlString.Create("false");
     }
 }
コード例 #47
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
 public static IEnumerable<User> allUsers()
 {
     var BugSession = new MongoSession<User>();
     return BugSession.Queryable.AsEnumerable();
 }
コード例 #48
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
 public IEnumerable<Bug>allBugs()
 {
     var BugSession = new MongoSession<Bug>();
     return BugSession.Queryable.AsEnumerable();
 }
コード例 #49
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
 public static void newUser(string username, string mail, string passwd)
 {
     var UserSession = new MongoSession<User>();
     User b = new User();
     b.UserName = username;
     b.Email = mail;
     b.Password = passwd;
     UserSession.Save(b);
 }
コード例 #50
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
        public static BugProject newBugProject(User user, string projectname, string projectdescription)
        {
            var UserSession = new MongoSession<User>();
            var ProjectSession = new MongoSession<BugProject>();

            var test = Mapper.CreateMap<BugProject,User>();

            BugProject p = new BugProject();
            p.ProjectDescription = projectdescription;
            p.ProjectName = projectname;
            p.ProjectOwner = user;

            ProjectSession.Save(p);
            return p;
        }
コード例 #51
0
 public ClientController()
 {
     session     = new MongoSession <Client>();
     projSession = new MongoSession <Project>();
 }
コード例 #52
0
 static PermissionsProvider()
 {
     MinutesToRefreshCache = 5;
     _session = new MongoSession(MongoMembershipProvider.ConnectionString);
 }
コード例 #53
0
ファイル: Program.cs プロジェクト: Itslet/BugBase
        public static void newBug(string mail, string desc, string bugnaam)
        {
            var BugSession = new MongoSession<Bug>();
            var UserSession = new MongoSession<User>();

            var users = UserSession.Queryable.AsEnumerable();
            var thisuser = users.Where(u => u.Email == mail).FirstOrDefault();

            Bug myB = new Bug
            {
                Description = desc,
                Name = bugnaam,
                BugSubmitter = thisuser
            };
        }
コード例 #54
0
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = "MongoDbRoleProvider";
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "EazyRole Provider for MongoDb");
            }
            base.Initialize(name, config);

            bool.TryParse(config["useAppHarbor"], out _useAppHarbor);
            if (_useAppHarbor)
            {
                _connectionString =
                    ConfigurationManager.AppSettings.Get("MONGOHQ_URL") ??
                    ConfigurationManager.AppSettings.Get("MONGOLAB_URI");
            }

            if (string.IsNullOrEmpty(_connectionString))
            {
                string temp = config["connectionStringName"];
                if (string.IsNullOrEmpty(temp))
                    throw new ProviderException(StringResources.GetString(StringResources.Connection_name_not_specified));
                _connectionString = SecUtility.GetConnectionString(temp, true, true);

                if (string.IsNullOrEmpty(_connectionString))
                {
                    throw new ProviderException(StringResources.GetString(StringResources.Connection_string_not_found, temp));
                }
            }
            _session = new MongoSession(_connectionString);

            _AppName = config["applicationName"];

            if (string.IsNullOrEmpty(_AppName))
                _AppName = SecUtility.GetDefaultAppName();

            if (_AppName.Length > 256)
            {
                throw new ProviderException(StringResources.GetString(StringResources.Provider_application_name_too_long));
            }

            config.Remove("useAppHarbor");
            config.Remove("connectionStringName");
            config.Remove("applicationName");
            config.Remove("commandTimeout");

            if (config.Count > 0)
            {
                string attribUnrecognized = config.GetKey(0);
                if (!String.IsNullOrEmpty(attribUnrecognized))
                    throw new ProviderException(StringResources.GetString(StringResources.Provider_unrecognized_attribute, attribUnrecognized));
            }
        }
コード例 #55
0
ファイル: Program.cs プロジェクト: gaiverrr/TEDdownloader
        static void Main(string[] args)
        {
            //string connectionString = "mongodb://localhost/?safe=true";
            if (args.Length > 0)
            {
                if (Language.IsValidLanguageCode(args[0]))
                {
                    string languageCode = args[0];
                    string language;

                    if (languageCode == "all")
                        language = languageCode;
                    else
                        language = Language.GetLanguage(languageCode);

                    Console.WriteLine("Current language: {0}", language);
                    var pageList = new List<string>();

#if DEBUG
                    string directoryPath = Directory.GetCurrentDirectory();
                    using (StreamReader sr = new StreamReader(directoryPath + "/urls_test.txt", Encoding.UTF8))
                    {
                        string url;
                        while ((url = sr.ReadLine()) != null)
                        {
                            pageList.Add(url);
                        }
                    }
#else
                    pageList = GeneratePageList(languageCode);
                    //string directoryPath = Directory.GetCurrentDirectory();
                    //foreach (string str in pageList)
                    //{
                    //    using (StreamWriter sw = new StreamWriter(directoryPath + "/urls4.txt", true, Encoding.UTF8))
                    //    {
                    //        sw.Write(str);
                    //        sw.Write("\n");
                    //return;
                    
#endif
                    //MongoServer server = MongoServer.Create(connectionString);
                    //server.Connect();
                    //MongoDatabase db = server.GetDatabase("db");
                    //MongoCollection<string> employees = db.GetCollection<string>("test");

                    //MongoCollection<BsonDocument> books = db.GetCollection<BsonDocument>("test");
                    //BsonDocument book = new BsonDocument {
                    //    { "author", "Ernest Hemingway" },
                    //    { "title", "For Whom the Bell Tolls" }
                    //};
                    //books.Insert(book);



                    var vcList = new BlockingCollection<VideoClass>();
                    foreach (string url in pageList)
                    {
                        vcList.Add(new VideoClass(url, languageCode));
                    }


                    var session = new MongoSession();

                    //var categories = session.All<VideoClass>().AsEnumerable();
                    //foreach (var videoClass in categories)
                    //{
                    //    Console.WriteLine(videoClass.ToString());
                    //}



                    var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism = 10};

                    Parallel.ForEach(vcList, parallelOptions, video =>
                    {
                        Console.WriteLine("GetInformation()");
                        video.GetInformation();
                        var bd = new BsonDocument();
                        bd = video.ToBsonDocument();
                            
                        if (!video.IsNull())
                        {
                            video.SaveSrtToFile(@"\srt\");
                            video.SaveDownloadLinkToFile(@".\srt\");

                            /*                            session.DeleteAll<VideoClass>();

                                                        session.Save<VideoClass>(video);
                                                        using (var db = Norm.Mongo.Create("mongodb://localhost/test"))
                                                        {
                                                            //var vc = db.GetCollection<VideoClass>().AsQueryable().ToList();
                                                            categories = session.All<VideoClass>().AsEnumerable();


                                                            //foreach (var videoclass in vc.

                                                        }
                           

                                                        List<VideoClass> ls = new List<VideoClass>();
                                                        ls = db.GetCollection<VideoClass>().Find();
                                                        ls = db.GetCollection<VideoClass>().AsQueryable()
                                                            .Where(vd => vd.DownloadLink == video.DownloadLink)
                                                            .ToList();
                            */
                        }
                        else
                        {
                            ErrorVideoList.Add(video);
                            _countOfErrors++;

                            using (var sw = new StreamWriter("ErrorList.txt", true, Encoding.UTF8))
                            {
                                lock (sw)
                                {
                                    sw.Write(video.Url);
                                    sw.Write("\n");
                                }
                            }
                            Console.WriteLine("Empty object");
                        }
                    });

                    if (ErrorVideoList.Count > 0)
                    {
                        foreach (VideoClass video in ErrorVideoList)
                        {
                            video.GetInformation();

                            if (!video.IsNull())
                            {
                                video.SaveSrtToFile(@"\srt\");
                                video.SaveDownloadLinkToFile(@".\srt\");
                            }
                        }
                    }

                }
                else
                {
                    Console.WriteLine("Didn't find language, please input code language in correct format \n");
                    Console.WriteLine("You can find all languages codes on page: http://www.ted.com/pages/view/id/286");
                }

                Console.WriteLine("Count of errors: {0}", _countOfErrors);
                Console.WriteLine("Finished. Press any key.");
                Console.ReadKey(true);
                return;
            }
            else
            {
                Console.WriteLine("Please launch application with language code parametr");
                Console.ReadKey(true);
                return;
            }

            //This is main case for save content to mongo repository
            //------------------------------------------------------------------------------------------------------------------------------            
            //RepositoryClass repository = new RepositoryClass();
            //repository.Db();

        }
コード例 #56
0
 private IEnumerable<string> GetCollectionNames(MongoLinqpadProperties props)
 {
     var session = new MongoSession(props.ConnectionString);
     return session.GetCollectionNames();
 }
コード例 #57
0
 public ContractorController()
 {
     session = new MongoSession <Contractor>();
 }
コード例 #58
0
 public static bool HasPermission(this IPrincipal user, params string[] currentPermissions)
 {
     var session = new MongoSession(MongoMembershipProvider.ConnectionString);
     var userEntity = session.Users.FirstOrDefault(x => x.UserName == user.Identity.Name);
     return AuthorizeHelper.CheckUser(userEntity, session.Roles, session.Permissions, currentPermissions);
 }
コード例 #59
0
        static void QueryTest()
        {
            var session = new MongoSession(_connectionString) as IMongoSession;
            var col_q = session.AsQuerable<TestData>();
            //var server = MongoServer.Create(_connectionString);
            //var db = server.GetDatabase("common");
            //var col = db.GetCollection<TestData>("TestData", SafeMode.False);
            //var col_q = col.AsQueryable<TestData>();

            //var query = from d in col_q where d.Timestamp > DateTime.Parse("2012-3-1") select d;
            //var query = from d in col_q where d.InnerData.IntData >= 4 select d;
            //var query = from d in col_q where d.InnerData.BoolList[0] == true && d.InnerData.BoolList[1] == false select d;
            //var query = from d in col_q where d.IntData < 10 && d.InnerData.BoolList[0] == true && d.InnerData.BoolList[1] == false select d;
            var query = from d in col_q where d.IntData < 10 && d.InnerData.BoolList[0] == true && Query.EQ("InnerData.BoolList.1", false).Inject() select d;
            //var query = from d in col_q where d.DecimalData > 6.0m select d;  // decimals stored as strings in mongo, so can't query on them
            //var query = from d in col_q where d.InnerData.BoolList.Contains(true) select d;
            //var query = from d in col_q where d.IntData == 7 && d.InnerData.BoolList.Contains(true) select d;

            var mq = (MongoQueryable<TestData>)query;
            var imq = mq.GetMongoQuery();
            var mongoQueryStr = imq.ToString();

            var q2 = query.MongoQueryStr();

            PrintQueryResults(query);
        }
コード例 #60
0
        static void AddTestData()
        {
            var session = new MongoSession(_connectionString) as IMongoSession;
            var db = session.Server.GetDatabase("common");
            var col = db.GetCollection<TestData>("TestData");

            var t = new TestData
            {
                BoolData = true,
                DecimalData = 3.50m,
                DoubleData = 5.50,
                IntData = 7,
                LongData = 9,
                StringData = "one",
                Timestamp = DateTime.Parse("2012-3-1"),
                InnerData = new InnerData
                {
                    IntData = 2,
                    StringData = "a",
                    BoolList = new List<bool>() { true, false }
                },
                DynamicProps = new BsonDocument().Add("Name", "John").Add("Age", 23)
            };

            col.Insert<TestData>(t);

            t = new TestData
            {
                BoolData = true,
                DecimalData = 4.50m,
                DoubleData = 6.50,
                IntData = 8,
                LongData = 10,
                StringData = "one",
                Timestamp = DateTime.Parse("2012-3-1"),
                InnerData = new InnerData
                {
                    IntData = 3,
                    StringData = "b",
                    BoolList = new List<bool>() { true, true }
                }
            };

            col.Insert<TestData>(t);

            t = new TestData
            {
                BoolData = false,
                DecimalData = 5.50m,
                DoubleData = 7.50,
                IntData = 9,
                LongData = 11,
                StringData = "two",
                Timestamp = DateTime.Parse("2012-3-2"),
                InnerData = new InnerData
                {
                    IntData = 4,
                    StringData = "c",
                    BoolList = new List<bool>() { false, false }
                }
            };

            col.Insert<TestData>(t);

            t = new TestData
            {
                BoolData = false,
                DecimalData = 6.50m,
                DoubleData = 8.50,
                IntData = 10,
                LongData = 12,
                StringData = "two",
                Timestamp = DateTime.Parse("2012-3-2"),
                InnerData = new InnerData
                {
                    IntData = 4,
                    StringData = "c",
                    BoolList = new List<bool>() { true, true }
                }
            };

            col.Insert<TestData>(t);

            t = new TestData
            {
                BoolData = true,
                DecimalData = 13.50m,
                DoubleData = 15.50,
                IntData = 17,
                LongData = 19,
                StringData = "three",
                Timestamp = DateTime.Parse("2012-3-3"),
                InnerData = new InnerData
                {
                    IntData = 12,
                    StringData = "aa",
                    BoolList = new List<bool>() { true, false }
                }
            };

            col.Insert<TestData>(t);

            t = new TestData
            {
                BoolData = true,
                DecimalData = 23.50m,
                DoubleData = 25.50,
                IntData = 27,
                LongData = 29,
                StringData = "three",
                Timestamp = DateTime.Parse("2012-3-4"),
                InnerData = new InnerData
                {
                    IntData = 22,
                    StringData = "bb",
                    BoolList = new List<bool>() { false, false }
                },
                DynamicProps = new BsonDocument().Add("Name", "Jane").Add("Age", 28)

            };

            col.Insert<TestData>(t);
        }