コード例 #1
0
        public HttpResponseMessage GetSearchResult(object data)
        {
            var db = DbUtils.GetDBConnection();

            db.Connection.Open();
            IEnumerable <IDictionary <string, object> > response = null;
            var    jsonData = JsonConvert.SerializeObject(data);
            var    dictJson = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonData);
            object actionObject;

            dictJson.TryGetValue("actionName", out actionObject);
            string Action = actionObject.ToString();

            string input_queryapi = "";

            object userName;

            dictJson.TryGetValue("queried_by_username", out userName);


            if (Action.Equals("GetTableSchema"))
            {
                object tableName;
                dictJson.TryGetValue("TableName", out tableName);
                input_queryapi = tableName.ToString();
                response       = db.Query("INFORMATION_SCHEMA.COLUMNS").Select("COLUMN_NAME").WhereRaw("TABLE_NAME  = ?", tableName).Get().Cast <IDictionary <string, object> >();
                return(Request.CreateResponse(HttpStatusCode.OK, response));
            }
            if (Action.Equals("GetInstructorByName"))
            {
                object empName;
                dictJson.TryGetValue("EmpName", out empName);
                input_queryapi = empName.ToString();
                response       = db.Query("Employee").WhereRaw("lower(EmpName) = ?", empName).Get().Cast <IDictionary <string, object> >();
                //response = db.Query("Employee").WhereRaw("lower(EmpName) = ?", "dr. abdul aziz").Get().Cast<IDictionary<string, object>>();
            }
            else if (Action.Equals("GetInstructorByEmail"))
            {
                object email;
                dictJson.TryGetValue("Email", out email);
                input_queryapi = email.ToString();
                response       = db.Query("Employee").WhereRaw("lower(Email) = ?", email).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetInstructorByRank"))
            {
                object designationTitle;
                dictJson.TryGetValue("DesignationTitle", out designationTitle);
                input_queryapi = designationTitle.ToString();
                response       = db.Query("Employee").Join("Designation", "Employee.DesignationID", "Designation.DesignationID").Where("DesignationTitle", designationTitle).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetInstructorByDepartment"))
            {
                object departmentID;
                dictJson.TryGetValue("DepartmentID", out departmentID);
                input_queryapi = departmentID.ToString();
                response       = db.Query("Employee").Join("Department", "Employee.DepartmentID", "Department.DepartmentID").Where("Department.DepartmentID", departmentID).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetInstructorByNameStartsWith"))
            {
                object startNamePrefix;
                dictJson.TryGetValue("EmpName", out startNamePrefix);
                string prefixString = startNamePrefix.ToString() + "%";
                input_queryapi = startNamePrefix.ToString();
                response       = db.Query("Employee").WhereLike("EmpName", prefixString).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetInstructorByNameContains"))
            {
                object startNamePrefix;
                dictJson.TryGetValue("EmpName", out startNamePrefix);
                string prefixString = "%" + startNamePrefix.ToString() + "%";
                input_queryapi = startNamePrefix.ToString();
                response       = db.Query("Employee").WhereLike("EmpName", prefixString).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetInstructorByCourseName"))
            {
                object courseName;
                dictJson.TryGetValue("CourseName", out courseName);
                input_queryapi = courseName.ToString();
                response       = db.Query("Employee").Join("CourseFaculty", "Employee.EmpID", "CourseFaculty.EmpID").Join("CourseOffered", "CourseOffered.CourseOfferedID", "CourseFaculty.CourseOfferedID").Join("Course", "CourseOffered.CourseID", "Course.CourseID").Where("CourseName", courseName).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetInstructorByCourseCode"))
            {
                object courseCode;
                dictJson.TryGetValue("CourseCode", out courseCode);
                input_queryapi = courseCode.ToString();
                response       = db.Query("Employee").Join("CourseFaculty", "Employee.EmpID", "CourseFaculty.EmpID").Join("CourseOffered", "CourseOffered.CourseOfferedID", "CourseFaculty.CourseOfferedID").Join("Course", "CourseOffered.CourseID", "Course.CourseID").Where("CourseCode", courseCode).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetCoursesTaughtByASpecificInstructor"))
            {
                object EmpName;
                dictJson.TryGetValue("EmpName", out EmpName);
                input_queryapi = EmpName.ToString();
                response       = db.Query("Semester").Select("CourseName").Join("CourseOffered", "Semester.SemesterID", "CourseOffered.SemesterID").Join("Course", "Course.CourseID", "CourseOffered.CourseID")
                                 .Join("CourseFaculty", "CourseFaculty.CourseOfferedID", "CourseOffered.CourseOfferedID")
                                 .Join("Employee", "Employee.EmpID", "CourseFaculty.EmpID")
                                 .Where("EmpName", EmpName).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            else if (Action.Equals("GetCoursesTaughtByAInstructorInAParticularSemester"))
            {
                object semesterName;
                object empName;
                dictJson.TryGetValue("EmpName", out empName);
                dictJson.TryGetValue("SemesterName", out semesterName);
                input_queryapi = empName.ToString() + " " + semesterName.ToString();
                response       = db.Query("Semester").Join("CourseOffered", "Semester.SemesterID", "CourseOffered.SemesterID").Join("Course", "Course.CourseID", "CourseOffered.CourseID")
                                 .Join("CourseFaculty", "CourseFaculty.CourseOfferedID", "CourseOffered.CourseOfferedID")
                                 .Join("Employee", "Employee.EmpID", "CourseFaculty.EmpID")
                                 .Where("SemesterName", semesterName)
                                 .Where("EmpName", empName).Get().Cast <IDictionary <string, object> >(); //get product by id=1
            }
            // STUDENT QUERIES
            else if (Action.Equals("GetStudentByName"))
            {
                object SName;
                dictJson.TryGetValue("SName", out SName);
                input_queryapi = SName.ToString();
                response       = db.Query("Student").WhereRaw("lower(SName) = ?", SName).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentByStudentID"))
            {
                object RollNumber;
                dictJson.TryGetValue("RollNumber", out RollNumber);
                input_queryapi = RollNumber.ToString();
                response       = db.Query("Student").WhereRaw("lower(RollNumber) = ?", RollNumber).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentByBatchID"))
            {
                object BatchID;
                dictJson.TryGetValue("BatchID", out BatchID);
                input_queryapi = BatchID.ToString();
                response       = db.Query("Student").WhereRaw("BatchID = ?", BatchID).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsByDepartment"))
            {
                object DepartmentName;
                dictJson.TryGetValue("DepartmentName", out DepartmentName);
                input_queryapi = DepartmentName.ToString();
                response       = db.Query("Student").Join("Programme", "Programme.ProgrammeID", "Student.ProgrammeID").Join("Department", "Department.DepartmentID", "Programme.DepartmentID")
                                 .Where("DepartmentName", DepartmentName).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsBySection"))
            {
                object SectionName;
                dictJson.TryGetValue("SectionName", out SectionName);
                input_queryapi = SectionName.ToString();
                response       = db.Query("Student").Join("Section", "Section.BatchID", "Student.BatchID")
                                 .Where("SectionName", SectionName).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentByNUEmail"))
            {
                object Email;
                dictJson.TryGetValue("Email", out Email);
                input_queryapi = Email.ToString();
                response       = db.Query("Student").Join("CandidateStudent", "CandidateStudent.CandidateID", "Student.CandidateID")
                                 .Where("Student.Email", Email).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentByPrimaryEmail"))
            {
                object Email;
                dictJson.TryGetValue("Email", out Email);
                input_queryapi = Email.ToString();
                response       = db.Query("Student").Join("CandidateStudent", "CandidateStudent.CandidateID", "Student.CandidateID")
                                 .Where("CandidateStudent.Email", Email).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsByNameStartsWith"))
            {
                object startNamePrefix;
                dictJson.TryGetValue("Sname", out startNamePrefix);
                input_queryapi = startNamePrefix.ToString();
                string prefixString = startNamePrefix.ToString() + "%";
                response = db.Query("Student").WhereLike("Sname", prefixString).Get().Cast <IDictionary <string, object> >();  //get product by id=1
            }
            else if (Action.Equals("GetStudentsByNameContains"))
            {
                object startNamePrefix;
                dictJson.TryGetValue("EmpName", out startNamePrefix);
                input_queryapi = startNamePrefix.ToString();
                string prefixString = "%" + startNamePrefix.ToString() + "%";
                response = db.Query("Student").WhereLike("Sname", prefixString).Get().Cast <IDictionary <string, object> >();  //get product by id=1
            }
            else if (Action.Equals("GetStudentsByCourseName"))
            {
                object CourseName;
                dictJson.TryGetValue("CourseName", out CourseName);
                input_queryapi = CourseName.ToString();
                response       = db.Query("Student").Join("CourseEnrollment", "CourseEnrollment.StudentID", "Student.StudentID").Join("Course", "Course.CourseID", "CourseEnrollment.CourseID")
                                 .Where("CourseName", CourseName).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsByCourseCode"))
            {
                object CourseCode;
                dictJson.TryGetValue("CourseCode", out CourseCode);
                input_queryapi = CourseCode.ToString();

                response = db.Query("Student").Join("CourseEnrollment", "CourseEnrollment.StudentID", "Student.StudentID").Join("Course", "Course.CourseID", "CourseEnrollment.CourseID")
                           .Where("CourseCode", CourseCode).Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsBySkill"))
            {
                response = db.Query("StudentSkills").Join("Skill", "Skill.SkillID", "StudentSkills.SkillID").Join("Student", "StudentSkills.StudentID", "Student.StudentID")
                           .Get().Cast <IDictionary <string, object> >();
            }
            else if (Action.Equals("GetStudentsByDomain"))
            {
                response = db.Query("Domain").Join("Skill", "Skill.DomainID", "Domain.DomainID").Join("StudentSkills", "StudentSkills.SkillID", "Skill.SkillID").Join("Student", "Student.StudentID", "StudentSkills.StudentID")
                           .Get().Cast <IDictionary <string, object> >();
            }



            //var db1 = DbUtils.GetDBConnection();
            //db1.Connection.Open();

            SqlConnection dbConnection = new SqlConnection(ConfigurationManager.AppSettings["SqlDBConn"].ToString());



            try
            {
                /**
                 * db1.Query("dbo.SearchLog").AsInsert(new
                 * {
                 *  input_query = input_queryapi,
                 *  actionName = Action,
                 *  queried_by_username = userName.ToString()
                 * });
                 **/

                string query = "INSERT INTO dbo.SearchLog(input_query, actionName, queried_by_username) VALUES(@input_query,@actionName,@queried_by_username)";
                using (SqlCommand command = new SqlCommand(query, dbConnection))
                {
                    command.Parameters.AddWithValue("@input_query", input_queryapi);
                    command.Parameters.AddWithValue("@actionName", Action);
                    command.Parameters.AddWithValue("@queried_by_username", userName.ToString());

                    dbConnection.Open();
                    int result = command.ExecuteNonQuery();

                    // Check Error
                    if (result < 0)
                    {
                        Console.WriteLine("Error inserting data into Database!");
                    }
                }
            }
            catch (Exception e)
            {
            }



            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
コード例 #2
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     DbUtils.Clean("Spec-EventJournal");
 }
コード例 #3
0
 /// <summary>
 /// Determines the connection to use. If transaction to use is null, a new connection is created, otherwise the connection of the transaction is used.
 /// </summary>
 /// <param name="transactionToUse">Transaction to use.</param>
 /// <returns>a ready to use connection object.</returns>
 protected override IDbConnection DetermineConnectionToUse(ITransaction transactionToUse)
 {
     return(DbUtils.DetermineConnectionToUse(transactionToUse));
 }
コード例 #4
0
ファイル: Home.cs プロジェクト: schifflee/LightBox
        private void bStartDump_Click(object sender, EventArgs e)
        {
            //new ProgressFormContainer().Show();
            if (!performChecks())
            {
                return;
            }
            if (adapter.isDumpRunning())
            {
                MessageBox.Show("dump is running...");
                return;
            }
            adapter = new SqlDumpAdapter();

            List <string> databases      = new List <string>();
            List <string> excludedTables = new List <string>();

            tableList = new List <string>();
            foreach (TreeNode node in tvDatabases.Nodes)
            {
                if (node.Checked)
                {
                    databases.Add(node.Text);
                    string tables = "";
                    foreach (TreeNode childNode in node.Nodes)
                    {
                        if (!childNode.Checked)
                        {
                            tables += childNode.Text + ",";
                        }
                        else
                        {
                            tableList.Add(childNode.Text);
                        }
                    }
                    if (tables != "")
                    {
                        tables = tables.Substring(0, tables.Length - 1); //vgazei to teleutaio comma
                    }
                    excludedTables.Add(tables);
                }
            }
            DumpCredentialsConfig config = new DumpCredentialsConfig(DbUtils.getSqlServerFromTable(serverData, cmbServers));

            if (databases.Count == 0)
            {
                MessageBox.Show("No database selected", "MySQL Dump", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (databases.Count == 1)
            {
                config.database = databases[0];
                if (excludedTables[0] != "")
                {
                    config.excludeTablesSingleDatabase = excludedTables[0];
                }
            }
            else
            {
                config.database      = databases[0];
                config.databases     = databases.ToArray();
                config.excludeTables = excludedTables.ToArray();
            }

            pbDumpExec.Value = 0;

            bStartDump.Enabled = false;
            adapter.setTableList(tableList);

            adapter.Cancelled        += onCancelledHandler;
            adapter.Completed        += onCompletedHandler;
            adapter.CompressProgress += compressProgressHandler;
            adapter.CompressStart    += onCompressStartHandler;
            adapter.Error            += onErrorHandler;
            adapter.InitDumpTables   += initDumpTablesHandler;
            adapter.Progress         += onProgressHandler;
            adapter.TableRowCount    += tableRowCountHandler;
            adapter.TableStartDump   += onTableDumpStartHandler;

            this.UseWaitCursor = true;
            adapter.startDump(config);
        }
コード例 #5
0
        public void RemoveAuthorBook(AuthorBooks authorBooks)
        {
            String sql = "DELETE FROM AuthorBooks WHERE author_id = '" + authorBooks.AuthorId.ToString() + "' AND book_id = '" + authorBooks.BookId.ToString() + "'";

            DbUtils.ExecuteNonQuery(_connection, sql);
        }
コード例 #6
0
        public List <Post> GetAllWithComments()
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                SELECT p.Id AS PostId, p.Title, p.Caption, p.DateCreated AS PostDateCreated,
                       p.ImageUrl AS PostImageUrl, p.UserProfileId AS PostUserProfileId,

                       up.Name, up.Bio, up.Email, up.DateCreated AS UserProfileDateCreated,
                       up.ImageUrl AS UserProfileImageUrl,

                       c.Id AS CommentId, c.Message, c.UserProfileId AS CommentUserProfileId
                  FROM Post p
                       LEFT JOIN UserProfile up ON p.UserProfileId = up.id
                       LEFT JOIN Comment c on c.PostId = p.id
              ORDER BY p.DateCreated";

                    var reader = cmd.ExecuteReader();

                    var posts = new List <Post>();
                    while (reader.Read())
                    {
                        var postId = DbUtils.GetInt(reader, "PostId");

                        var existingPost = posts.FirstOrDefault(p => p.Id == postId);
                        if (existingPost == null)
                        {
                            existingPost = new Post()
                            {
                                Id            = postId,
                                Title         = DbUtils.GetString(reader, "Title"),
                                Caption       = DbUtils.GetString(reader, "Caption"),
                                DateCreated   = DbUtils.GetDateTime(reader, "PostDateCreated"),
                                ImageUrl      = DbUtils.GetString(reader, "PostImageUrl"),
                                UserProfileId = DbUtils.GetInt(reader, "PostUserProfileId"),
                                UserProfile   = new UserProfile()
                                {
                                    Id          = DbUtils.GetInt(reader, "PostUserProfileId"),
                                    Name        = DbUtils.GetString(reader, "Name"),
                                    Email       = DbUtils.GetString(reader, "Email"),
                                    DateCreated = DbUtils.GetDateTime(reader, "UserProfileDateCreated"),
                                    ImageUrl    = DbUtils.GetString(reader, "UserProfileImageUrl"),
                                },
                                Comments = new List <Comment>()
                            };

                            posts.Add(existingPost);
                        }

                        if (DbUtils.IsNotDbNull(reader, "CommentId"))
                        {
                            existingPost.Comments.Add(new Comment()
                            {
                                Id            = DbUtils.GetInt(reader, "CommentId"),
                                Message       = DbUtils.GetString(reader, "Message"),
                                PostId        = postId,
                                UserProfileId = DbUtils.GetInt(reader, "CommentUserProfileId")
                            });
                        }
                    }

                    reader.Close();

                    return(posts);
                }
            }
        }
        public List <Post> GetPostsByUserProfileId(int userProfileId)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                 SELECT p.Id as PostId, p.Title, p.Content, p.ImageLocation, p.CreateDateTime, p.PublishDateTime, p.IsApproved, p.CategoryId,
                                        up.Id as UserProfileId, up.DisplayName, up.FirstName, up.LastName, up.Email, up.UserTypeId,
                                        c.Id as CategoryId, c.[Name] as Category
                FROM Post p
                LEFT JOIN UserProfile up ON up.Id = p.UserProfileId
                LEFT JOIN Category c on c.Id = p.CategoryId
                WHERE p.UserProfileId = @userProfileId
            ";

                    cmd.Parameters.AddWithValue("@userProfileId", userProfileId);

                    SqlDataReader reader = cmd.ExecuteReader();

                    List <Post> posts = new List <Post>();

                    while (reader.Read())
                    {
                        Post post = new Post()
                        {
                            Id              = DbUtils.GetInt(reader, "PostId"),
                            Title           = DbUtils.GetString(reader, "Title"),
                            Content         = DbUtils.GetString(reader, "Content"),
                            CreateDateTime  = DbUtils.GetDateTime(reader, "CreateDateTime"),
                            PublishDateTime = DbUtils.GetDateTime(reader, "PublishDateTime"),
                            ImageLocation   = DbUtils.GetString(reader, "ImageLocation"),
                            IsApproved      = reader.GetBoolean(reader.GetOrdinal("IsApproved")),
                            CategoryId      = DbUtils.GetInt(reader, "CategoryId"),
                            UserProfileId   = DbUtils.GetInt(reader, "UserProfileId"),
                            userProfile     = new UserProfile()
                            {
                                Id          = DbUtils.GetInt(reader, "UserProfileId"),
                                DisplayName = DbUtils.GetString(reader, "DisplayName"),
                                FirstName   = DbUtils.GetString(reader, "FirstName"),
                                LastName    = DbUtils.GetString(reader, "LastName"),
                                Email       = DbUtils.GetString(reader, "Email"),
                                UserTypeId  = DbUtils.GetInt(reader, "UserTypeId"),
                            },
                            category = new Category()
                            {
                                Id   = DbUtils.GetInt(reader, "CategoryId"),
                                Name = DbUtils.GetString(reader, "Category")
                            }
                        };

                        post.userProfile = new UserProfile()
                        {
                            DisplayName = reader.GetString(reader.GetOrdinal("DisplayName"))
                        };


                        posts.Add(post);
                    }
                    reader.Close();
                    return(posts);
                }
            }
        }
コード例 #8
0
ファイル: ValuesController.cs プロジェクト: wypick/RestApi
 public IActionResult Post(Pass pass)
 {
     //var result = JsonSerializer.Deserialize<Pass>(pass);
     return(Ok(JsonSerializer.Serialize(DbUtils.Post(pass))));
 }
コード例 #9
0
        public Puzzle GetPuzzleWithUserProfileById(int id)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                      SELECT p.Id AS PuzzleId, p.CategoryId, p.CurrentOwnerId AS CurrentOwnerId, p.ImageLocation, p.Pieces, p.CreateDateTime,
                      p.Title, p.Manufacturer, p.Notes, p.IsAvailable, p.IsDeleted, p.InProgress,

                      c.Id AS CategoryId, c.Name,

                      up.Id as UserId, up.DisplayName, up.ImageLocation

                      FROM Puzzle p
                      LEFT JOIN Category c 
                      ON p.CategoryId = c.Id
                      LEFT JOIN UserProfile up
                      ON p.CurrentOwnerId = up.Id
                      WHERE p.Id = @id AND p.IsDeleted = 0
                      ORDER BY CreateDateTime DESC
                       ";

                    cmd.Parameters.AddWithValue("@id", id);

                    var    reader = cmd.ExecuteReader();
                    Puzzle puzzle = null;

                    if (reader.Read())
                    {
                        puzzle = new Puzzle
                        {
                            Id             = reader.GetInt32(reader.GetOrdinal("PuzzleId")),
                            CategoryId     = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                            CurrentOwnerId = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                            ImageLocation  = DbUtils.GetNullableString(reader, "ImageLocation"),
                            Pieces         = reader.GetInt32(reader.GetOrdinal("Pieces")),
                            CreateDateTime = reader.GetDateTime(reader.GetOrdinal("CreateDateTime")),
                            Title          = reader.GetString(reader.GetOrdinal("Title")),
                            Manufacturer   = reader.GetString(reader.GetOrdinal("Manufacturer")),
                            Notes          = DbUtils.GetNullableString(reader, "Notes"),
                            IsAvailable    = reader.GetInt32(reader.GetOrdinal("IsAvailable")),
                            IsDeleted      = reader.GetInt32(reader.GetOrdinal("IsDeleted")),
                            InProgress     = reader.GetInt32(reader.GetOrdinal("InProgress")),
                            Category       = new Category
                            {
                                Id   = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                Name = reader.GetString(reader.GetOrdinal("Name"))
                            },
                            UserProfile = new UserProfile
                            {
                                Id          = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                                DisplayName = reader.GetString(reader.GetOrdinal("DisplayName"))
                            }
                        };
                        reader.Close();
                        return(puzzle);
                    }
                    else
                    {
                        reader.Close();
                        return(null);
                    }
                }
            }
        }
コード例 #10
0
        //search
        public List <Puzzle> SearchActivePuzzles(string criterion)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    var sql = @"
                      SELECT p.Id AS PuzzleId, p.CategoryId, p.CurrentOwnerId AS CurrentOwnerId, p.ImageLocation, p.Pieces, p.CreateDateTime,
                      p.Title, p.Manufacturer, p.Notes, p.IsAvailable, p.IsDeleted, p.InProgress,

                      c.Id AS CategoryId, c.Name,
    
                      up.DisplayName, up.ImageLocation

                      FROM Puzzle p
                      LEFT JOIN Category c 
                      ON p.CategoryId = c.Id
                      LEFT JOIN UserProfile up
                      ON p.CurrentOwnerId = up.Id
                      WHERE p.IsAvailable = 1 AND p.IsDeleted = 0 AND p.InProgress = 0
                      AND (p.Title LIKE @Criterion OR p.Pieces LIKE @Criterion OR up.DisplayName LIKE @Criterion OR p.Manufacturer LIKE @Criterion OR c.Name LIKE @Criterion)
                      ORDER BY p.CreateDateTime DESC";

                    cmd.CommandText = sql;
                    DbUtils.AddParameter(cmd, "@Criterion", $"%{criterion}%");
                    var reader = cmd.ExecuteReader();

                    var puzzles = new List <Puzzle>();

                    while (reader.Read())
                    {
                        puzzles.Add(new Puzzle()
                        {
                            Id             = reader.GetInt32(reader.GetOrdinal("PuzzleId")),
                            CategoryId     = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                            CurrentOwnerId = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                            ImageLocation  = DbUtils.GetNullableString(reader, "ImageLocation"),
                            Pieces         = reader.GetInt32(reader.GetOrdinal("Pieces")),
                            CreateDateTime = reader.GetDateTime(reader.GetOrdinal("CreateDateTime")),
                            Title          = reader.GetString(reader.GetOrdinal("Title")),
                            Manufacturer   = reader.GetString(reader.GetOrdinal("Manufacturer")),
                            Notes          = DbUtils.GetNullableString(reader, "Notes"),
                            IsAvailable    = reader.GetInt32(reader.GetOrdinal("IsAvailable")),
                            IsDeleted      = reader.GetInt32(reader.GetOrdinal("IsDeleted")),
                            InProgress     = reader.GetInt32(reader.GetOrdinal("InProgress")),
                            Category       = new Category
                            {
                                Id   = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                Name = reader.GetString(reader.GetOrdinal("Name"))
                            },
                            UserProfile = new UserProfile
                            {
                                Id          = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                                DisplayName = reader.GetString(reader.GetOrdinal("DisplayName"))
                            }
                        });
                    }

                    reader.Close();

                    return(puzzles);
                }
            }
        }
コード例 #11
0
        //get puzzle with history by puzzle id
        public Puzzle GetPuzzleById(int id)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                      SELECT p.Id AS PuzzleId, p.CategoryId, p.CurrentOwnerId AS CurrentOwnerId, p.ImageLocation, p.Pieces, p.CreateDateTime,
                      p.Title, p.Manufacturer, p.Notes, p.IsAvailable, p.IsDeleted, p.InProgress,

                      c.Id AS CategoryId, c.Name,

                      h.Id AS HistoryId, h.UserProfileId AS HistoricalOwnerId, h.StartDateOwnership, h.EndDateOwnership,
    
                      up.Id as UserId, up.DisplayName, up.ImageLocation

                      FROM Puzzle p
                      LEFT JOIN Category c 
                      ON p.CategoryId = c.Id
                      LEFT JOIN History h
                      ON h.PuzzleId = p.Id
                      LEFT JOIN UserProfile up
                      ON h.UserProfileId = up.Id
                      WHERE p.Id = @id AND p.IsDeleted = 0
                      ORDER BY CreateDateTime DESC
                       ";

                    cmd.Parameters.AddWithValue("@id", id);

                    var    reader = cmd.ExecuteReader();
                    Puzzle puzzle = null;

                    while (reader.Read())
                    {
                        if (puzzle == null)
                        {
                            puzzle = new Puzzle
                            {
                                Id             = reader.GetInt32(reader.GetOrdinal("PuzzleId")),
                                CategoryId     = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                CurrentOwnerId = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                                ImageLocation  = DbUtils.GetNullableString(reader, "ImageLocation"),
                                Pieces         = reader.GetInt32(reader.GetOrdinal("Pieces")),
                                CreateDateTime = reader.GetDateTime(reader.GetOrdinal("CreateDateTime")),
                                Title          = reader.GetString(reader.GetOrdinal("Title")),
                                Manufacturer   = reader.GetString(reader.GetOrdinal("Manufacturer")),
                                Notes          = DbUtils.GetNullableString(reader, "Notes"),
                                IsAvailable    = reader.GetInt32(reader.GetOrdinal("IsAvailable")),
                                IsDeleted      = reader.GetInt32(reader.GetOrdinal("IsDeleted")),
                                InProgress     = reader.GetInt32(reader.GetOrdinal("InProgress")),
                                Category       = new Category
                                {
                                    Id   = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                    Name = reader.GetString(reader.GetOrdinal("Name"))
                                },
                                Histories = new List <History>()
                            };
                        }


                        if (DbUtils.IsNotDbNull(reader, "HistoryId"))
                        {
                            puzzle.Histories.Add(new History()
                            {
                                Id                 = reader.GetInt32(reader.GetOrdinal("HistoryId")),
                                PuzzleId           = reader.GetInt32(reader.GetOrdinal("PuzzleId")),
                                UserProfileId      = reader.GetInt32(reader.GetOrdinal("HistoricalOwnerId")),
                                StartDateOwnership = reader.GetDateTime(reader.GetOrdinal("StartDateOwnership")),
                                EndDateOwnership   = DbUtils.GetNullableDateTime(reader, "EndDateOwnership"),
                                UserProfile        = new UserProfile
                                {
                                    Id          = reader.GetInt32(reader.GetOrdinal("UserId")),
                                    DisplayName = reader.GetString(reader.GetOrdinal("DisplayName"))
                                }
                            });
                        }
                    }
                    reader.Close();
                    return(puzzle);
                }
            }
        }
コード例 #12
0
        public List <Puzzle> GetAllUserPuzzlesInProgressById(int id)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                   SELECT p.Id AS PuzzleId, p.CategoryId, p.CurrentOwnerId AS CurrentOwnerId, p.ImageLocation, p.Pieces, p.CreateDateTime,
                      p.Title, p.Manufacturer, p.Notes, p.IsAvailable, p.IsDeleted, p.InProgress,

                      c.Id AS CategoryId, c.Name,
    
                      up.DisplayName, up.ImageLocation

                      FROM Puzzle p
                      LEFT JOIN Category c 
                      ON p.CategoryId = c.Id
                      LEFT JOIN UserProfile up
                      ON p.CurrentOwnerId = up.Id  
                      WHERE p.CurrentOwnerId = @id
                      AND p.IsAvailable = 0
                      AND p.IsDeleted = 0
                      AND p.InProgress = 1  
                      ORDER BY CreateDateTime DESC
                       ";

                    cmd.Parameters.AddWithValue("@id", id);
                    var puzzles = new List <Puzzle>();

                    var reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        var puzzleId = DbUtils.GetInt(reader, "PuzzleId");

                        var existingPuzzle = puzzles.FirstOrDefault(puzzle => puzzle.Id == puzzleId);

                        if (existingPuzzle == null)
                        {
                            existingPuzzle = new Puzzle()
                            {
                                Id             = puzzleId,
                                CategoryId     = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                CurrentOwnerId = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                                ImageLocation  = DbUtils.GetNullableString(reader, "ImageLocation"),
                                Pieces         = reader.GetInt32(reader.GetOrdinal("Pieces")),
                                CreateDateTime = reader.GetDateTime(reader.GetOrdinal("CreateDateTime")),
                                Title          = reader.GetString(reader.GetOrdinal("Title")),
                                Manufacturer   = reader.GetString(reader.GetOrdinal("Manufacturer")),
                                Notes          = DbUtils.GetNullableString(reader, "Notes"),
                                IsAvailable    = reader.GetInt32(reader.GetOrdinal("IsAvailable")),
                                IsDeleted      = reader.GetInt32(reader.GetOrdinal("IsDeleted")),
                                InProgress     = reader.GetInt32(reader.GetOrdinal("InProgress")),
                                Category       = new Category
                                {
                                    Id   = reader.GetInt32(reader.GetOrdinal("CategoryId")),
                                    Name = reader.GetString(reader.GetOrdinal("Name"))
                                },
                                UserProfile = new UserProfile
                                {
                                    Id          = reader.GetInt32(reader.GetOrdinal("CurrentOwnerId")),
                                    DisplayName = reader.GetString(reader.GetOrdinal("DisplayName"))
                                }
                            };

                            puzzles.Add(existingPuzzle);
                        }
                    }

                    reader.Close();
                    return(puzzles);
                }
            }
        }
