예제 #1
0
        /// <summary>
        /// Moves the specified folder and all of its content, by creating a ItemsDeletedChange and a ItemsCreatedChange.
        /// The two changes is returned inside of a ICollection.
        /// </summary>
        /// <param name="from">The relative path to copy from</param>
        /// <param name="to">The relative path to copy to</param>
        /// <returns>Returns the changes that makes the move possible</returns>
        protected ICollection<AbstractChange> MoveFolder(string from, string to)
        {
            ICollection<AbstractChange> returnCollection = new List<AbstractChange>();
            ItemsCreatedChange itemsCreation = new ItemsCreatedChange();

            SortedSet<String> entriesFullPaths = VersionSystemFacade.GetEntryPaths(from);

            itemsCreation.CreateItem(new FolderCreation(to));

            foreach (var entry in entriesFullPaths)
            {
                string newPath = to + "\\" + entry;
                newPath = newPath.Replace("\\\\", "\\");

                string oldPath = from + "\\" + entry;
                oldPath = oldPath.Replace("\\\\", "\\");

                if (VersionSystemFacade.GetVersionControlSystem(oldPath).IsDirectory(oldPath))
                {

                    itemsCreation.CreateItem(new FolderCreation(newPath + (newPath.EndsWith("\\") ? string.Empty : "\\")));
                }
                else
                {
                    string[] content = VersionSystemFacade.GetFileText(oldPath);
                    itemsCreation.CreateItem(new FileCreation(newPath, content));
                }
            }

            returnCollection.Add(itemsCreation);
            returnCollection.Add(DeleteFolder(from));

            return returnCollection;
        }
 public ChartData(List<Dictionary<string, string>> data, string title = "title", string xAxis = "X", 
     string yAxis = "Y", int height = 400, int width = 600)
 {
     ListOfDataSets = data;
     Title = title;
     XAxis = xAxis;
     YAxis = yAxis;
     Height = height;
     Width = width;
 }
예제 #3
0
 /// <summary>
 /// Visszaadja a játékosok neveit
 /// </summary>
 /// <returns></returns>
 public static List<string> getNamesOfPlayers()
 {
     List<string> retVal = new List<string>();
     string sqlCommand = "select name from dbUserSet";
     SqlCommand comm = new SqlCommand(sqlCommand);
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
         comm.Connection = conn;
         conn.Open();
         SqlDataReader dr = comm.ExecuteReader();
         while (dr.Read())
             retVal.Add(dr["name"].ToString());
     }
     return retVal;
 }
예제 #4
0
        /// <summary>
        /// Moves the specified file, by creating a ItemsDeletedChange (deleting the old file) and a ItemsCreatedChange (creating the file at the new path, with the content).
        /// The two changes is returned inside of a ICollection.
        /// </summary>
        /// <param name="from">The relative path to copy from</param>
        /// <param name="to">The relative path to copy to</param>
        /// <param name="content">The content of the file</param>
        /// <returns>Returns the changes that makes the move possible</returns>
        protected ICollection<AbstractChange> MoveFile(string from, string to, string content)
        {
            ICollection<AbstractChange> returnCollection = new List<AbstractChange>();

            ICreation creation = new FileCreation((to), content.Split('\n'));
            ItemsCreatedChange itemCreation = new ItemsCreatedChange();
            itemCreation.CreateItem(creation);

            ItemsDeletedChange itemDeletion = new ItemsDeletedChange();
            itemDeletion.DeleteItem(from);

            returnCollection.Add(itemCreation);
            returnCollection.Add(itemDeletion);

            return returnCollection;
        }
예제 #5
0
        protected void BindFiles()
        {
            List<FileResult> files = new List<FileResult>();

            int i = 1;
            foreach (string file in Directory.EnumerateFiles(Server.MapPath("~/Uploads/")))
            {
                FileInfo info = new FileInfo(file);
                files.Add(new FileResult { Name = Path.GetFileName(file), Path = file, Number = i, Size = info.Length, Uploaded = info.CreationTime });
                i++;
            }

            lblFileCount.Text = files.Count().ToString();

            gvFiles.DataSource = files;
            gvFiles.DataBind();
        }
