Ejemplo n.º 1
0
        /// <summary>
        /// Gets the query.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="selector">The selector.</param>
        /// <returns></returns>
        private static ISequoiaQuery GetQuery <T>(DBCollection <T> collection, Expression <Func <T, bool> > selector) where T : class
        {
            var query      = collection.AsQueryable <T>().Where(selector);
            var mongoQuery = ((SequoiaQueryable <T>)query).GetMongoQuery();

            return(mongoQuery);
        }
Ejemplo n.º 2
0
 public TeachersManagementWindow()
 {
     InitializeComponent();
     SubjectsList = (DBCollection)Resources["SubjectsList"];
     DepartmentsList = (DBCollection)Resources["DepartmentsList"];
     Title = "Добавить преподавателя";
 }
Ejemplo n.º 3
0
        public ActionResult approveday(string selectedday)
        {
            DateTime day = DateTime.ParseExact(selectedday, "yyyyMMdd", CultureInfo.InvariantCulture);

            day = new DateTime(day.Year, day.Month, day.Day, day.Hour, day.Minute, day.Second, DateTimeKind.Utc);

            var query = new DBQuery("workentries", "unacceptedentrydata");

            query.AddParameter("start", day);
            query.AddParameter("end", day);
            query.AddParameter("user", new ObjectId(Runtime.SessionManager.CurrentUser[DBQuery.Id]));

            DBResponse response = query.Find();

            DBCollection timesheetEntries = response["timesheetentry"];
            DBCollection abseneceEntries  = response["absenceentry"];
            DBCollection dayEntries       = response["dayentry"];
            DBCollection articleEntries   = response["articleentry"];
            DBCollection assetEntries     = response["assetentry"];

            var tasks = new List <Task <DBUpdateResponse> >();

            tasks.Add(ApproveEntriesInCollection(timesheetEntries));
            tasks.Add(ApproveEntriesInCollection(abseneceEntries));
            tasks.Add(ApproveEntriesInCollection(dayEntries));
            tasks.Add(ApproveEntriesInCollection(articleEntries));
            tasks.Add(ApproveEntriesInCollection(assetEntries));

            Task.WaitAll(tasks.ToArray());

            return(new AjaxResult("success"));
        }