コード例 #13
0
ファイル: MasterDal.cs プロジェクト: jtdotnetgroup/Hn_Arrow
        public List <MasterModel> GetListByIds(string ids)
        {
            string sql = "SELECT * FROM TB_MASTER WHERE FID IN ('" + ids.Replace(",", "','") + "')";

            return(DbUtils.GetList <MasterModel>(sql, null).ToList());
        }
コード例 #14
0
 public SyncMetadataJob(uint id, string job_options, int run_at, JobPriority job_priority, bool persistent) : this(id, job_options, DbUtils.DateTimeFromUnixTime(run_at), job_priority, persistent)
 {
 }
コード例 #15
0
        public List <Post> Search(string criterion, bool sortDescending, string since)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    var sql =
                        @"SELECT p.Id AS PostId, p.Title, p.Caption, p.DateCreated AS PostDateCreated, 
                                 p.ImageUrl AS PostImageUrl, p.UserProfileId,

                                 up.Name, up.Bio, up.Email, up.DateCreated AS UserProfileDateCreated, 
                                 up.ImageUrl AS UserProfileImageUrl
                            FROM Post p 
                                 LEFT JOIN UserProfile up ON p.UserProfileId = up.id
                           WHERE (p.Title LIKE @Criterion OR p.Caption LIKE @Criterion)";

                    if (since != null)
                    {
                        sql += " AND p.DateCreated >= @Since";
                    }

                    if (sortDescending)
                    {
                        sql += " ORDER BY p.DateCreated DESC";
                    }
                    else
                    {
                        sql += " ORDER BY p.DateCreated";
                    }


                    cmd.CommandText = sql;
                    DbUtils.AddParameter(cmd, "@Criterion", $"%{criterion}%");
                    DbUtils.AddParameter(cmd, "@Since", since);
                    var reader = cmd.ExecuteReader();

                    var posts = new List <Post>();
                    while (reader.Read())
                    {
                        posts.Add(new Post()
                        {
                            Id            = DbUtils.GetInt(reader, "PostId"),
                            Title         = DbUtils.GetString(reader, "Title"),
                            Caption       = DbUtils.GetString(reader, "Caption"),
                            DateCreated   = DbUtils.GetDateTime(reader, "PostDateCreated"),
                            ImageUrl      = DbUtils.GetString(reader, "PostImageUrl"),
                            UserProfileId = DbUtils.GetInt(reader, "UserProfileId"),
                            UserProfile   = new UserProfile()
                            {
                                Id          = DbUtils.GetInt(reader, "UserProfileId"),
                                Name        = DbUtils.GetString(reader, "Name"),
                                Email       = DbUtils.GetString(reader, "Email"),
                                DateCreated = DbUtils.GetDateTime(reader, "UserProfileDateCreated"),
                                ImageUrl    = DbUtils.GetString(reader, "UserProfileImageUrl"),
                            },
                        });
                    }

                    reader.Close();

                    return(posts);
                }
            }
        }