예제 #6
0
파일: Node.cs 프로젝트: GarageInc/all
        public List<bool> Traverse(char symbol, List<bool> data)
        {
            // Лист
            if (Right == null && Left == null)
            {
                if (symbol.Equals(this.Symbol))
                {
                    return data;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                List<bool> left = null;
                List<bool> right = null;

                if (Left != null)
                {
                    List<bool> leftPath = new List<bool>();
                    leftPath.AddRange(data);
                    leftPath.Add(false);

                    left = Left.Traverse(symbol, leftPath);
                }

                if (Right != null)
                {
                    List<bool> rightPath = new List<bool>();
                    rightPath.AddRange(data);
                    rightPath.Add(true);
                    right = Right.Traverse(symbol, rightPath);
                }

                if (left != null)
                {
                    return left;
                }
                else
                {
                    return right;
                }
            }
        }
예제 #7
0
        public static List<Dictionary<string, object>> LayDanhSachSanBong()
        {
            var danhSach = new List<Dictionary<string, object>>();
            List<DM_SAN> listEntity;
            using (var context = new DB_9EEDEC_QLSBEntities())
            {
                listEntity = context.DM_SAN.ToList();

                foreach (DM_SAN item in listEntity)
                {
                    var san = new Dictionary<string, object>();
                    san["id"] = item.ID;
                    san["ten_san"] = item.TEN_SAN;
                    //san["ten_khu_san"] = item.DM_KHU_SAN.TEN_KHU_SAN;
                    var khuSan = context.DM_KHU_SAN.Where(s => s.ID == item.ID_KHU_SAN).First();
                    san["ten_khu_san"] = khuSan.TEN_KHU_SAN;
                    danhSach.Add(san);
                }

            }
            return danhSach;
        }
예제 #8
0
        // Кодирование
        public BitArray Encode(string source)
        {
            List<bool> encodedSource = new List<bool>();

            for (int i = 0; i < source.Length; i++)
            {
                //str += "'"+source[i]+"':[";
                List<bool> encodedSymbol = this.Root.Traverse(source[i], new List<bool>());
                foreach (bool ee in encodedSymbol)
                {
                    str+=ee?"1":"0";
                }
                //str += "] ";
                if(i!=source.Length-1)
                    str += " ";

                encodedSource.AddRange(encodedSymbol);
            }

            BitArray bits = new BitArray(encodedSource.ToArray());

            return bits;
        }
예제 #9
0
파일: Project.cs 프로젝트: semexion/APP
        public List<ComputerObject> SearchComputer(string query, string item)
        {
            //item = "description";
            //item = "name";

            List<ComputerObject> lst = new List<ComputerObject>();
            //if (!Roles.IsUserInRole("admin"))
            //{
            //    return lst;
            //}
            foreach (var adObject in ADObjectQuery.List(ADOil, new Contains(item, query)))
            {
                using (adObject)
                {
                    if (adObject.Type == ADObjectType.Computer)
                    {
                        ComputerObject Comp = (ComputerObject)adObject;
                        lst.Add(Comp);
                        //Clients.Caller.response_comp(Comp.Name, Comp.Description);
                    }
                }
            }
            return lst;
        }
예제 #10
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            //Declaring the list for storing movie values
            List<String> movieList = new List<string>();
            XmlReader xmlRead;
            string data;
            //Declaring the table for displaying data
            Table Table1 = new Table();
            Table1.BorderWidth = 1;

            try
            {
                //Storing the url of api to be used
                string url = "http://localhost:54743/Service1.svc/GetMovieByYear/" + TextBox1.Text;
                //Initializing the client
                WebClient wc = new WebClient();
                //Reading the data stream from the url
                StreamReader reader = new StreamReader(wc.OpenRead(url));
                data = reader.ReadToEnd();
                xmlRead = XmlReader.Create(new StringReader(data));

                //Creating table row for the headings
                TableRow tr = new TableRow();
                TableCell c = new TableCell();
                TableCell c2 = new TableCell();
                TableCell c3 = new TableCell();
                c.BorderWidth = 1;
                c2.BorderWidth = 1;
                c3.BorderWidth = 1;

                c.Controls.Add(new LiteralControl("Movie Title"));
                c2.Controls.Add(new LiteralControl("Popularity"));
                c3.Controls.Add(new LiteralControl("Rating"));

                tr.Cells.Add(c);
                tr.Cells.Add(c2);
                tr.Cells.Add(c3);

                Table1.Rows.Add(tr);
                //Reading the xml document until we reach the end
                while (!xmlRead.EOF)
                {

                    xmlRead.ReadToFollowing("MoviesDetail");
                    TableRow r = new TableRow();
                    //Reading the required nodes
                    xmlRead.ReadToFollowing("popularity");
                    string popularity = Convert.ToString(xmlRead.ReadString());
                    xmlRead.ReadToFollowing("rating");
                    string rating = Convert.ToString(xmlRead.ReadString());
                    xmlRead.ReadToFollowing("title");
                    string title = Convert.ToString(xmlRead.ReadString());

                    c = new TableCell();
                    c2 = new TableCell();
                    c3 = new TableCell();
                    c.BorderWidth = 1;
                    c2.BorderWidth = 1;
                    c3.BorderWidth = 1;
                    //Storing the values in the table cells
                    c.Controls.Add(new LiteralControl(title));
                    c2.Controls.Add(new LiteralControl(popularity));
                    c3.Controls.Add(new LiteralControl(rating));
                    //Adding cells to the row
                    r.Cells.Add(c);
                    r.Cells.Add(c2);
                    r.Cells.Add(c3);

                    //Adding row to the table
                    Table1.Rows.Add(r);
                }

                Table1.Visible = true;
                form1.Controls.Add(Table1);
            }
            catch (Exception) { }
        }