Ejemplo n.º 4
0
        public static void LoadDatabase()
        {
            Task.Run(() =>
            {
                Session = new Session(SessionMode.Users, @".\Data\")
                {
                    BackUp = false
                };

                Globals.ItemInfoList           = Session.GetCollection <ItemInfo>();
                Globals.MagicInfoList          = Session.GetCollection <MagicInfo>();
                Globals.MapInfoList            = Session.GetCollection <MapInfo>();
                Globals.NPCPageList            = Session.GetCollection <NPCPage>();
                Globals.MonsterInfoList        = Session.GetCollection <MonsterInfo>();
                Globals.StoreInfoList          = Session.GetCollection <StoreInfo>();
                Globals.NPCInfoList            = Session.GetCollection <NPCInfo>();
                Globals.MovementInfoList       = Session.GetCollection <MovementInfo>();
                Globals.QuestInfoList          = Session.GetCollection <QuestInfo>();
                Globals.QuestTaskList          = Session.GetCollection <QuestTask>();
                Globals.CompanionInfoList      = Session.GetCollection <CompanionInfo>();
                Globals.CompanionLevelInfoList = Session.GetCollection <CompanionLevelInfo>();

                KeyBinds       = Session.GetCollection <KeyBindInfo>();
                WindowSettings = Session.GetCollection <WindowSetting>();
                CastleInfoList = Session.GetCollection <CastleInfo>();

                Globals.GoldInfo = Globals.ItemInfoList.Binding.FirstOrDefault(x => x.Effect == ItemEffect.Gold);

                CheckKeyBinds();

                Loaded = true;
            });
        }
Ejemplo n.º 5
0
        static void FindTotalNumRecords(DBCollection dbc)
        {
            BsonDocument condition = new BsonDocument();

            Console.WriteLine("Get total number of records for collection");
            Common.GetCount(dbc, condition);
        }
Ejemplo n.º 6
0
        static void FindRangeRecords(DBCollection dbc)
        {
            DBQuery query = new DBQuery();

            try
            {
                BsonDocument condition = new BsonDocument
                {
                    { "Id",
                      new BsonDocument
                      {
                          { "$gte", 25 },
                          { "$lte", 30 }
                      } }
                };

                query.Matcher = condition;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create range record query condition");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Find range records from collection");
            Common.FindRecord(dbc, query);
        }
Ejemplo n.º 7
0
        static void BullInsertTest(DBCollection cl)
        {
            int times    = 1;
            int bulkSize = 5000;

            for (int i = 0; i < times; i++)
            {
                List <BsonDocument> list = new List <BsonDocument>(bulkSize);
                for (int j = 0; j < bulkSize; j++)
                {
                    BsonDocument obj = new BsonDocument();
                    obj.Add("bbs", "725").
                    Add("csbh", 1817).
                    Add("cljg", "工作状态").
                    Add("sjym", "79H").
                    Add("wxbs", "WX1558").
                    Add("dmzbs", "DMZ2206").
                    Add("cxbz", 0).
                    Add("sjsj", new DateTime()).
                    Add("rksj", new DateTime());
                    list.Add(obj);
                }
                DateTime beginTime = DateTime.Now;
                cl.BulkInsert(list, 0);
                DateTime        endTime = DateTime.Now;
                System.TimeSpan takes   = endTime - beginTime;
                Console.WriteLine(String.Format("Times: {0}, tasks: {1}ms", i, takes.TotalMilliseconds));
            }
        }
Ejemplo n.º 8
0
        static void GetNumofRowsCondition(DBCollection dbc)
        {
            BsonDocument condition = null;

            try
            {
                condition = new BsonDocument
                {
                    { "Id",
                      new BsonDocument
                      {
                          { "$gte", 50 },
                          { "$lte", 70 }
                      } }
                };
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create query condition");
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Get count for query");
            Common.GetCount(dbc, condition);
        }
Ejemplo n.º 9
0
        // create collection, if the collection exists then return
        public static DBCollection CreateColleciton(CollectionSpace cs, string cName)
        {
            DBCollection dbc = null;

            try
            {
                dbc = cs.CreateCollection(cName);
            }
            catch (BaseException e)
            {
                // verify whether the collection space exists
                if ("SDB_DMS_CS_NOTEXIST" == e.ErrorType)
                {
                    cs  = CreateCollecitonSpace(cs.SequoiaDB, cs.Name);
                    dbc = CreateColleciton(cs, cName);
                }
                // verify whether the collection space exists
                else if ("SDB_DMS_EXIST" == e.ErrorType)
                {
                    dbc = GetColleciton(cs, cName);
                }
                else
                {
                    Console.WriteLine("Failed to create collection {0},ErrorType = {1}", cName, e.ErrorType);
                    Environment.Exit(0);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            return(dbc);
        }
Ejemplo n.º 10
0
        public static void FindRecord(DBCollection dbc, BsonDocument query, BsonDocument selector, BsonDocument orderBy,
                                      BsonDocument hint, long skip, long numReturn)
        {
            try
            {
                // find specific records from collection with rules
                DBCursor cursor = dbc.Query(query, selector, orderBy, hint, skip, numReturn);

                Console.WriteLine("Record read:");
                while (cursor.Next() != null)
                {
                    Console.WriteLine(cursor.Current().ToString());
                }
            }
            catch (BaseException e)
            {
                Console.WriteLine("Failed to find records from collection, ErrorType = {0}", e.ErrorType);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }
        }
Ejemplo n.º 11
0
        public void ConnectWithSSLTest()
        {
            ConfigOptions   cfgOpt = null;
            CollectionSpace cs2    = null;
            DBCollection    coll2  = null;
            Sequoiadb       sdb2   = new Sequoiadb(config.conf.Coord.Address);

            System.Console.WriteLine(config.conf.Coord.Address.ToString());

            // set connect using ssl
            cfgOpt        = new ConfigOptions();
            cfgOpt.UseSSL = true;

            // connect to database
            sdb2.Connect("", "", cfgOpt);
            if (true == sdb2.IsCollectionSpaceExist("testSSL"))
            {
                cs2 = sdb2.GetCollecitonSpace("testSSL");
            }
            else
            {
                cs2 = sdb2.CreateCollectionSpace("testSSL");
            }
            if (true == cs2.IsCollectionExist("testSSL"))
            {
                coll2 = cs2.GetCollection("testSSL");
            }
            else
            {
                coll2 = cs2.CreateCollection("testSSL");
            }

            sdb2.DropCollectionSpace("testSSL");
        }
Ejemplo n.º 12
0
        public void MyTestInitialize()
        {
            csArr[0]  = csName1;
            csArr[1]  = csName2;
            csArr[2]  = csName3;
            clArr1[0] = clName1_1;
            clArr1[1] = clName1_2;
            clArr1[2] = clName1_3;
            clArr2[0] = clName2_1;
            clArr2[1] = clName2_2;
            clArr2[2] = clName2_3;
            clArr3[0] = clName3_1;
            clArr3[1] = clName3_2;
            clArr3[2] = clName3_3;
            sdb       = new Sequoiadb(config.conf.Coord.Address);
            sdb.Connect(config.conf.UserName, config.conf.Password);
            BsonDocument options = new BsonDocument();

            options.Add("ReplSize", 0);
            if (sdb.IsCollectionSpaceExist(csName))
            {
                sdb.DropCollectionSpace(csName);
            }
            cs   = sdb.CreateCollectionSpace(csName);
            coll = cs.CreateCollection(cName, options);
        }
 public StudentsGroupsManagementWindow(studentsgroup s)
 {
     InitializeComponent();
     cur = s;
     Title = "Изменить группу";
     NameTextBox.Text = s.Name;
     CourseTextBox.Text = s.Course.ToString();
     DateInPicker.SelectedDate = s.DateIn;
     DateOutPicker.SelectedDate = s.DateOut;
     InitFaculties();
     int idx = FacultiesComboBox.Items.IndexOf(s.department.faculty.Name);
     if (idx >= 0)
         FacultiesComboBox.SelectedIndex = idx;
     idx = DepartmentsComboBox.Items.IndexOf(s.department.Name);
     if (idx >= 0)
         DepartmentsComboBox.SelectedIndex = idx;
     SubjectList = (DBCollection)Resources["SubjectList"];
     try
     {
         List<dynamic> lst = DBModel.Instance.GetSubjectsByGroupDynamic(cur.Name);
         foreach (var i in lst)
             SubjectList.Add(i);
     }
     catch (DBException ex)
     {
         Message.Show(ex.Message, MessageTypes.Error);
     }
     IsEdit = true;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Updates the selectorified collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="updater">The updater.</param>
        /// <param name="selector">The selector.</param>
        public static void Update <T>(this DBCollection <T> collection, Expression <Func <T, T> > updater, Expression <Func <T, bool> > selector) where T : class
        {
            Dictionary <string, object> KV = new Dictionary <string, object>();

            #region //获取Update的赋值语句。

            var updateMemberExpr = (MemberInitExpression)updater.Body;
            var updateMembers    = updateMemberExpr.Bindings.Cast <MemberAssignment>();
            foreach (var item in updateMembers)
            {
                string name  = item.Member.Name;
                var    value = Expression.Lambda(item.Expression).Compile().DynamicInvoke();
                if (!string.IsNullOrEmpty(name))
                {
                    KV.Add(name, value);
                }
            }

            #endregion

            var          wrapper  = new UpdateDocument(KV);
            BsonDocument modifier = new BsonDocument();
            modifier.Add("$set", (BsonDocument)wrapper);
            var mongoQuery = GetQuery(collection, selector);
            collection.Update((BsonDocument)mongoQuery, modifier, new BsonDocument());
        }
Ejemplo n.º 15
0
        public void AddFriend(string Username, string FriendUsername)
        {
            DBCollection dbc = new DBCollection();

            dbc.AddFriend(Username, FriendUsername);
            Console.WriteLine();
            Console.WriteLine("AddFriend() " + GetExecutionThreadTime());
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DBIndex"/> class.
 /// </summary>
 /// <param name="collection">The collection.</param>
 /// <param name="indexUri">The index URI.</param>
 /// <param name="indexKeyFieldSet">The index key field set.</param>
 /// <param name="unique">if set to <c>true</c> [unique].</param>
 public DBIndex(DBCollection collection, Uri indexUri, DBFieldSet indexKeyFieldSet, bool unique)
 {
     Collection = collection;
     Uri relative = indexUri.IsAbsoluteUri ? indexUri.MakeRelativeUri(collection.Uri) : indexUri;
     Uri = new Uri(new Uri(collection.Uri.ToString() + "/"), relative);
     KeyFieldSet = indexKeyFieldSet;
     Unique = unique;
 }
 public StudentsGroupsManagementWindow()
 {
     InitializeComponent();
     InitFaculties();
     cur = new studentsgroup();
     SubjectList = (DBCollection)Resources["SubjectList"];
     Title = "Добавить группу";
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the MongoQueryProvider class.
 /// </summary>
 /// <param name="collection">The collection being queried.</param>
 public SequoiaQueryProvider(DBCollection collection)
 {
     if (collection == null)
     {
         throw new ArgumentNullException("collection");
     }
     _collection = collection;
 }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Please give the database server address <IP:Port>");
                Environment.Exit(0);
            }

            // The database server address
            string sdbIP = args[0];
            // The collection space name
            string csName = "SAMPLE";
            // The collection name
            string cName = "employee";

            BsonDocument insertor1 = CreateEnglisthRecord();
            BsonDocument insertor2 = CreateChineseRecord();

            Sequoiadb sdb = new Sequoiadb(sdbIP);

            Common.Connect(sdb);
            CollectionSpace cs  = Common.GetCollecitonSpace(sdb, csName);
            DBCollection    dbc = Common.GetColleciton(cs, cName);

            try
            {
                ObjectId id = dbc.Insert(insertor1);
                Console.WriteLine("Successfully inserted english records, object ID = {0}", id.ToString());
            }
            catch (BaseException e)
            {
                Console.WriteLine("Failed to insert english record, ErrorType = {0}", e.ErrorType);
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            try
            {
                ObjectId id = dbc.Insert(insertor2);
                Console.WriteLine("Successfully inserted chinese records, object ID = {0}", id.ToString());
            }
            catch (BaseException e)
            {
                Console.WriteLine("Failed to insert chinese record, ErrorType = {0}", e.ErrorType);
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            Common.Disconnect(sdb);
        }
Ejemplo n.º 20
0
        private async Task <bool> CopyEntriesToDay(DBCollection collection, DateTime targetDay)
        {
            if (collection.Count == 0)
            {
                return(false);
            }

            var newCollection = new DBCollection(new DataTree(collection.Name));

            var somethingFiltered = false;

            foreach (DBDocument doc in collection)
            {
                // Remove id to make as new
                doc[DBDocument.Id].Remove();

                // Remove timestamps, they will be applied automatically based on date
                doc["starttimestamp"].Remove();
                doc["endtimestamp"].Remove();

                // Remove approval and export data. All pasted entries must be approved again.
                doc["approvedbymanager"]     = false;
                doc["approvedbyworker"]      = false;
                doc["exported_ax"]           = false;
                doc["exportfailurecount_ax"] = 0;
                doc["exporttimestamp_ax"].Remove();
                doc["exported_visma"] = false;
                doc["exporttimestamp_visma"].Remove();

                // Set target date
                doc["date"] = targetDay;

                bool filtered = false;
                if (!doc["project"].Empty)
                {
                    var project = DBDocument.FindOne("project", doc["project"][DBDocument.Id]);
                    if (project != null && project["status"] == "Done")
                    {
                        filtered          = true;
                        somethingFiltered = true;
                    }
                }


                if (!filtered)
                {
                    newCollection.Add(doc);
                }
            }

            await newCollection.UpdateDatabaseAsync(new DBCallProperties()
            {
                RunWithPrivileges = 5
            });

            return(somethingFiltered);
        }
Ejemplo n.º 21
0
        public DataSet GetEggs(string Username)
        {
            DBCollection dbc = new DBCollection();
            DataSet      ds  = dbc.GetEggs(Username);

            Console.WriteLine();
            Console.WriteLine("GetEggs() " + GetExecutionThreadTime());
            return(ds);
        }
Ejemplo n.º 22
0
        public void InsertCollection(string Username, string Id)
        {
            DBCollection dbc = new DBCollection();

            dbc.InsertCollection(Username, Int32.Parse(Id));

            Console.WriteLine();
            Console.WriteLine("InsertCollection() " + GetExecutionThreadTime());
        }
Ejemplo n.º 23
0
 public ChooseSubjectsWindow(DBCollection subjects)
 {
     InitializeComponent();
     SelectedSubjects = new DBCollection();
     SubjectsList = SubjectsControl.GeneralList;
     SubjectsControl.AddGridColumns(ConfigureGridColumns());
     SubjectsControl.SearchTextChanged += SearchSubject;
     SubjectsControl.ConfigureUpdateMethod(DBModel.Instance.GetAllSubjects);
     SubjectsControl.ConfigureCurrentItems(subjects);
     UpdateSubjects();
 }
Ejemplo n.º 24
0
 public void MyTestInitialize()
 {
     sdb = new Sequoiadb(config.conf.Coord.Address);
     sdb.Connect(config.conf.UserName, config.conf.Password);
     if (sdb.IsCollectionSpaceExist(csName))
     {
         sdb.DropCollectionSpace(csName);
     }
     cs   = sdb.CreateCollectionSpace(csName);
     coll = cs.CreateCollection(cName);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// This method initializes the database and collection using the connection string provided
        /// in the app.config
        /// </summary>
        private void InitalizeDatabaseAndCollection()
        {
            string conectionString = ConfigurationManager.AppSettings["ConnectionString"];
            string collection      = ConfigurationManager.AppSettings["CollectionName"];

            // Initialize an instance of the database to begin performing operations:
            _database = NosDB.Client.NosDBClient.GetDatabase(conectionString);

            // Get an instance of the 'Products' collection from the database:
            _productsCollection = _database.GetDBCollection <Product>(collection);
        }
Ejemplo n.º 26
0
 public LibrariansTab()
 {
     InitializeComponent();
     LibrariansList = LibrariansControl.GeneralList;
     LibrariansControl.AddGridColumns(ConfigureGridColumns());
     LibrariansControl.AddButtonClick += AddLibrarianButton_Click;
     LibrariansControl.EditButtonClick += EditLibrarianButton_Click;
     LibrariansControl.DeleteButtonClick += DeleteLibrarianButton_Click;
     LibrariansControl.SearchTextChanged += SearchLibrarian;
     LibrariansControl.ConfigureUpdateMethod(DBModel.Instance.GetAllLibrarians);
     UpdateLibrarians();
 }
Ejemplo n.º 27
0
        /**
         * Creates a GridFS instance for the specified bucket
         * in the given database.
         *
         * @param db database to work with
         * @param bucket bucket to use in the given database
         */
        public GridFS(DB db, string bucket)
        {
            _db = db;
            _bucketName = bucket;

            _filesCollection = _db.getCollection(_bucketName + ".files");
            _chunkCollection = _db.getCollection(_bucketName + ".chunks");

            _chunkCollection.ensureIndex(BasicDBObjectBuilder.start().Add("files_id", 1).Add("n", 1).get());

            _filesCollection.setObjectClass(typeof(GridFSDBFile));
        }
Ejemplo n.º 28
0
 public SubjectsTab()
 {
     InitializeComponent();
     SubjectsList = SubjectsControl.GeneralList;
     SubjectsControl.AddGridColumns(ConfigureGridColumns());
     SubjectsControl.AddButtonClick += AddSubjectButton_Click;
     SubjectsControl.EditButtonClick += EditSubjectButton_Click;
     SubjectsControl.DeleteButtonClick += DeleteSubjectButton_Click;
     SubjectsControl.SearchTextChanged += SearchSubject;
     SubjectsControl.ConfigureUpdateMethod(DBModel.Instance.GetAllSubjects);
     UpdateSubjects();
 }
Ejemplo n.º 29
0
 public DepartmentsTab()
 {
     InitializeComponent();
     DepartmentsList = DepartmentsControl.GeneralList;
     DepartmentsControl.AddGridColumns(ConfigureGridColumns());
     DepartmentsControl.AddButtonClick += AddDepartmentButton_Click;
     DepartmentsControl.EditButtonClick += EditDepartmentButton_Click;
     DepartmentsControl.DeleteButtonClick += DeleteDepartmentButton_Click;
     DepartmentsControl.SearchTextChanged += SearchDepartment;
     DepartmentsControl.ConfigureUpdateMethod(DBModel.Instance.GetAllDepartments);
     UpdateDepartments();
 }
Ejemplo n.º 30
0
 public TeachersTab()
 {
     InitializeComponent();
     TeachersList = TeachersControl.GeneralList;
     TeachersControl.AddGridColumns(ConfigureGridColumns());
     TeachersControl.AddButtonClick += AddTeacherButton_Click;
     TeachersControl.EditButtonClick += EditTeacherButton_Click;
     TeachersControl.DeleteButtonClick += DeleteTeacherButton_Click;
     TeachersControl.SearchTextChanged += SearchTeacher;
     TeachersControl.ConfigureUpdateMethod(DBModel.Instance.GetAllTeachers);
     UpdateTeachers();
 }
Ejemplo n.º 31
0
 public FacultiesTab()
 {
     InitializeComponent();
     FacultiesList = FacultiesControl.GeneralList;
     FacultiesControl.AddGridColumns(ConfigureGridColumns());
     FacultiesControl.AddButtonClick += AddFacultyButton_Click;
     FacultiesControl.EditButtonClick += EditFacultyButton_Click;
     FacultiesControl.DeleteButtonClick += DeleteFacultyButton_Click;
     FacultiesControl.SearchTextChanged += SearchFaculty;
     FacultiesControl.ConfigureUpdateMethod(DBModel.Instance.GetAllFaculties);
     UpdateFaculties();
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Initalizes the database using the connection string provided in app.config, gets
        /// employee collection and attachment store
        /// </summary>
        private void InitializeDatabaseAndCollections()
        {
            string conectionString = ConfigurationManager.AppSettings["ConnectionString"];
            string collection      = ConfigurationManager.AppSettings["CollectionName"];

            _database = Client.NosDBClient.GetDatabase(conectionString);

            // Get instance of collection from the database
            _employeeCollection = _database.GetDBCollection <Employee>(collection);

            // Get an instance of the Attachment store from the database that has enabled attachments:
            _attachmentStore = _database.GetAttachmentStore();
        }
Ejemplo n.º 33
0
 internal DBLob(DBCollection cl)
 {
     this._cl          = cl;
     this._connection  = cl.CollSpace.SequoiaDB.Connection;
     this._isBigEndian = cl.isBigEndian;
     _id         = ObjectId.Empty;
     _mode       = -1;
     _size       = 0;
     _readOffset = -1;
     _createTime = 0;
     _isOpen     = false;
     _contextID  = -1;
 }
Ejemplo n.º 34
0
 internal DBLob(DBCollection cl)
 {
     this._cl = cl;
     this._connection = cl.CollSpace.SequoiaDB.Connection;
     this._isBigEndian = cl.isBigEndian;
     _id = ObjectId.Empty;
     _mode = -1;
     _size = 0;
     _readOffset = -1;
     _createTime = 0;
     _isOpen = false;
     _contextID = -1;
 }
Ejemplo n.º 35
0
 public StudentsTab()
 {
     InitializeComponent();
     StudentsList = StudentsControl.GeneralList;
     StudentsControl.AddGridColumns(ConfigureGridColumns());
     StudentsControl.AddButtonClick += AddStudentButton_Click;
     StudentsControl.EditButtonClick += EditStudentButton_Click;
     StudentsControl.DeleteButtonClick += DeleteStudentButton_Click;
     StudentsControl.SearchTextChanged += SearchStudent;
     StudentsControl.ConfigureGroupBox("Факультет", "Кафедра", "Группа", "Курс", "Нет");
     StudentsControl.GroupBoxSelectionChanged += StudentsControlOnGroupBoxSelectionChanged;
     StudentsControl.ConfigureUpdateMethod(DBModel.Instance.GetAllStudents);
     UpdateStudents();
 }
Ejemplo n.º 36
0
        /// <summary>
        /// This method initializes database and collection for futher use and sets the caching behvior
        /// to cache all data
        /// </summary>
        private void InitializeDatabaseAndCollection()
        {
            // Initialize an instance of the database to begin performing operations:
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            string collection       = ConfigurationManager.AppSettings["CollectionName"];

            _database = Client.NosDBClient.GetDatabase(connectionString);

            // Get an instance of the 'Products' collection from the database:
            _productsCollection = _database.GetDBCollection <Product>(collection);

            // Cache behavior for this collection can be set using following property. By default, behavior specified in config file is used. However, specifying in code will override the settings specified in app.config.
            _productsCollection.CachingBehavior = CachingBehavior.CacheAll;
        }
Ejemplo n.º 37
0
        static void TestAggregate2(Sequoiadb sdb)
        {
            var cs = sdb.GetCollecitonSpace("dbo");

            DBCollection coll = null;

            if (cs.IsCollectionExist("t2"))
            {
                coll = cs.GetCollection("t2");
            }
            else
            {
                coll = cs.CreateCollection("t2");
            }

            String[] command = new String[2];
            command[0] = "{$match:{status:\"A\"}}";
            command[1] = "{$group:{_id:\"$cust_id\",amount:{\"$sum\":\"$amount\"},cust_id:{\"$first\":\"$cust_id\"}}}";
            String[] record = new String[4];
            record[0] = "{cust_id:\"A123\",amount:500,status:\"A\"}";
            record[1] = "{cust_id:\"A123\",amount:250,status:\"A\"}";
            record[2] = "{cust_id:\"B212\",amount:200,status:\"A\"}";
            record[3] = "{cust_id:\"A123\",amount:300,status:\"D\"}";
            // insert record into database
            for (int i = 0; i < record.Length; i++)
            {
                BsonDocument obj = new BsonDocument();
                obj = BsonDocument.Parse(record[i]);
                Console.WriteLine("Record is: " + obj.ToString());
                coll.Insert(obj);
            }
            List <BsonDocument> list = new List <BsonDocument>();

            for (int i = 0; i < command.Length; i++)
            {
                BsonDocument obj = new BsonDocument();
                obj = BsonDocument.Parse(command[i]);
                list.Add(obj);
            }

            DBCursor cursor = coll.Aggregate(list);
            int      count  = 0;

            while (null != cursor.Next())
            {
                Console.WriteLine("Result is: " + cursor.Current().ToString());
                String str = cursor.Current().ToString();
                count++;
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Updates the selectorified collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="document">The document.</param>
        /// <param name="selector">The selector.</param>
        public static void Update <T>(this DBCollection <T> collection, T document, Expression <Func <T, bool> > selector) where T : class
        {
            BsonDocument updater = new BsonDocument();

            using (BsonWriter bsonWriter = BsonWriter.Create(updater))
            {
                SequoiaDB.Bson.Serialization.BsonSerializer.Serialize <T>(bsonWriter, document);
            }
            var          mongoQuery = GetQuery(collection, selector);
            BsonDocument modifier   = new BsonDocument();

            modifier.Add("$set", updater);
            collection.Update((BsonDocument)mongoQuery, modifier, new BsonDocument());
        }
Ejemplo n.º 39
0
        public void MyTestInitialize()
        {
            sdb = new Sequoiadb(config.conf.Coord.Address);
            sdb.Connect(config.conf.UserName, config.conf.Password);
            BsonDocument options = new BsonDocument();

            options.Add("ReplSize", 0);
            if (sdb.IsCollectionSpaceExist(csName))
            {
                sdb.DropCollectionSpace(csName);
            }
            cs   = sdb.CreateCollectionSpace(csName);
            coll = cs.CreateCollection(cName, options);
        }
Ejemplo n.º 40
0
        private DBCollection <WFFinsEntity> GetRuningData(PageEntity searchModel, TableFilter filter)
        {
            DBCollection <WFFinsEntity> col = _dataAccess.Query("wffins").FixField("*")
                                              .Paging(searchModel.PageIndex, searchModel.PageSize)
                                              .Sort("CDATE DESC")
                                              .Where(filter).Query <WFFinsEntity>();

            foreach (WFFinsEntity en in col.Data)
            {
                en.RefData.Add("serviceidname", this._wfServiceTableRefdata.GetData(en.ServiceId).Name);
                en.RefData.Add("statusName", ((EFlowStatus)en.Status).ToString());
            }
            return(col);
        }
Ejemplo n.º 41
0
        public Stream GetEggsJson(string Username)
        {
            DBCollection dbc = new DBCollection();
            DataSet      ds  = dbc.GetEggs(Username);

            string jsonString = string.Empty;

            jsonString = JsonConvert.SerializeObject(ds);

            Console.WriteLine();
            Console.WriteLine("GetEggsJson() " + GetExecutionThreadTime());

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)));
        }
Ejemplo n.º 42
0
 internal DBLob(DBCollection cl)
 {
     this._cl          = cl;
     this._connection  = cl.CollSpace.SequoiaDB.Connection;
     this._isBigEndian = cl.isBigEndian;
     _id             = ObjectId.Empty;
     _mode           = -1;
     _lobSize        = 0;
     _createTime     = 0;
     _currentOffset  = -1;
     _cachedOffset   = -1;
     _cachedDataBuff = null;
     _isOpened       = false;
     _seekWrite      = false;
     _contextID      = -1;
 }
Ejemplo n.º 43
0
 public TeachersManagementWindow(dynamic teacher)
 {
     InitializeComponent();
     curTeacher = teacher;
     Title = "Изменить преподавателя";
     PControl.SetPerson(curTeacher.person);
     SubjectsList = (DBCollection)Resources["SubjectsList"];
     DepartmentsList = (DBCollection)Resources["DepartmentsList"];
     List<dynamic> lst = DBModel.Instance.GetSubjectsByTeacher(curTeacher);
     foreach (var i in lst)
         SubjectsList.Add(i);
     lst = DBModel.Instance.GetDepartmentsByTeacher(curTeacher);
     foreach (var i in lst)
         DepartmentsList.Add(i);
     IsEdit = true;
 }
Ejemplo n.º 44
0
        /// <summary>
        /// This method initalizes database and collection using the connection string specified in app.config
        /// </summary>
        private void InitializeDatabaseAndCollection()
        {
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            string collection       = ConfigurationManager.AppSettings["CollectionName"];

            if (String.IsNullOrEmpty(connectionString))
            {
                Console.WriteLine("The connection string cannot be null or empty.");
                return;
            }
            //Initialize an instance of the database to begin performing operations:
            _database = Client.NosDBClient.GetDatabase(connectionString);

            //Get an instance of the collection from the database:
            _productsCollection = _database.GetDBCollection <Product>(collection);
        }
Ejemplo n.º 45
0
 internal DBCursor(SDBMessage rtnSDBMessage, DBCollection dbc)
 {
     this.dbc = dbc;
     connection = dbc.CollSpace.SequoiaDB.Connection;
     hint = new BsonDocument();
     hint.Add("", SequoiadbConstants.CLIENT_RECORD_ID_INDEX);
     sdbMessage = new SDBMessage();
     reqId = rtnSDBMessage.RequestID;
     sdbMessage.NodeID = SequoiadbConstants.ZERO_NODEID;
     sdbMessage.ContextIDList = rtnSDBMessage.ContextIDList;
     contextId = sdbMessage.ContextIDList[0];
     sdbMessage.NumReturned = -1;    // return data count
     list = rtnSDBMessage.ObjectList; // while using fineOne, ObjectList may have data
     hasMore = true;
     isBigEndian = dbc.isBigEndian;
     isClosed = false;
     this.DBQuery = new DBQuery();
 }
Ejemplo n.º 46
0
        public ChooseGroupWindow(ChooseType s)
        {
            InitializeComponent();
            type = s;
            StudentsGroupsList = (DBCollection)this.Resources["StudentsGroupsList"];
            StudentsGroupsViewSource = (CollectionViewSource)this.Resources["StudentsGroupsViewSource"];
            UpdateStudentsGroups();
            DataGridSelectionMode sl;
            if (s == ChooseType.Single)
            {
                sl = DataGridSelectionMode.Single;
                Title = "Выбор группы";
            }
            else
            {
                sl = DataGridSelectionMode.Extended;
                Title = "Выбор групп";
                StudentsGroupsDataGrid.ToolTip = "Для выделения нескольких элементов нажмите и удерживайте Ctrl.";
            }

            StudentsGroupsDataGrid.SelectionMode = sl;
        }
Ejemplo n.º 47
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the MongoLinqQuery class.
 /// </summary>
 /// <param name="collection">The collection being queried.</param>
 /// <param name="documentType">The document type being queried.</param>
 protected TranslatedQuery(DBCollection collection, Type documentType)
 {
     _collection = collection;
     _documentType = documentType;
 }
Ejemplo n.º 48
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the MongoLinqFindQuery class.
 /// </summary>
 /// <param name="collection">The collection being queried.</param>
 /// <param name="documentType">The document type.</param>
 public SelectQuery(DBCollection collection, Type documentType)
     : base(collection, documentType)
 {
     _serializationInfoHelper = new BsonSerializationInfoHelper();
 }
Ejemplo n.º 49
0
        /* \fn void UpdateCurrent(BsonDocument modifier)
        *  \brief Update the current Bson of this cursor
        *  \param modifier The updating rule
        *  \exception SequoiaDB.BaseException
        *  \exception System.Exception
        */

        /*
        public void UpdateCurrent(BsonDocument modifier)
        {
            if (modifier == null)
                throw new BaseException("SDB_INVALIDARG");
            if (dbc == null)
                throw new BaseException("SDB_CLT_OBJ_NOT_EXIST");
            BsonDocument current;
            if (( current = Current()) != null )
            {
                BsonDocument matcher = new BsonDocument();
                matcher.Add(SequoiadbConstants.OID, current[SequoiadbConstants.OID].AsObjectId);
                dbc.Update(matcher, modifier, hint);
                BsonDocument dummy = new BsonDocument();
                list[index] = dbc.Query(matcher, dummy, dummy, dummy).Next();
            }
        }
        */

        /* \fn void DeleteCurrent()
        *  \brief Delete the current Bson of this cursor
        *  \exception SequoiaDB.BaseException
        *  \exception System.Exception
        */
        /*
        public void DeleteCurrent()
        {
            if ( Current() != null )
                dbc.Delete( list[index] );
            list.RemoveAt(index);
            if (index >= list.Count)
                index = -1;
        }
        */

        private void ReadNextBuffer()
        {
            if (connection == null)
            {
                throw new BaseException("SDB_NOT_CONNECTED");
            }
            if (-1 == contextId)
            {
                hasMore = false;
                index = -1;
                dbc = null;
                list = null;
                return;
            }

            sdbMessage.OperationCode = Operation.OP_GETMORE;
            sdbMessage.RequestID = reqId;
            byte[] request = SDBMessageHelper.BuildGetMoreRequest(sdbMessage, isBigEndian);
            connection.SendMessage(request);
            SDBMessage rtnSDBMessage = SDBMessageHelper.MsgExtractReply(connection.ReceiveMessage(isBigEndian), isBigEndian);
            rtnSDBMessage = SDBMessageHelper.CheckRetMsgHeader(sdbMessage, rtnSDBMessage);
            
            int flags = rtnSDBMessage.Flags;
            if (flags == SequoiadbConstants.SDB_DMS_EOC)
            {
                hasMore = false;
                index = -1 ;
                dbc = null ;
                list = null;
            }
            else if (flags != 0)
            {
                throw new BaseException(flags);
            }
            else
            {
                reqId = rtnSDBMessage.RequestID;
                list = rtnSDBMessage.ObjectList;
            }
        }
Ejemplo n.º 50
0
        internal IDBCollection _GetCollection(Uri collectionUri)
        {
            DBCollection c = null;
            if (_CollectionLookup.TryGetValue(collectionUri.GetCollectionName(), out c))
                return c;

            lock (_CollectionLookup)
            {
                //Re-get for thread safety?
                if (_CollectionLookup.TryGetValue(collectionUri.GetCollectionName(), out c))
                    return c;

                if (ReadOnly && !IsStandardCollection(collectionUri) && !this.CollectionExists(collectionUri))
                {
                    throw new ReadOnlyException("cannot create a new collection when using a readonly binding");
                }

                c = new DBCollection(this, collectionUri);
                _CollectionLookup[collectionUri.GetCollectionName()] = c;
            }
            return c;
        }
Ejemplo n.º 51
0
 private void SaveButton_Click(object sender, RoutedEventArgs e)
 {
     SelectedSubjects = SubjectsControl.SelectedItems;
     DialogResult = true;
 }
Ejemplo n.º 52
0
 public void ConfigureCurrentItems (DBCollection list)
 {
     if (list != null)
         ExistingItems = list;
 }