コード例 #16
0
 private void TreeViewTables_BeforeExpand(object sender, TreeViewCancelEventArgs e)
 {
     this.setTableFields(DbUtils.getTableFields(GetSqlConnection(), e.Node.Text), e.Node.Index);
 }
コード例 #17
0
        public Post GetById(int id)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        SELECT p.Id AS PostId, p.Title, p.Caption, p.DateCreated AS PostDateCreated, 
                               p.ImageUrl AS PostImageUrl, p.UserProfileId,

                               up.Name, up.Bio, up.Email, p.DateCreated AS UserProfileDateCreated, 
                               up.ImageUrl AS UserProfileImageUrl,

                               c.Id AS CommentId, c.Message, c.UserProfileId AS CommentUserProfileId
                          FROM Post p 
                               LEFT JOIN UserProfile up ON p.UserProfileId = up.id
                               LEFT JOIN Comment c ON p.Id = c.PostId
                         WHERE p.Id = @Id";

                    DbUtils.AddParameter(cmd, "@Id", id);

                    var reader = cmd.ExecuteReader();

                    Post post = null;
                    while (reader.Read())
                    {
                        if (post == null)
                        {
                            post = new Post()
                            {
                                Id            = id,
                                Title         = DbUtils.GetString(reader, "Title"),
                                Caption       = DbUtils.GetString(reader, "Caption"),
                                DateCreated   = DbUtils.GetDateTime(reader, "PostDateCreated"),
                                ImageUrl      = DbUtils.GetString(reader, "PostImageUrl"),
                                UserProfileId = DbUtils.GetInt(reader, "UserProfileId"),
                                Comments      = new List <Comment>(),
                                UserProfile   = new UserProfile()
                                {
                                    Id          = DbUtils.GetInt(reader, "UserProfileId"),
                                    Name        = DbUtils.GetString(reader, "Name"),
                                    Email       = DbUtils.GetString(reader, "Email"),
                                    DateCreated = DbUtils.GetDateTime(reader, "UserProfileDateCreated"),
                                    ImageUrl    = DbUtils.GetString(reader, "UserProfileImageUrl"),
                                }
                            };
                        }

                        if (DbUtils.IsNotDbNull(reader, "CommentId"))
                        {
                            post.Comments.Add(new Comment()
                            {
                                Id            = DbUtils.GetInt(reader, "CommentId"),
                                Message       = DbUtils.GetString(reader, "Message"),
                                PostId        = post.Id,
                                UserProfileId = DbUtils.GetInt(reader, "CommentUserProfileId")
                            });
                        }
                    }

                    reader.Close();

                    return(post);
                }
            }
        }