예제 #11
0
        /// <summary>
        /// Tries to save the folder according to the info shown in the view. 
        /// If the folder can't be renamed or moved the change wont take effect.
        /// And the user is sent back to the info.aspx page
        /// </summary>
        protected void SaveChanges(object sender, EventArgs e)
        {
            string oldFolderName = _path.Substring(0, _path.LastIndexOf(@"\"));
            string newName = NameTextBox.Text;

            bool hasBeenMoved = !oldFolderName.Equals(FolderDropDown.SelectedItem.ToString());
            bool hasBeenRenamed = !_name.Equals(newName);

            var vsc = VersionSystemFacade.GetVersionControlSystem(_path.Substring(4));

            if (hasBeenRenamed)
            {
                FileModifiedChange modification = new FileModifiedChange(VersionSystemFacade.GetPathRelativeToRepository(_absolutPath));
                modification.Rename(newName + "\\");

                if (vsc.Save(modification) != null)
                {
                    base.ShowWarning();
                    Response.Redirect("Info.aspx?path=" + _path);
                }
            }

            // respond URI is the orignal path (but might be with a new name)
            _responeUri = "info.aspx?path=Pie\\" + newName;

            if (hasBeenMoved)
            {
                string newFolder = FolderDropDown.SelectedItem.ToString().Substring(3) + @"\";
                List<AbstractChange> fileMovedChanges = new List<AbstractChange>();
                ICollection<AbstractChange> moveChanges = base.MoveFolder(_path.Substring(3), (newFolder + newName));

                fileMovedChanges.AddRange(moveChanges);

                // Adds the move-changes to the version control system.
                // Sets the respond URI.
                if (vsc.Save(fileMovedChanges).Any())
                {
                    // If there was any errors while moving (returned a not-empty collction),
                    // respond URI is the orignal path (but might be with a new name).
                    _responeUri = "info.aspx?path=Pie\\" + newName;
                }
                else
                {
                    // Else the respond URI is the new path.
                    _responeUri = "info.aspx?path=Pie\\" + newFolder + newName;
                }
            }

            // Redirect to view the info.aspx page, for the current file.
            Response.Redirect(_responeUri);
        }
예제 #12
0
        /// <summary>
        /// Tries to save the file according to the info shown in the view. 
        /// 
        /// First it is tried to merge and rename the current file, with the one on the server.
        /// If the file cant be mearged with the file on the server, 
        /// the user is being directed to the merge-view (merge.aspx).
        /// 
        /// Then it is tried to move the current file (if needed).
        /// If the file cant be moved, the move is being droped, 
        /// and the user is sent back to the info.aspx page
        /// </summary>
        protected void SaveChanges(object sender, EventArgs e)
        {
            // Gets all the differences between the new local file, and the old local file.
            FileModifiedChange modification = ModificationManager.CompareFileModifications(_path.Substring(4), VersionSystemFacade.ReadAllText(_path.Substring(3)), FileContent.Value);

            string oldFolderName = _path.Substring(0, _path.LastIndexOf(@"\"));
            bool hasBeenMoved = !oldFolderName.Equals(FolderDropDown.SelectedItem.ToString());
            bool hasBeenRenamed = !_name.Equals(NameTextBox.Text);

            string newName = NameTextBox.Text;

            if (hasBeenRenamed) { modification.Rename(newName); }

            // respond URI is the orignal path (but might be with a new name)
            _responeUri = "info.aspx?path=Pie\\" + newName;

            var vsc = VersionSystemFacade.GetVersionControlSystem(_path.Substring(3));
            Conflict? saveConflict = vsc.Save(modification);
            // If there occurs any conflicts while merging the current file with the server-version,
            // send the user to the merge.aspx page
            if (saveConflict != null)
            {
                Merge.CurrentConflinct = saveConflict;
                Response.Redirect("merge.aspx");
            }

            if (hasBeenMoved)
            {
                string newFolder = FolderDropDown.SelectedItem.ToString().Substring(3) + @"\";
                List<AbstractChange> fileMovedChanges = new List<AbstractChange>();
                ICollection<AbstractChange> moveChanges = MoveFile(_path.Substring(3), (newFolder + newName), FileContent.Value);

                fileMovedChanges.AddRange(moveChanges);

                // Adds the move-changes to the version control system.
                // Sets the respond URI.
                if (vsc.Save(fileMovedChanges).Count > 0)
                {
                    // If there was any errors while moving (returned a not-empty collction),
                    // respond URI is the orignal path (but might be with a new name).
                    _responeUri = "info.aspx?path=Pie\\" + newName;
                }
                else
                {
                    // Else the respond URI is the new path.
                    _responeUri = "info.aspx?path=Pie\\" + newFolder + newName;
                }
            }

            // Redirect to view the info.aspx page, for the current file.
            Response.Redirect(_responeUri);
        }
예제 #13
0
        public static List<List<Dictionary<string, object>>> ChiTietKhuSan(decimal id_khu_san, DateTime date)
        {
            using (var context = new DB_9EEDEC_QLSBEntities())
            {
                var item = new Dictionary<string, object>();
                var khu_san = context.DM_KHU_SAN.Where(s => s.ID == id_khu_san).First();
                List<DM_SAN> dsSan = khu_san.DM_SAN.OrderBy(s => s.TEN_SAN).ToList();
                int hang = dsSan.Count;
                List<DM_KHUNG_GIO> dsKhungGio = context.DM_KHUNG_GIO.OrderBy(s => s.GIO_BAT_DAU).ToList();
                int cot = dsKhungGio.Count + 1;
                var bang = new List<List<Dictionary<string, object>>>();
                var dsPhieu = context.GD_PHIEU_DAT_SAN.Where(s => s.NGAY_DA == date).ToList();
                for (int i = 0; i < hang; i++)
                {
                    var san = new List<Dictionary<string, object>>();
                    for (int j = 0; j < cot; j++)
                    {
                        var cell = new Dictionary<string, object>();
                        if (j == 0)
                        {
                            cell["ten_san"] = dsSan[i].TEN_SAN;
                        }
                        else
                        {
                            cell["id_san"] = dsSan[i].ID;
                            decimal gioBatDau = dsKhungGio[j - 1].GIO_BAT_DAU;
                            cell["gio_bat_dau"] = gioBatDau;
                            cell["ten_khach_hang"] = "";
                            cell["id_phieu_dat"] = "";
                            cell["gia"] = XemGia(dsSan[i].ID_KHU_SAN, date, gioBatDau);
                        }
                        san.Add(cell);
                    }
                    bang.Add(san);
                }
                foreach (GD_PHIEU_DAT_SAN phieu in dsPhieu)
                {
                    var chiTiet = phieu.GD_PHIEU_DAT_SAN_CHI_TIET.ToList();
                    foreach (GD_PHIEU_DAT_SAN_CHI_TIET phieuChiTiet in chiTiet)
                    {
                        if (phieuChiTiet.DM_SAN.ID_KHU_SAN == id_khu_san)
                        {
                            int i;
                            for (i = 0; i < hang; i++)
                            {
                                if (phieuChiTiet.ID_SAN == dsSan[i].ID) break;
                            }
                            int j;
                            for (j = 0; j < cot - 1; j++)
                            {
                                if (phieuChiTiet.ID_KHUNG_GIO == dsKhungGio[j].ID) break;
                            }
                            bang[i][j + 1]["ten_khach_hang"] = phieu.TEN_KHACH_HANG;
                            bang[i][j + 1]["id_phieu_dat"] = phieu.ID;
                            //bang[i][j + 1]["gia"] = XemGia(id_khu_san,date,phieuChiTiet.DM_KHUNG_GIO.GIO_BAT_DAU);
                            //bang[i][j + 1]["gia"] = "";

                        }
                    }
                }
                return bang;
            }
        }
예제 #14
0
 public static List<Dictionary<string, object>> LayDanhSachKhuSan()
 {
     var danhSach = new List<Dictionary<string, object>>();
     using (var context = new DB_9EEDEC_QLSBEntities())
     {
         var listKhuSan = context.DM_KHU_SAN.ToList();
         foreach (var item in listKhuSan)
         {
             var khuSan = new Dictionary<string, object>();
             khuSan["id"] = item.ID;
             khuSan["ten_khu_san"] = item.TEN_KHU_SAN;
             khuSan["so_dien_thoai"] = item.SO_DIEN_THOAI;
             khuSan["dia_chi"] = item.DIA_CHI;
             danhSach.Add(khuSan);
         }
         return danhSach;
     }
 }
예제 #15
0
        // Дополнительные сведения о настройке проверки подлинности см. по адресу: http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Настройка контекста базы данных, диспетчера пользователей и диспетчера входа для использования одного экземпляра на запрос
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            var cookieOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(20),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            };
            // Включение использования файла cookie, в котором приложение может хранить информацию для пользователя, выполнившего вход,
            app.UseCookieAuthentication(cookieOptions);
            // Использование файла cookie для временного хранения информации о входах пользователя с помощью стороннего поставщика входа
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Позволяет приложению временно хранить информацию о пользователе, пока проверяется второй фактор двухфакторной проверки подлинности.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Позволяет приложению запомнить второй фактор проверки имени входа. Например, это может быть телефон или почта.
            // Если выбрать этот параметр, то на устройстве, с помощью которого вы входите, будет сохранен второй шаг проверки при входе.
            // Точно так же действует параметр RememberMe при входе.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Включение использования приложением маркера-носителя для проверки подлинности пользователей
            app.UseOAuthBearerTokens(OAuthOptions);

            // Раскомментируйте приведенные далее строки, чтобы включить вход с помощью сторонних поставщиков входа
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            //app.UseVkontakteAuthentication(new VkAuthenticationOptions
            //{
            //    // You should add "email" as a parameter for scope
            //    // if you are willing to receive user email
            //    Scope = new List<string>() { "email" },
            //    ClientId = "5074012",
            //    ClientSecret = "NGSd1D3XME4KPLdykpQC"

            //});
            //app.UseInstagramAuthentication("abf3fe9816ee4173abf0a9b13fa91fdf", "57913357bcbe476ebafa0cd4251f5ec5");

            //Enable Mixed Authentication
            //As we are using LogonUserIdentity, its required to run in PipelineStage.PostAuthenticate
            //Register this after any middleware that uses stage marker PipelineStage.Authenticate
            //See http://www.asp.net/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline
            app.UseMixedAuth(
                new MixedAuthOptions()
            {
                Provider = new MixedAuthProvider()
                {
                    OnImportClaims = identity =>
                    {
                        List<Claim> claims = new List<Claim>();
                        using (var principalContext = new PrincipalContext(ContextType.Domain | ContextType.Machine))
                        {
                            using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, identity.Name))
                            {
                                if (userPrincipal != null)
                                {
                                    claims.Add(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress ?? string.Empty));
                                    claims.Add(new Claim(ClaimTypes.Surname, userPrincipal.Surname ?? string.Empty));
                                    claims.Add(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName ?? string.Empty));
                                }
                            }
                        }
                        return claims;
                    }
                }
            },
            cookieOptions);
        }
 public string[] GetCities(string prefixText, int count, Dictionary<string, string> contextValues)
 {
     List<string> cities = new List<string>(_lookupService.GetCities(prefixText,
                                                                     contextValues["State"],
                                                                     count));
     return cities.ToArray();
 }
 public string[] GetZipCodes(string prefixText, int count, Dictionary<string, string> contextValues)
 {
     List<ZipCode> zips = new List<ZipCode>(_lookupService.GetZipCodes(prefixText,
                                                          contextValues["City"],
                                                          contextValues["State"],
                                                          count));
     return zips.ConvertAll<string>(delegate(ZipCode zip) { return zip.PostalCode; }).ToArray();
 }