コード例 #18
0
 public AuthorBooksRepository()
 {
     this._connection = DbUtils.GetConnection();
 }
コード例 #19
0
        public List <Subscription> GetAllFollowersForAuthor(int authorId)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        SELECT s.Id, s.SubscriberUserProfileId, s.ProviderUserProfileId, s.BeginDateTime, s.EndDateTime
                        FROM Subscription s
                        LEFT JOIN UserProfile up ON s.SubscriberUserProfileId = up.id
                        WHERE s.ProviderUserProfileId = @AuthorId ";

                    DbUtils.AddParameter(cmd, "@AuthorId", authorId);
                    //Subscription subscription = null;
                    var reader        = cmd.ExecuteReader();
                    var subscriptions = new List <Subscription>();

                    if (reader.Read())
                    {
                        {
                            subscriptions.Add(NewSubscriptionFromReader(reader));
                        };
                        reader.Close();
                        return(subscriptions);
                    }
                    else
                    {
                        reader.Close();
                        return(null);
                    }
                }
            }
            //Getting all the subscribers to one user(author) by the user's Id
            //public Subscription GetByUserId(int id, int authorId)
            //{
            //    using (var conn = Connection)
            //    {
            //        conn.Open();
            //        using (var cmd = conn.CreateCommand())
            //        {
            //            cmd.CommandText = @"
            //                SELECT s.Id, s.SubscriberUserProfileId, s.ProviderUserProfileId, s.BeginDateTime, s.EndDateTime
            //                FROM Subscription s
            //                LEFT JOIN UserProfile up ON s.SubscriberUserProfileId = up.id
            //                WHERE s.SubscriberUserProfileId = @FollowerId
            //                AND s.ProviderUserProfileId = @AuthorId ";

            //            DbUtils.AddParameter(cmd, "@FollowerId", id);
            //            DbUtils.AddParameter(cmd, "@AuthorId", authorId);

            //            var reader = cmd.ExecuteReader();

            //            if (reader.Read())
            //            {
            //                Subscription subscription = new Subscription
            //                {
            //                    Id = reader.GetInt32(reader.GetOrdinal("Id")),
            //                    SubscriberUserProfileId = reader.GetInt32(reader.GetOrdinal("SubscriberUserProfileId")),
            //                    ProviderUserProfileId = reader.GetInt32(reader.GetOrdinal("ProviderUserProfileId")),
            //                    BeginDateTime = reader.GetDateTime(reader.GetOrdinal("BeginDateTime")),
            //                    EndDateTime = reader.GetDateTime(reader.GetOrdinal("EndDateTime")),

            //                };
            //                reader.Close();
            //                return subscription;

            //            }
            //            else
            //            {
            //                reader.Close();
            //                return null;
            //            }
            //        }
            //    }
            //}
        }