예제 #18
0
 public static List<string> getTop5Players()
 {
     List<string> retVal = new List<string>();
     SqlCommand comm = new SqlCommand("getTop5Winner") { CommandType = System.Data.CommandType.StoredProcedure };
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
         comm.Connection = conn;
         conn.Open();
         SqlDataReader dr = comm.ExecuteReader();
         while (dr.Read())
             retVal.Add(dr[0].ToString());
     }
     return retVal;
 }
예제 #19
0
파일: Project.cs 프로젝트: semexion/APP
        public List<UserObject> SearchUsers(string query)
        {
            List<UserObject> lst = new List<UserObject>();

            IFilter filter = new Or(new Contains("ObjectSID", query),
                                    new Contains("name", query),
                                    new Contains(PersonAttributeNames.TelephoneNumber, query),
                                    new Contains(PersonAttributeNames.Department, query),
                                    new Contains(PersonAttributeNames.Title, query));

            foreach (var adObject in ADObjectQuery.List(ADOil, filter))
            {
                using (adObject)
                {
                    if (adObject.Type == ADObjectType.User)
                    {
                        UserObject User = (UserObject)adObject;
                        lst.Add(User);
                    }
                }
            }
            return lst;
        }
        public ActionResult Edit(Entry entry, int[] selectedCategories, string huKeywords, string enKeywords, string toDeleteFiles)
        {
            var toEditEntry = db.Entries.Where(e => e.Id == entry.Id).First();
            KeywordsProcedure(toEditEntry, huKeywords, enKeywords);

            var attachments = TempData["Attachments"] as List<string>;
            var featuredImage = TempData["FeaturedImage"] as List<string>;

            if (ModelState.IsValid)
            {
                toEditEntry.enContent = entry.enContent;
                toEditEntry.enIntroduction = entry.enIntroduction;
                toEditEntry.enTitle = entry.enTitle;
                toEditEntry.huContent = entry.huContent;
                toEditEntry.huIntroduction = entry.huIntroduction;
                toEditEntry.huTitle = entry.huTitle;
                toEditEntry.IsFeatured = entry.IsFeatured;
                toEditEntry.Published = entry.Published;
                toEditEntry.PublishedDate = entry.PublishedDate;
                toEditEntry.UserId = int.Parse((string)Session["UserId"]);
                toEditEntry.Categories.Clear();
                foreach (var id in selectedCategories.ToList())
                {
                    Category category = db.Categories.Single(e => e.Id == id);
                    toEditEntry.Categories.Add(category);
                }
                //Delete to delete
                List<string> fileNames = new List<string>();
                foreach (var idString in toDeleteFiles.Split(',').Where(e => e != ""))
                {
                    int id = int.Parse(idString);
                    var file = db.Files.Where(e => e.Id == id).First();
                    fileNames.Add(file.Name);
                    toEditEntry.Files.Remove(file);
                    db.Files.Remove(file);
                }
                var ctrl = new UploadController();
                ctrl.PathValue = "/Public/Files/";
                ctrl.Remove(fileNames.ToArray());
                //Add new ones
                if (attachments != null)
                {
                    foreach (var att in attachments)
                    {
                        WebApplication.File newAtt = new WebApplication.File { Entry = toEditEntry, Location = Guid.NewGuid().ToString(), Name = Path.GetFileName(att) };
                        db.Files.Add(newAtt);
                    }
                }
                if (featuredImage != null && featuredImage.Count > 0)
                {
                    string[] fileName = { Path.GetFileName(entry.FeaturedImage) };
                    ctrl.PathValue = "/Public/Images/";
                    ctrl.Remove(fileName);
                    toEditEntry.FeaturedImage = featuredImage[0];
                }
                else if (string.IsNullOrEmpty(entry.FeaturedImage))
                {
                    toEditEntry.FeaturedImage = "";
                }
                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                }

                TempData["Attachments"] = null;
                TempData["FeaturedImage"] = null;

                return RedirectToAction("Index");
            }

            ViewBag.Categories = db.Categories.Select(e => e);
            ViewBag.SelectedCategories = selectedCategories.ToList();
            ViewBag.enKeywords = db.Keywords.Where(e => e.Type == true);
            ViewBag.huKeywords = db.Keywords.Where(e => e.Type == false);
            return View(entry);
        }
예제 #21
0
        public static List<Dictionary<string, object>> LayDanhSachKhungGio()
        {
            var danhSach = new List<Dictionary<string, object>>();
            List<DM_KHUNG_GIO> listEntity;
            using (var context = new DB_9EEDEC_QLSBEntities())
            {
                listEntity = context.DM_KHUNG_GIO.OrderBy(s => s.GIO_BAT_DAU).ToList();

                foreach (DM_KHUNG_GIO item in listEntity)
                {
                    var gio = new Dictionary<string, object>();
                    gio["id"] = item.ID;
                    gio["gio_bat_dau"] = item.GIO_BAT_DAU;
                    danhSach.Add(gio);
                }
            }
            return danhSach;
        }