コード例 #20
0
ファイル: Startup.cs プロジェクト: randyammar/LogicMine
 private void OnShutdown()
 {
     _traceExporter?.Dispose();
     DbUtils.DeleteDb();
 }
コード例 #21
0
        public void WriteLog1(string old_value, string new_value, string middle_value)
        {
            try
            {
                #region 保旧值
                IniFileReference _iniFile = new IniFileReference(AppDomain.CurrentDomain.BaseDirectory + "Geometry.ini");

                _iniFile.IniWriteValue("SYSDNSection", "local_old_value", Convert.ToString(new_value));

                _iniFile.IniWriteValue("SYSDNSection", "local_middle_value", Convert.ToString(middle_value));

                _iniFile = null;
                #endregion

                #region 工位判断

                string Manufacture = ConfigurationManager.AppSettings["生产企业"];


                //string UUID = System.Guid.NewGuid().ToString("N");
                int i = 0;

                string strD = "";

                if (old_value == "94" && new_value == "126")
                {
                    string str = "INSERT INTO CmdGongWei (cGWid,cGWlineCode,cManufacture) VALUES ('08','01','" + Manufacture + "')";
                    strD = str;
                }
                if (old_value == "125" && new_value == "93")
                {
                    string str = "INSERT INTO CmdGongWei (cGWid,cGWlineCode,cManufacture) VALUES ('09','01','" + Manufacture + "')";
                    strD = str;
                }
                if (old_value == "123" && new_value == "91")
                {
                    string str = "INSERT INTO CmdGongWei (cGWid,cGWlineCode,cManufacture) VALUES ('09','02','" + Manufacture + "')";
                    strD = str;
                }
                if (old_value == "119" && new_value == "87")
                {
                    string str = "INSERT INTO CmdGongWei (cGWid,cGWlineCode,cManufacture) VALUES ('09','03','" + Manufacture + "')";
                    strD = str;
                }
                if (old_value == "111" && new_value == "79")
                {
                    string str = "INSERT INTO CmdGongWei (cGWid,cGWlineCode,cManufacture) VALUES ('09','04','" + Manufacture + "')";
                    strD = str;
                }
                try
                {
                    if (strD != "")
                    {
                        i = DbUtils.ExecuteNonQuerySp(strD);
                    }
                }
                catch (Exception ex)
                {
                    #region 错误日记
                    AppLog.WriteErr(ex.Message);
                    #endregion
                }
                finally
                {
                    #region 变化日记
                    AppLog.Write(System.Convert.ToString(Convert.ToInt32(old_value), 2).PadLeft(7, '0') + "--" + System.Convert.ToString(Convert.ToInt32(new_value), 2).PadLeft(7, '0') + "--插入标识:" + Convert.ToString(i) + "--" + strD);
                    #endregion
                }

                #endregion
            }
            catch (Exception ex)
            {
                #region 错误日记
                AppLog.WriteErr(ex.Message);
                #endregion
            }
        }
コード例 #22
0
 public void UpdateLastLoginTime(string fid)
 {
     DbUtils.ExecuteNonQuery("UPDATE TB_APP_USER SET LAST_LOGIN_TIME =:LAST_LOGIN_TIME WHERE FID =:FID", new { LAST_LOGIN_TIME = DateTime.Now, FID = fid });
 }
コード例 #23
0
        public async Task <HttpResponseMessage> PostUserImage()
        {
            Dictionary <string, object> dict    = new Dictionary <string, object>();
            Dictionary <string, object> product = new Dictionary <string, object>();

            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }
            var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

            var contentMP = filesReadToProvider.Contents;

            foreach (var item in contentMP)
            {
                if (item.Headers.ContentType.MediaType == "application/json")
                {
                    product[item.Headers.ContentDisposition.Name.ToString().Replace("\"", "")] = item.ReadAsStringAsync().Result;
                }
                else
                {
                    var fileBytes = await item.ReadAsByteArrayAsync();

                    int            MaxContentLength      = 1024 * 1024 * 5; //Size = 1 MB
                    IList <string> AllowedFileExtensions = new List <string> {
                        ".jpg", ".gif", ".png"
                    };
                    var filename = item.Headers.ContentDisposition.FileName;
                    filename = filename.Replace("\"", "");

                    var ext       = filename.Substring(filename.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    // extension= extension.Remove(extension.Length - 1, 1);
                    if (!AllowedFileExtensions.Contains(extension))
                    {
                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
                        dict.Add("error", message);

                        return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                    }
                    else if (item.Headers.ContentLength > MaxContentLength)
                    {
                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                    }
                    else
                    {
                        var httpPostedFile = HttpContext.Current.Request.Files["image"];

                        string relativepath = "~/productimage/" + product["ItemName"] + extension;
                        product["filepath"] = relativepath;
                        var filePath = HttpContext.Current.Server.MapPath(relativepath);
                        httpPostedFile.SaveAs(filePath);
                    }
                }
            }
            //db add


            var db = DbUtils.GetDBConnection();

            db.Connection.Open();
            // using (var scope = db.Connection.BeginTransaction())
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    var res = db.Query("fooditem").Insert(product);
                    scope.Complete();  // if record is entered successfully , transaction will be committed
                    db.Connection.Close();
                    return(Request.CreateResponse(HttpStatusCode.Created, new Dictionary <string, object>()
                    {
                        { "LastInsertedId", res }
                    }));
                }
                catch (Exception ex)
                {
                    scope.Dispose();   //if there are any error, rollback the transaction
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
                }
            }
        }
コード例 #24
0
 /// <summary>
 /// Creates a new ADO.NET data adapter.
 /// </summary>
 /// <returns>ready to use ADO.NET data-adapter</returns>
 protected override DbDataAdapter CreateDataAdapter()
 {
     return(DbUtils.CreateDataAdapter());
 }
コード例 #25
0
        /// <summary>
        /// 采购确认
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ConfirmSave(string action, List <ICPRBILLENTRYMODEL> data, User loginUser)
        {
            var conn = DbUtils.GetConnection();

            conn.Open();
            var tran = conn.BeginTransaction();

            try
            {
                foreach (ICPRBILLENTRYMODEL model in data)
                {
                    ICPRBILLENTRYMODEL uptModel = ICPRBILLENTRYDAL.Instance.Get(model.FID);


                    if (uptModel != null)
                    {
                        //uptModel.FACCOUNT = model.FACCOUNT;
                        //uptModel.FSTOREHOUSE = model.FSTOREHOUSE;
                        //uptModel.FPOLICY = model.FPOLICY;
                        uptModel.FCOMMITQTY = model.FCOMMITQTY;
                        //uptModel.FTRANSNAME = model.FTRANSNAME;
                        uptModel.FORDERREMARK1 = model.FORDERREMARK1;
                        uptModel.FORDERREMARK2 = model.FORDERREMARK2;

                        if (action == "confirm")
                        {
                            uptModel.FCONFIRM_USER = loginUser.FID;
                            uptModel.FCONFIRM_TIME = DateTime.Now;
                            uptModel.FSTATUS       = (int)Constant.ICPRBILL_FSTATUS.采购确认;
                        }
                        else if (action == "unconfirm")
                        {
                            var count = ICSEOUTBILLENTRYDAL.Instance.GetWhere(new { FICPRID = uptModel.FID }).ToList();
                            if (count.Count > 0)
                            {
                                continue;
                            }
                            uptModel.FSTATUS = (int)Constant.ICPRBILL_FSTATUS.审核通过;
                        }

                        LogHelper.WriteLog(JsonHelper.ToJson(uptModel));

                        DbUtils.Update(uptModel, conn, tran);
                    }
                }
                tran.Commit();
                conn.Close();

                var entry = ICPRBILLENTRYDAL.Instance.Get(data.First().FID);

                if (action == "unconfirm")
                {
                    DbUtils.UpdateWhatWhere <ICPRBILLMODEL>(new { FSTATUS = (int)Constant.ICPRBILL_FSTATUS.审核通过 }, new { FID = entry.FPLANID });
                }
                else
                {
                    if (ICPRBILLENTRYDAL.Instance.GetConfirmStatus(entry.FPLANID) == 0)
                    {
                    }
                    UpdateConfirmTime(entry.FID);
                    //LogHelper.WriteLog("Hello");
                }



                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("ConfirmError");
                LogHelper.WriteLog(ex);
                tran.Rollback();
                conn.Close();
                throw ex;
            }
        }
コード例 #26
0
ファイル: Home.cs プロジェクト: schifflee/LightBox
        private void fillTreeView()
        {
            if (cmbServers.Items.Count == 0)
            {
                return;
            }                                            //ama den iparxei kanenas server den to kanei
            sqlservers server = null;

            this.Invoke((MethodInvoker) delegate()
            {
                server = DbUtils.getSqlServerFromTable(serverData, cmbServers);
            });

            //edw prepei na bei to database kai mia if then else apo katw analoga ama kanei OldMySqlConnect se server i se database
            ConnectionResultSet result = DB.TestConnection(server);

            if (result.wasSuccessful)
            {
                MySqlConnection con       = (MySqlConnection)DB.connect(server);
                List <string>   databases = DbUtils.getDatabases(server, con);//con.getDatabases();
                if (hideSystemDatabases)
                {
                    databases = DbUtils.removeSystemDatabases(databases);
                }
                foreach (string database in databases)
                {
                    this.Invoke((MethodInvoker) delegate() {
                        TreeNode node        = new TreeNode(database);
                        node.ImageIndex      = 0;
                        List <string> tables = DbUtils.getTables(server, database, con);
                        foreach (string table in tables)
                        {
                            TreeNode tablenode   = new TreeNode(table);
                            tablenode.ImageIndex = 1;
                            node.Nodes.Add(tablenode);
                        }
                        tvDatabases.Nodes.Add(node);
                    });
                }

                this.Invoke((MethodInvoker) delegate() {
                    ToolStripMenuItem opendb    = new ToolStripMenuItem();
                    ToolStripMenuItem analyzedb = new ToolStripMenuItem();
                    opendb.Text           = "browse data";
                    opendb.Tag            = "sql";
                    opendb.Click         += new EventHandler(menuClick);
                    analyzedb.Text        = "inspect database";
                    analyzedb.Click      += new EventHandler(menuClick);
                    ContextMenuStrip menu = new ContextMenuStrip();
                    menu.Items.AddRange(new ToolStripMenuItem[] { opendb, analyzedb });
                    tvDatabases.ContextMenuStrip = menu;
                });
                DB.close(con);
            }
            else
            {
                this.Invoke((MethodInvoker) delegate() {
                    MessageBox.Show("Connection failed: \n" + result.errorMessage, "Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            }
        }
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     DbUtils.Clean();
 }
コード例 #28
0
        // event handler for Button
        public void SaveButton_Click_Base(object sender, EventArgs args)
        {
            bool   shouldRedirect = true;
            string target         = null;

            if (target == null)
            {
                target = "";             // avoid warning on VS
            }
            try {
                // Enclose all database retrieval/update code within a Transaction boundary
                DbUtils.StartTransaction();


                if (!this.IsPageRefresh)
                {
                    this.SaveData();
                }

                this.CommitTransaction(sender);
                string field            = "";
                string formula          = "";
                string displayFieldName = "";
                string value            = "";
                if (value == null)
                {
                    value = "";           // added to remove warning from VS
                }
                string id = "";
                if (id == null)
                {
                    id = "";        //added to avoid warning in VS
                }
                // retrieve necessary URL parameters
                if (!String.IsNullOrEmpty(Page.Request["Target"]))
                {
                    target = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("Target");
                }
                if (!String.IsNullOrEmpty(Page.Request["IndexField"]))
                {
                    field = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("IndexField");
                }
                if (!String.IsNullOrEmpty(Page.Request["Formula"]))
                {
                    formula = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("Formula");
                }
                if (!String.IsNullOrEmpty(Page.Request["DFKA"]))
                {
                    displayFieldName = (this.Page as BaseApplicationPage).GetDecryptedURLParameter("DFKA");
                }

                if (!string.IsNullOrEmpty(target) && !string.IsNullOrEmpty(field))
                {
                    if (this.FieldTripsRecordControl != null && this.FieldTripsRecordControl.DataSource != null)
                    {
                        id = this.FieldTripsRecordControl.DataSource.GetValue(this.FieldTripsRecordControl.DataSource.TableAccess.TableDefinition.ColumnList.GetByAnyName(field)).ToString();
                        if (!string.IsNullOrEmpty(formula))
                        {
                            System.Collections.Generic.IDictionary <String, Object> variables = new System.Collections.Generic.Dictionary <String, Object>();
                            variables.Add(this.FieldTripsRecordControl.DataSource.TableAccess.TableDefinition.TableCodeName, this.FieldTripsRecordControl.DataSource);
                            value = EvaluateFormula(formula, this.FieldTripsRecordControl.DataSource, null, variables);
                        }
                        else if (displayFieldName == "")
                        {
                            value = id;
                        }
                        else
                        {
                            value = this.FieldTripsRecordControl.DataSource.GetValue(this.FieldTripsRecordControl.DataSource.TableAccess.TableDefinition.ColumnList.GetByAnyName(displayFieldName)).ToString();
                        }
                    }
                    if (value == null)
                    {
                        value = id;
                    }
                    BaseClasses.Utils.MiscUtils.RegisterAddButtonScript(this, target, id, value);
                    shouldRedirect = false;
                }
                else if (!string.IsNullOrEmpty(target))
                {
                    BaseClasses.Utils.MiscUtils.RegisterAddButtonScript(this, target, null, null);
                    shouldRedirect = false;
                }
            } catch (Exception ex) {
                // Upon error, rollback the transaction
                this.RollBackTransaction(sender);
                shouldRedirect   = false;
                this.ErrorOnPage = true;

                // Report the error message to the end user
                BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            } finally {
                DbUtils.EndTransaction();
            }
            if (shouldRedirect)
            {
                this.ShouldSaveControlsToSession = true;
                this.RedirectBack();
            }
        }
 protected override void Dispose(bool disposing)
 {
     DbUtils.Clean(Database);
     base.Dispose(disposing);
 }
コード例 #30
0
        public void SaveSessions(DbUtils.Core.Api.IDbServerConnection[] sessions)
        {
            SqliteConnectionStringBuilder sbuilder = new SqliteConnectionStringBuilder ();
            sbuilder.DataSource = StateDbDataSource;

            using (SqliteConnection con = new SqliteConnection (sbuilder.ConnectionString)) {
                con.Open ();
                SaveSessions (sessions, con);
            }
        }
コード例 #31
0
 private int getDbTableRowsCount(string tableName, string dbname)
 {
     return(DbUtils.getTableRowCount(new sqlservers(credentialsConfigInstance.host, credentialsConfigInstance.port,
                                                    credentialsConfigInstance.username, credentialsConfigInstance.password), dbname, tableName));
 }