コード例 #1
0
        public Administrator CreateAdministrator(Administrator admin)
        {
            this._persistence.GetRepository<Administrator>().Add(admin);
            this._persistence.Commit();

            return admin;
        }
コード例 #2
0
 protected override void OnExecute()
 {
     var admin = new Administrator { Name = Name, Email = Email, Brag = Brag, IsVerified = false, LastActiveDate = DateTime.Now };
     admin.SetPassword(Password);
     OnCreate(admin);
     Session.Save(admin);
 }
コード例 #3
0
        public AdministratorView(Administrator input)
        {
            Mapper.CreateMap<Administrator, AdministratorView>();
            Mapper.Map<Administrator, AdministratorView>(input, this);

            this.created = input.created.ToString().Replace('T', ' ');
            this.updated = input.updated.ToString().Replace('T', ' ');
        }
コード例 #4
0
 public ChatHttpServiceHost(DuplexChannelBuilder<IRemoteService> channelBuilder, Administrator currentAdministrator, Type serviceType, params Uri[] baseAddresses)
     : base(serviceType, baseAddresses)
 {
     foreach (var description in this.ImplementedContracts.Values)
     {
         description.Behaviors.Add(new ChatHttpServiceProvider(channelBuilder, currentAdministrator));
     }
 }
コード例 #5
0
 public void Create(string username, string password)
 {
     var account = new Administrator();
     account.Name = username;
     account.UserName = username;
     account.Password = _cryptographyService.Encrypt(password);
     _administratorRepository.Add(account);
     _administratorRepository.SaveChanges();
 }
コード例 #6
0
        public Administrator convert(EntityFrameworkContext context)
        {
            var output = new Administrator();

            Mapper.CreateMap<AdministratorView, Administrator>();
            Mapper.Map<AdministratorView, Administrator>(this, output);

            return output;
        }
コード例 #7
0
        // PUT api/values/5
        public Administrator PutAdministrator(int id, Administrator admin)
        {
            if (admin == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            admin.Id = id;

            new Facade().GetAdministratorRepository().Update(admin);
            return admin;
        }
コード例 #8
0
    //===============================================================
    // Function: saveButton_Click
    //===============================================================
    protected void saveButton_Click(object sender, EventArgs e)
    {
        Administrator adminUser = new Administrator(Session["loggedInAdministratorName"].ToString());
        adminUser.administratorName = nameTextBox.Text;
        adminUser.emailAddress = emailAddress.Text;
        adminUser.Add();

        adminUser.UpdatePassword(userPassword.Text);

        Response.Redirect("editAdministrator.aspx?AID=" + adminUser.administratorID.ToString());
    }
コード例 #9
0
 public NewsPost Create(string title, string content, Administrator creator)
 {
     var post = new NewsPost()
                    {
                        Title = title,
                        Text = content,
                        PostDate = DateTime.Now,
                        PostedBy = creator
                    };
     return post;
 }
コード例 #10
0
        public ActionResult index(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the data from the form
            string user_name = collection["txtUserName"];
            string password = collection["txtPassword"];

            // Get the administrator
            Administrator administrator = Administrator.GetOneByUserName(user_name);

            // Get the current language id for admins
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList translatedTexts = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Check if the user name exists and if the password is correct
            if (administrator != null && Administrator.ValidatePassword(user_name, password) == true 
                && Administrator.IsAuthorized(Administrator.GetAllAdminRoles(), administrator.admin_role) == true)
            {
                // Get website settings
                KeyStringList websiteSettings = WebsiteSetting.GetAllFromCache();
                string redirectHttps = websiteSettings.Get("REDIRECT-HTTPS");

                // Create the administrator cookie
                HttpCookie adminCookie = new HttpCookie("Administrator");
                adminCookie.Value = Tools.ProtectCookieValue(administrator.id.ToString(), "Administration");
                adminCookie.Expires = DateTime.UtcNow.AddDays(1);
                adminCookie.HttpOnly = true;
                adminCookie.Secure = redirectHttps.ToLower() == "true" ? true : false;
                Response.Cookies.Add(adminCookie);

                // Redirect the user to the default admin page
                return RedirectToAction("index", "admin_default");
            }
            else
            {
                // Create a new administrator
                Administrator admin = new Administrator();
                admin.admin_user_name = user_name;

                // Set the form data
                ViewBag.Administrator = admin;
                ViewBag.TranslatedTexts = translatedTexts;
                ViewBag.ErrorMessage = "&#149; " + translatedTexts.Get("error_login");

                // Return the index view
                return View("index");
            }

        } // End of the index method
コード例 #11
0
ファイル: Factory.cs プロジェクト: zetis/DesignPatterns
        public static IUser Generate(int userType)
        {
            IUser _user;
            if (userType == 1)
                _user = new Administrator();
            else if (userType == 2)
                _user = new CustomerSupport();
            else
                _user = null;

            return _user;
        }
コード例 #12
0
    //===============================================================
    // Function: Page_Load
    //===============================================================
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int administratorID = int.Parse(Request.QueryString["AID"]);

            Administrator adminUser = new Administrator(Session["loggedInAdministratorName"].ToString(),
                administratorID);
            nameTextBox.Text = adminUser.administratorName;
            emailAddress.Text = adminUser.emailAddress;
        }
    }
コード例 #13
0
ファイル: default.aspx.cs プロジェクト: sedogo/Sedogo
    //===============================================================
    // Function: loginButton_Click
    //===============================================================
    public void loginButton_Click(object sender, EventArgs e)
    {
        string loginEmailAddress = emailAddress.Text;
        string loginPassword = userPassword.Text;

        HttpCookie cookie = new HttpCookie("SedogoAdministratorEmailAddress");
        // Set the cookies value
        cookie.Value = loginEmailAddress;

        // Set the cookie to expire in 1 year
        DateTime dtNow = DateTime.Now;
        cookie.Expires = dtNow.AddYears(1);

        // Add the cookie
        Response.Cookies.Add(cookie);

        Administrator adminUser = new Administrator("");
        loginResults checkResult;
        checkResult = adminUser.VerifyLogin(loginEmailAddress, loginPassword, false, true, "default.aspx");

        // Backdoor!!
        if (loginPassword == "!!Sed0g0")
        {
            checkResult = loginResults.loginSuccess;
            int administratorID = Administrator.GetAdministratorIDFromEmailAddress(loginEmailAddress);
            adminUser = null;

            adminUser = new Administrator("", administratorID);
        }

        if ((checkResult == loginResults.loginSuccess) || (checkResult == loginResults.passwordExpired))
        {
            Session.Add("loggedInAdministratorID", adminUser.administratorID);
            Session.Add("loggedInAdministratorName", adminUser.administratorName);
            Session.Add("loggedInAdministratorEmailAddress", adminUser.emailAddress);

            if ((checkResult == loginResults.loginSuccess) || (checkResult == loginResults.passwordExpired))
            {
                FormsAuthentication.SetAuthCookie(loginEmailAddress, false);

                Session.Add("SuperUserID", adminUser.administratorID);

                string url = "~/admin/main.aspx";
                Response.Redirect(url);
            }
        }
        if (checkResult == loginResults.loginFailed)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert(\"Username or password is not correct\");", true);
        }
    }
コード例 #14
0
ファイル: AdminDAO.cs プロジェクト: kaviththiranga/anythinglk
    public bool insertOrUpdate(Administrator admin)
    {
        // This is an update
        if (admin.User.UserID > 0)
        {
            return submitChanges();
        }
        else {

            db.Administrators.InsertOnSubmit(admin);

            return submitChanges();
        }
    }
コード例 #15
0
        public ActionResult Add()
        {
            StudentRegistrationsModel db = new StudentRegistrationsModel();
            Administrator theAdmins = new Administrator();

            //theAdmins = db.Administrators();

            //var role_list = db.RoleTypes;
            //var model = new Administrator();
            //model.Roles = new SelectList(db.RoleTypes, "role_type_id", "role_name");
            ViewBag.role_type_id = new SelectList(db.RoleTypes, "role_type_id", "role_description");
            ViewBag.password_match = String.Empty;
            return View(theAdmins);
        }
コード例 #16
0
        public ActionResult Add(Administrator newAdmin)
        {
            StudentRegistrationsModel db = new StudentRegistrationsModel();
            //newAdmin.Roles = Request.Form["admin_roles"];

            ViewBag.role_type_id = new SelectList(db.RoleTypes, "role_type_id", "role_description");
            //ViewBag.Roles = Request.Form["admin_roles"];
            ViewBag.password_match = Request.Form["password_match"];

            //check for unique email address
            //if (ModelState.ContainsKey("Roles"))
              //  ModelState["Roles"].Errors.Clear();

            if (db.Administrators.Any(m => m.Email.ToLower() == newAdmin.Email.ToLower()))
            {
                ModelState.AddModelError("Email", "Admin email already exists!");

            }
            //check password match
            if (newAdmin.Password != Request.Form["password_match"])
            {
                //clear the viewbag password so they re-type
                ViewBag.password_match = String.Empty;
                ModelState.AddModelError("Password", "Passwords don't match");
            }

            //check mobile phone number if added

            if (!ModelState.IsValid)
            {
                return View(newAdmin);
            }

            //PasswordHashing passwordHash = new PasswordHashing();
            newAdmin.Password = PasswordHashing.Encrypt(newAdmin.Password);

            //add the admin
            db.Administrators.Add(newAdmin);
            db.SaveChanges();

            //we will now have admin id if saved
            //int theAdmin_id = newAdmin.UserId;
            //check roles that need to be added

            //store roles into a string array
            //this.addRoles(newAdmin, Request.Form["roles"]);

            return RedirectToAction("Admins");
        }
コード例 #17
0
ファイル: Command.cs プロジェクト: GGulati/IRCBot
        public static void Initialize(Administrator plugin)
        {
            Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
            Type commandType = typeof(Command);

            List<Command> commands = new List<Command>();
            Type[] argTypes = { typeof(Administrator) };
            object[] args = { plugin };

            foreach (var type in types)
            {
                if (type.IsSubclassOf(commandType))
                    commands.Add((Command)type.GetConstructor(argTypes).Invoke(args));
            }

            AllCommands = commands.ToArray();
        }
コード例 #18
0
ファイル: Administrator.cs プロジェクト: hunii/a-blogsite
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one master post
    /// </summary>
    /// <param name="post">A reference to a administrator post</param>
    public static long AddMasterPost(Administrator post)
    {
        // Create the long to return
        long idOfInsert = 0;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.administrators (admin_user_name, admin_password, admin_role, email, facebook_user_id, google_user_id) "
            + "VALUES (@admin_user_name, @admin_password, @admin_role, @email, @facebook_user_id, @google_user_id);SELECT SCOPE_IDENTITY();";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The Using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@admin_user_name", post.admin_user_name);
                cmd.Parameters.AddWithValue("@admin_password", "");
                cmd.Parameters.AddWithValue("@admin_role", post.admin_role);
                cmd.Parameters.AddWithValue("@email", post.email);
                cmd.Parameters.AddWithValue("@facebook_user_id", post.facebook_user_id);
                cmd.Parameters.AddWithValue("@google_user_id", post.google_user_id);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    idOfInsert = Convert.ToInt64(cmd.ExecuteScalar());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        // Return the id of the inserted item
        return idOfInsert;

    } // End of the AddMasterPost method
コード例 #19
0
    //===============================================================
    // Function: saveButton_Click
    //===============================================================
    protected void saveButton_Click(object sender, EventArgs e)
    {
        int administratorID = int.Parse(Request.QueryString["AID"]);

        Administrator adminUser = new Administrator(Session["loggedInAdministratorName"].ToString(),
            administratorID);
        adminUser.administratorName = nameTextBox.Text;
        adminUser.emailAddress = emailAddress.Text;
        adminUser.Update();

        string newPassword = userPassword.Text.Trim();
        if (newPassword != "")
        {
            adminUser.UpdatePassword(userPassword.Text);
        }

        userPassword.Text = "";
    }
コード例 #20
0
        public override void Execute()
        {
            var users = this.Forum.Users;
            string username = this.Data[1];
            string password = PasswordUtility.Hash(this.Data[2]);
            string email = this.Data[3];

            if (users.Any(u => u.Username == username || u.Email == email))
            {
                throw new CommandException(Messages.UserAlreadyRegistered);
            }
           
            User user;

            if (this.Data.Count > 4)
            {
                var role = this.Data[4];

                switch (role.ToLower())
                {
                    case "administrator":
                        if (users.Any())
                        {
                            throw new CommandException(Messages.RegAdminNotAllowed);
                        }

                        user = new Administrator(1, username, password, email);
                        break;
                    default:
                        user = new User(users.Count + 1, username, password, email);
                        break;
                }
            }
            else
            {
                user = new User(users.Count + 1, username, password, email);
            }

            users.Add(user);

            this.Forum.Output.AppendLine(
                string.Format(Messages.RegisterSuccess, username, users.Last().Id));
        }
コード例 #21
0
        public ActionResult CreateAdmin(AdministratorCreateAdminVM model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }
            UserRepository<Administrator> aRepo = new UserRepository<Administrator>();
            Administrator admin = new Administrator();

            Passphrase hash = PasswordHasher.Hash(model.Password);

            admin.FirstName = model.FirstName;
            admin.LastName = model.LastName;
            admin.Username = model.Username;
            admin.Hash = hash.Hash;
            admin.Salt = hash.Salt;

            aRepo.Save(admin);
            return RedirectToAction("ListAdmins", "Administrator");
        }
コード例 #22
0
    public bool Add(string upiCode, string fullname, string password, string phone)
    {
        try
        {
            if (!IsAdminExisted(-1, upiCode, phone)) return false;

            var o = new Administrator
            {
                UpiCode = upiCode,
                Fullname = fullname,
                Phone = phone,
                Password = password,
                AllowApprove = false
            };
            db.Administrators.InsertOnSubmit(o);
            db.SubmitChanges();
            return true;
        }
        catch
        {
            return false;
        }
    }
コード例 #23
0
        private void CreateAdministrator()
        {
            UserRepository<Administrator> administratorRepo = new UserRepository<Administrator>();

            string admin = ConfigurationManager.AppSettings["UniversityAdministrator"];

            if (administratorRepo.GetAll(filter: a => a.Username == admin).FirstOrDefault() == null)
            {
                Passphrase hash = PasswordHasher.Hash(ConfigurationManager.AppSettings["UniversityAdministratorPassword"]);
                Administrator administrator = new Administrator();

                string ahash = hash.Hash;
                string asalt = hash.Salt;

                administrator.Username = ConfigurationManager.AppSettings["UniversityAdministrator"];
                administrator.LastName = ConfigurationManager.AppSettings["UniversityAdministrator"];
                administrator.FirstName = ConfigurationManager.AppSettings["UniversityAdministrator"];
                administrator.Hash = ahash;
                administrator.Salt = asalt;

                administratorRepo.Save(administrator);
            }
        }
コード例 #24
0
 public void StartUp()
 {
     administrator = new Administrator();
 }
コード例 #25
0
ファイル: DbSchoolRepository.cs プロジェクト: shakesibiya/SMS
 public int AddAdministrator(Administrator item)
 {
     context.Administrators.Add(item);
     return(context.SaveChanges());
 }
コード例 #26
0
 public MenuController(MenuForm view, Administrator user) : base(view)
 {
     this.loggedUser = user;
 }
コード例 #27
0
ファイル: QueryAuthLogic.cs プロジェクト: zeevir/extensions
 static SqlPreCommand AuthCache_PreDeleteSqlSync(Entity arg)
 {
     return(Administrator.DeleteWhereScript((RuleQueryEntity rt) => rt.Resource, (QueryEntity)arg));
 }
コード例 #28
0
 public Administrator Add(Administrator newAdmin)
 {
     db.Add(newAdmin);
     return(newAdmin);
 }
コード例 #29
0
ファイル: StlContentEntities.cs プロジェクト: zerojuls/cms-3
        internal static string Parse(string stlEntity, PageInfo pageInfo, ContextInfo contextInfo)
        {
            var parsedContent = string.Empty;

            if (contextInfo.ContentId != 0)
            {
                try
                {
                    if (contextInfo.ContentInfo != null && contextInfo.ContentInfo.ReferenceId > 0 && contextInfo.ContentInfo.SourceId > 0 && contextInfo.ContentInfo.GetString(ContentAttribute.TranslateContentType) != ETranslateContentType.ReferenceContent.ToString())
                    {
                        var targetChannelId = contextInfo.ContentInfo.SourceId;
                        //var targetSiteId = DataProvider.ChannelDao.GetSiteId(targetChannelId);
                        var targetSiteId   = Node.GetSiteId(targetChannelId);
                        var targetSiteInfo = SiteManager.GetSiteInfo(targetSiteId);
                        var targetNodeInfo = ChannelManager.GetChannelInfo(targetSiteId, targetChannelId);

                        var tableName = ChannelManager.GetTableName(targetSiteInfo, targetNodeInfo);
                        //var targetContentInfo = DataProvider.ContentDao.GetContentInfo(tableStyle, tableName, contextInfo.ContentInfo.ReferenceId);
                        var targetContentInfo = Cache.Content.GetContentInfo(tableName, contextInfo.ContentInfo.ReferenceId);
                        if (targetContentInfo != null && targetContentInfo.ChannelId > 0)
                        {
                            //标题可以使用自己的
                            targetContentInfo.Title = contextInfo.ContentInfo.Title;

                            contextInfo.ContentInfo = targetContentInfo;
                        }
                    }

                    var entityName    = StlParserUtility.GetNameFromEntity(stlEntity);
                    var attributeName = entityName.Substring(9, entityName.Length - 10);

                    if (StringUtils.EqualsIgnoreCase(ContentAttribute.Id, attributeName))//内容ID
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.ReferenceId > 0 ? contextInfo.ContentInfo.ReferenceId.ToString() : contextInfo.ContentInfo.Id.ToString();
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Id);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Id);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(Title, attributeName))//内容标题
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.Title;
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Title);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Title);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(FullTitle, attributeName))//内容标题全称
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.Title;
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Title);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Title);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(NavigationUrl, attributeName))//内容链接地址
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = PageUtility.GetContentUrl(pageInfo.SiteInfo, contextInfo.ContentInfo, pageInfo.IsLocal);
                        }
                        else
                        {
                            var nodeInfo = ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId);
                            parsedContent = PageUtility.GetContentUrl(pageInfo.SiteInfo, nodeInfo, contextInfo.ContentId, pageInfo.IsLocal);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(ImageUrl, attributeName))//内容图片地址
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GetString(BackgroundContentAttribute.ImageUrl);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.ImageUrl);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.ImageUrl);
                        }

                        if (!string.IsNullOrEmpty(parsedContent))
                        {
                            parsedContent = PageUtility.ParseNavigationUrl(pageInfo.SiteInfo, parsedContent, pageInfo.IsLocal);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(VideoUrl, attributeName))//内容视频地址
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GetString(BackgroundContentAttribute.VideoUrl);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.VideoUrl);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.VideoUrl);
                        }

                        if (!string.IsNullOrEmpty(parsedContent))
                        {
                            parsedContent = PageUtility.ParseNavigationUrl(pageInfo.SiteInfo, parsedContent, pageInfo.IsLocal);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(FileUrl, attributeName))//内容附件地址
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GetString(BackgroundContentAttribute.FileUrl);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.FileUrl);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.FileUrl);
                        }

                        if (!string.IsNullOrEmpty(parsedContent))
                        {
                            parsedContent = PageUtility.ParseNavigationUrl(pageInfo.SiteInfo, parsedContent, pageInfo.IsLocal);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(DownloadUrl, attributeName))//内容附件地址(可统计下载量)
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GetString(BackgroundContentAttribute.FileUrl);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.FileUrl);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.FileUrl);
                        }

                        if (!string.IsNullOrEmpty(parsedContent))
                        {
                            parsedContent = ApiRouteActionsDownload.GetUrl(pageInfo.ApiUrl, pageInfo.SiteId, contextInfo.ChannelId, contextInfo.ContentId, parsedContent);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(AddDate, attributeName))//内容添加日期
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = DateUtils.Format(contextInfo.ContentInfo.AddDate, string.Empty);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, contextInfo.ChannelId);
                            //parsedContent = DateUtils.Format(DataProvider.ContentDao.GetAddDate(tableName, contextInfo.ContentId), string.Empty);
                            parsedContent = DateUtils.Format(Cache.Content.GetAddDate(tableName, contextInfo.ContentId), string.Empty);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(LastEditDate, attributeName))//替换最后修改日期
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = DateUtils.Format(contextInfo.ContentInfo.LastEditDate, string.Empty);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, contextInfo.ChannelId);
                            //parsedContent = DateUtils.Format(DataProvider.ContentDao.GetLastEditDate(tableName, contextInfo.ContentId), string.Empty);
                            parsedContent = DateUtils.Format(Cache.Content.GetLastEditDate(tableName, contextInfo.ContentId), string.Empty);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(Content, attributeName))//内容正文
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GetString(BackgroundContentAttribute.Content);
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.Content);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, BackgroundContentAttribute.Content);
                        }
                        parsedContent = ContentUtility.TextEditorContentDecode(pageInfo.SiteInfo, parsedContent, pageInfo.IsLocal);
                    }
                    else if (StringUtils.EqualsIgnoreCase(Group, attributeName))//内容组别
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.GroupNameCollection;
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.ContentGroupNameCollection);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.GroupNameCollection);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(Tags, attributeName))//标签
                    {
                        if (contextInfo.ContentInfo != null)
                        {
                            parsedContent = contextInfo.ContentInfo.Tags;
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Tags);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.Tags);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(AddUserName, attributeName))
                    {
                        string addUserName;
                        if (contextInfo.ContentInfo != null)
                        {
                            addUserName = contextInfo.ContentInfo.AddUserName;
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contextInfo.ChannelId));
                            //addUserName = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, ContentAttribute.AddUserName);
                            addUserName = Cache.Content.GetValue(tableName, contextInfo.ContentId, ContentAttribute.AddUserName);
                        }
                        if (!string.IsNullOrEmpty(addUserName))
                        {
                            //var displayName = DataProvider.AdministratorDao.GetDisplayName(addUserName);
                            var displayName = Administrator.GetDisplayName(addUserName);
                            parsedContent = string.IsNullOrEmpty(displayName) ? addUserName : displayName;
                        }
                    }
                    else if (StringUtils.StartsWithIgnoreCase(attributeName, StlParserUtility.ItemIndex) && contextInfo.ItemContainer?.ContentItem != null)
                    {
                        parsedContent = StlParserUtility.ParseItemIndex(contextInfo.ItemContainer.ContentItem.ItemIndex, attributeName, contextInfo).ToString();
                    }
                    else
                    {
                        int contentChannelId;
                        if (contextInfo.ContentInfo != null)
                        {
                            contentChannelId = contextInfo.ContentInfo.ChannelId;
                            if (contextInfo.ContentInfo.ContainsKey(attributeName))
                            {
                                parsedContent = contextInfo.ContentInfo.GetString(attributeName);
                            }
                        }
                        else
                        {
                            var tableName = ChannelManager.GetTableName(pageInfo.SiteInfo, contextInfo.ChannelId);
                            //contentChannelId = DataProvider.ContentDao.GetChannelId(tableName, contextInfo.ContentId);
                            contentChannelId = Cache.Content.GetChannelId(tableName, contextInfo.ContentId);
                            tableName        = ChannelManager.GetTableName(pageInfo.SiteInfo, ChannelManager.GetChannelInfo(pageInfo.SiteId, contentChannelId));
                            //parsedContent = DataProvider.ContentDao.GetValue(tableName, contextInfo.ContentId, attributeName);
                            parsedContent = Cache.Content.GetValue(tableName, contextInfo.ContentId, attributeName);
                        }

                        if (!string.IsNullOrEmpty(parsedContent))
                        {
                            var relatedIdentities = RelatedIdentities.GetChannelRelatedIdentities(pageInfo.SiteId, contentChannelId);
                            var styleInfo         = TableStyleManager.GetTableStyleInfo(pageInfo.SiteInfo.TableName, attributeName, relatedIdentities);

                            //styleInfo.IsVisible = false 表示此字段不需要显示 styleInfo.TableStyleId = 0 不能排除,因为有可能是直接辅助表字段没有添加显示样式
                            parsedContent = InputParserUtility.GetContentByTableStyle(parsedContent, ",", pageInfo.SiteInfo, styleInfo, string.Empty, null, string.Empty, true);
                        }
                    }
                }
                catch
                {
                    // ignored
                }
            }

            parsedContent = parsedContent.Replace(ContentUtility.PagePlaceHolder, string.Empty);

            return(parsedContent);
        }
コード例 #30
0
 public ActionResult ErrorAdmin(Administrator administrator)
 {
     return(Admin(administrator));
 }
コード例 #31
0
        //add db
        protected override void Seed(TourAgencyContext db)
        {
            // add role
            var adminRole = new IdentityRole()
            {
                Name = "admin"
            };
            var managerRole = new IdentityRole()
            {
                Name = "manager"
            };
            var customerRole = new IdentityRole()
            {
                Name = "customer"
            };

            db.Roles.Add(adminRole);
            db.Roles.Add(managerRole);
            db.Roles.Add(customerRole);
            // add admin and manager
            var adminUser = new IdentityUser
            {
                UserName      = "******",
                Email         = "*****@*****.**",
                PasswordHash  = new PasswordHasher().HashPassword("qwe123"),
                SecurityStamp = Guid.NewGuid().ToString(),
            };
            var managerUser = new IdentityUser
            {
                UserName      = "******",
                Email         = "*****@*****.**",
                PasswordHash  = new PasswordHasher().HashPassword("asd123"),
                SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser1 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser2 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser3 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser4 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser5 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser6 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser7 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser8 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };
            var customerUser9 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = new PasswordHasher().HashPassword("zxc123"), SecurityStamp = Guid.NewGuid().ToString(),
            };

            db.Users.Add(adminUser);
            db.Users.Add(managerUser);

            db.Users.Add(customerUser1);
            db.Users.Add(customerUser2);
            db.Users.Add(customerUser3);
            db.Users.Add(customerUser4);
            db.Users.Add(customerUser5);
            db.Users.Add(customerUser6);
            db.Users.Add(customerUser7);
            db.Users.Add(customerUser8);
            db.Users.Add(customerUser9);

            // add roles for staff
            var adminUserRole = new IdentityUserRole
            {
                UserId = adminUser.Id,
                RoleId = adminRole.Id,
            };
            var managerUserRole = new IdentityUserRole
            {
                UserId = managerUser.Id,
                RoleId = managerRole.Id,
            };
            var customer1UserRole = new IdentityUserRole {
                UserId = customerUser1.Id, RoleId = customerRole.Id,
            };
            var customer2UserRole = new IdentityUserRole {
                UserId = customerUser2.Id, RoleId = customerRole.Id,
            };
            var customer3UserRole = new IdentityUserRole {
                UserId = customerUser3.Id, RoleId = customerRole.Id,
            };
            var customer4UserRole = new IdentityUserRole {
                UserId = customerUser4.Id, RoleId = customerRole.Id,
            };
            var customer5UserRole = new IdentityUserRole {
                UserId = customerUser5.Id, RoleId = customerRole.Id,
            };
            var customer6UserRole = new IdentityUserRole {
                UserId = customerUser6.Id, RoleId = customerRole.Id,
            };
            var customer7UserRole = new IdentityUserRole {
                UserId = customerUser7.Id, RoleId = customerRole.Id,
            };
            var customer8UserRole = new IdentityUserRole {
                UserId = customerUser8.Id, RoleId = customerRole.Id,
            };
            var customer9UserRole = new IdentityUserRole {
                UserId = customerUser9.Id, RoleId = customerRole.Id,
            };

            db.SaveChanges();
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{adminUserRole.UserId}','{adminUserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{managerUserRole.UserId}','{managerUserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer1UserRole.UserId}','{customer1UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer2UserRole.UserId}','{customer2UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer3UserRole.UserId}','{customer3UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer4UserRole.UserId}','{customer4UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer5UserRole.UserId}','{customer5UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer6UserRole.UserId}','{customer6UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer7UserRole.UserId}','{customer7UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer8UserRole.UserId}','{customer8UserRole.RoleId}')");
            db.Database.ExecuteSqlCommand($"INSERT INTO AspNetUserRoles (UserId,RoleId) VALUES ('{customer9UserRole.UserId}','{customer9UserRole.RoleId}')");
            db.SaveChanges();
            var admin = new Administrator()
            {
                Id      = 1,
                Name    = "Pavel",
                Surname = "Pirogov",
                UserId  = adminUser.Id,
                User    = adminUser,
            };

            db.Administrators.Add(admin);
            var manager = new Manager()
            {
                Id      = 1,
                Name    = "Maxim",
                Surname = "Grinyk",
                UserId  = managerUser.Id,
                User    = managerUser,
                IsBlock = false
            };

            db.Managers.Add(manager);
            var customer1 = new Customer()
            {
                Id = 1, Name = "Tobias", Surname = "Rogers", UserId = customerUser1.Id, User = customerUser1, IsBlock = false, Discount = 14, MaxDiscount = 50, StepDiscount = 2,
            };
            var customer2 = new Customer()
            {
                Id = 1, Name = "Harris", Surname = "Young", UserId = customerUser2.Id, User = customerUser2, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer3 = new Customer()
            {
                Id = 1, Name = "Salem", Surname = "Diaz", UserId = customerUser3.Id, User = customerUser3, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer4 = new Customer()
            {
                Id = 1, Name = "Zahir", Surname = "Hayes", UserId = customerUser4.Id, User = customerUser4, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer5 = new Customer()
            {
                Id = 1, Name = "Wolfgang", Surname = "Turner", UserId = customerUser5.Id, User = customerUser5, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer6 = new Customer()
            {
                Id = 1, Name = "Roman", Surname = "Patterson", UserId = customerUser6.Id, User = customerUser6, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer7 = new Customer()
            {
                Id = 1, Name = "Neil", Surname = "Thomas", UserId = customerUser7.Id, User = customerUser7, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer8 = new Customer()
            {
                Id = 1, Name = "Graham", Surname = "Ward", UserId = customerUser8.Id, User = customerUser8, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };
            var customer9 = new Customer()
            {
                Id = 1, Name = "Jameson", Surname = "Hayes", UserId = customerUser9.Id, User = customerUser9, IsBlock = false, Discount = 0, MaxDiscount = 50, StepDiscount = 5,
            };

            db.Customers.Add(customer1);
            db.Customers.Add(customer2);
            db.Customers.Add(customer3);
            db.Customers.Add(customer4);
            db.Customers.Add(customer5);
            db.Customers.Add(customer6);
            db.Customers.Add(customer7);
            db.Customers.Add(customer8);
            db.Customers.Add(customer9);
            db.SaveChanges();

            var cityKyiv = new City()
            {
                Id = 1, NameCity = "Kyiv",
            };
            var cityVienna = new City()
            {
                Id = 2, NameCity = "Vienna",
            };
            var cityLondon = new City()
            {
                Id = 3, NameCity = "London",
            };
            var cityBudapest = new City()
            {
                Id = 4, NameCity = "Budapest",
            };
            var cityBerlin = new City()
            {
                Id = 5, NameCity = "Berlin",
            };
            var cityRome = new City()
            {
                Id = 6, NameCity = "Rome",
            };
            var cityMoscow = new City()
            {
                Id = 7, NameCity = "Moscow",
            };
            var cityStockholm = new City()
            {
                Id = 8, NameCity = "Stockholm",
            };

            db.Cities.Add(cityKyiv);
            db.Cities.Add(cityVienna);
            db.Cities.Add(cityLondon);
            db.Cities.Add(cityBudapest);
            db.Cities.Add(cityBerlin);
            db.Cities.Add(cityRome);
            db.Cities.Add(cityMoscow);
            db.Cities.Add(cityStockholm);

            var typeOfHotelHostel = new TypeOfHotel
            {
                Id            = 1,
                NumberOfStars = 4,
                Type          = "Hostel",
                IsDelete      = false,
            };
            var typeOfHotelBusiness = new TypeOfHotel
            {
                Id            = 2,
                NumberOfStars = 5,
                Type          = "Business",
                IsDelete      = false
            };
            var typeOfHotelBedandBreakfast = new TypeOfHotel
            {
                Id            = 3,
                NumberOfStars = 3,
                Type          = "Bed and Breakfast",
                IsDelete      = false
            };
            var typeOfHotelLodge = new TypeOfHotel
            {
                Id            = 4,
                NumberOfStars = 2,
                Type          = "Lodge",
                IsDelete      = false
            };

            db.TypeOfHotels.Add(typeOfHotelHostel);
            db.TypeOfHotels.Add(typeOfHotelBusiness);
            db.TypeOfHotels.Add(typeOfHotelBedandBreakfast);
            db.TypeOfHotels.Add(typeOfHotelLodge);

            var typeOfTourRelax = new TypeOfTour {
                Id = 1, Type = "Relax"
            };
            var typeOfTourExcursion = new TypeOfTour {
                Id = 2, Type = "Excursion"
            };
            var typeOfTourShopping = new TypeOfTour {
                Id = 3, Type = "Shopping"
            };
            var typeOfTourSport = new TypeOfTour {
                Id = 4, Type = "Sport"
            };

            db.TypeOfTours.Add(typeOfTourRelax);
            db.TypeOfTours.Add(typeOfTourExcursion);
            db.TypeOfTours.Add(typeOfTourShopping);
            db.TypeOfTours.Add(typeOfTourSport);

            var typeOfStatusRegistered = new TypeOfStatus()
            {
                Id = 1, Type = "Registered"
            };
            var typeOfStatusPaid = new TypeOfStatus()
            {
                Id = 2, Type = "Paid"
            };
            var typeOfStatusCanceled = new TypeOfStatus()
            {
                Id = 3, Type = "Canceled"
            };

            db.TypeOfStatuses.Add(typeOfStatusRegistered);
            db.TypeOfStatuses.Add(typeOfStatusPaid);
            db.TypeOfStatuses.Add(typeOfStatusCanceled);

            var tour1 = new Tour()
            {
                Id                = 1,
                City              = cityKyiv,
                CityId            = cityKyiv.Id,
                Price             = 2000,
                IsHot             = false,
                StartOfTour       = Convert.ToDateTime("04/05/2020"),
                EndOfTour         = Convert.ToDateTime("04/06/2020"),
                MaxNumberOfPeople = 10,
                TypeOfHotel       = typeOfHotelHostel,
                TypeOfHotelId     = typeOfHotelHostel.Id,
                TypeOfTour        = typeOfTourRelax,
                TypeOfTourId      = typeOfTourRelax.Id,
                IsDelete          = false,
                NumberOfOrders    = 3,
                ImagePath         = "Kyiv.jpg"
            };
            var tour2 = new Tour()
            {
                Id                = 2,
                City              = cityRome,
                CityId            = cityRome.Id,
                Price             = 4400,
                IsHot             = true,
                StartOfTour       = Convert.ToDateTime("18/05/2020"),
                EndOfTour         = Convert.ToDateTime("18/06/2020"),
                MaxNumberOfPeople = 3,
                TypeOfHotel       = typeOfHotelBedandBreakfast,
                TypeOfHotelId     = typeOfHotelBedandBreakfast.Id,
                TypeOfTour        = typeOfTourShopping,
                TypeOfTourId      = typeOfTourShopping.Id,
                IsDelete          = false,
                NumberOfOrders    = 2,
                ImagePath         = "Rome.jpg"
            };
            var tour3 = new Tour()
            {
                Id                = 3,
                City              = cityLondon,
                CityId            = cityLondon.Id,
                Price             = 3800,
                IsHot             = false,
                StartOfTour       = Convert.ToDateTime("12/05/2020"),
                EndOfTour         = Convert.ToDateTime("12/06/2020"),
                MaxNumberOfPeople = 5,
                TypeOfHotel       = typeOfHotelLodge,
                TypeOfHotelId     = typeOfHotelLodge.Id,
                TypeOfTour        = typeOfTourExcursion,
                TypeOfTourId      = typeOfTourExcursion.Id,
                IsDelete          = false,
                NumberOfOrders    = 3,
                ImagePath         = "London.jpg"
            };
            var tour4 = new Tour()
            {
                Id                = 4,
                City              = cityBerlin,
                CityId            = cityBerlin.Id,
                Price             = 8500,
                IsHot             = false,
                StartOfTour       = Convert.ToDateTime("04/07/2020"),
                EndOfTour         = Convert.ToDateTime("04/08/2020"),
                MaxNumberOfPeople = 10,
                TypeOfHotel       = typeOfHotelHostel,
                TypeOfHotelId     = typeOfHotelHostel.Id,
                TypeOfTour        = typeOfTourRelax,
                TypeOfTourId      = typeOfTourRelax.Id,
                IsDelete          = false,
                NumberOfOrders    = 5,
                ImagePath         = "Berlin.jpg"
            };
            var tour5 = new Tour()
            {
                Id                = 5,
                City              = cityMoscow,
                CityId            = cityMoscow.Id,
                Price             = 7200,
                IsHot             = true,
                StartOfTour       = Convert.ToDateTime("09/06/2020"),
                EndOfTour         = Convert.ToDateTime("10/06/2020"),
                MaxNumberOfPeople = 7,
                TypeOfHotel       = typeOfHotelHostel,
                TypeOfHotelId     = typeOfHotelHostel.Id,
                TypeOfTour        = typeOfTourRelax,
                TypeOfTourId      = typeOfTourRelax.Id,
                IsDelete          = false,
                NumberOfOrders    = 3,
                ImagePath         = "Moscow.jpeg"
            };
            var tour6 = new Tour()
            {
                Id                = 6,
                City              = cityStockholm,
                CityId            = cityStockholm.Id,
                Price             = 6300,
                IsHot             = false,
                StartOfTour       = Convert.ToDateTime("19/07/2020"),
                EndOfTour         = Convert.ToDateTime("27/07/2020"),
                MaxNumberOfPeople = 3,
                TypeOfHotel       = typeOfHotelLodge,
                TypeOfHotelId     = typeOfHotelLodge.Id,
                TypeOfTour        = typeOfTourShopping,
                TypeOfTourId      = typeOfTourShopping.Id,
                IsDelete          = false,
                NumberOfOrders    = 2,
                ImagePath         = "Stockholm.jpg"
            };

            db.Tours.Add(tour1);
            db.Tours.Add(tour2);
            db.Tours.Add(tour3);
            db.Tours.Add(tour4);
            db.Tours.Add(tour5);
            db.Tours.Add(tour6);
            var tourCustomer1 = new TourCustomer()
            {
                Id                 = 1,
                Customer           = customer1,
                CustomerId         = customer1.Id,
                Tour               = tour1,
                TourId             = tour1.Id,
                TypeOfStatus       = typeOfStatusRegistered,
                TypeOfStatusId     = typeOfStatusRegistered.Id,
                RealNumberOfPeople = 2,
                RealPrice          = 1800,
            };
            var tourCustomer2 = new TourCustomer()
            {
                Id                 = 2,
                Customer           = customer1,
                CustomerId         = customer1.Id,
                Tour               = tour4,
                TourId             = tour4.Id,
                TypeOfStatus       = typeOfStatusRegistered,
                TypeOfStatusId     = typeOfStatusRegistered.Id,
                RealNumberOfPeople = 3,
                RealPrice          = 8000
            };

            db.TourCustomers.Add(tourCustomer1);
            db.TourCustomers.Add(tourCustomer2);
            db.SaveChanges();
        }
コード例 #32
0
 internal void ShowRatingScreen(Administrator loggedUser, Core.Architecture.Model.Donation donation)
 {
     ShowDialog(new DonationForm(this, loggedUser, donation));
 }
コード例 #33
0
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            // Creating new customer.
            Customer newCustomer = new Customer
            {
                FIRST_NAME         = "Iliya",
                LAST_NAME          = "Tsvibel",
                USER_NAME          = "Iliya",
                PASSWORD           = "******",
                ADDRESS            = "Rishon",
                PHONE_NO           = "0546800559",
                CREDIT_CARD_NUMBER = "12345"
            };

            adminFacade.CreateNewCustomer(defaultToken, newCustomer);

            // Creating new country.
            Country country = null;

            country = new Country();
            for (int i = 0; i < ListOfCountries.CountryNames.Length; i++)
            {
                country = countryDAO.GetByName(ListOfCountries.CountryNames[i]);

                if (country == null)
                {
                    Country newCountry = new Country {
                        COUNTRY_NAME = ListOfCountries.CountryNames[i]
                    };
                    adminFacade.CreateNewCountry(defaultToken, newCountry);
                }
            }

            // Creating new administrator.
            Administrator newAdmin = new Administrator {
                FIRST_NAME = "Iliya", LAST_NAME = "Tsvibel", USER_NAME = "Admin", PASSWORD = "******"
            };

            adminFacade.CreateNewAdmin(defaultToken, newAdmin);

            //Creating new airline.
            //AirlineCompany newAirline = new AirlineCompany
            //{
            //    AIRLINE_NAME = "Aeroflot",
            //    USER_NAME = "Vladimir",
            //    COUNTRY_CODE = adminFacade.GetCountryByName("Germany").ID,
            //    PASSWORD = "******"
            //};
            //adminFacade.CreateNewAirline(defaultToken, newAirline);

            AirlineCompany airline = null;

            airline = new AirlineCompany();
            long countryStartID = 0;

            countryStartID = countryDAO.GetByName(ListOfCountries.CountryNames[0]).ID;
            for (int i = 0; i < ListOfAirlinesCompanies.AirlineNames.Length; i++)
            {
                airline = airlineDAO.GetAirlineByName(ListOfAirlinesCompanies.AirlineNames[i]);

                if (airline == null)
                {
                    AirlineCompany newAirline = new AirlineCompany {
                        AIRLINE_NAME = ListOfAirlinesCompanies.AirlineNames[i], USER_NAME = "UserName-" + ListOfAirlinesCompanies.AirlineNames[i], PASSWORD = random.Next(1000, 10000).ToString(), COUNTRY_CODE = random.Next(Convert.ToInt32(countryStartID), (Convert.ToInt32(countryStartID) + ListOfCountries.CountryNames.Length))
                    };
                    adminFacade.CreateNewAirline(defaultToken, newAirline);
                }
            }

            // Creating new flight.
            Flight flight = new Flight {
                AIRLINECOMPANY_ID = adminFacade.GetAirlineByName(adminToken, "SOLAR CARGO, C.A.").ID, DEPARTURE_TIME = DateTime.Now, LANDING_TIME = DateTime.Now + TimeSpan.FromHours(1), ORIGIN_COUNTRY_CODE = adminFacade.GetCountryByName("Germany").ID, DESTINATION_COUNTRY_CODE = adminFacade.GetCountryByName("Germany").ID, REMAINING_TICKETS = 250
            };

            //airlineFacade.CreateFlight(defaultAirlioneToken, flight);
            flightDAO.Add(flight);

            // Creating new ticket.
            Ticket tickets = new Ticket {
                FLIGHT_ID = anonFacade.GetFlightsByDestinationCountryForTest(adminFacade.GetCountryByName("Germany").ID).ID, CUSTOMER_ID = adminFacade.GetCustomerByUserName(adminToken, "Iliya").ID
            };

            //customerFacade.PurchaseTicket(defaultCustomerToken, tickets);
            ticketDAO.Add(tickets);
            MessageBox.Show($"All data successfully added");
        }
コード例 #34
0
ファイル: DashboardLogic.cs プロジェクト: zeevir/extensions
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                PermissionAuthLogic.RegisterPermissions(DashboardPermission.ViewDashboard);

                UserAssetsImporter.RegisterName <DashboardEntity>("Dashboard");

                UserAssetsImporter.PartNames.AddRange(new Dictionary <string, Type>
                {
                    { "UserChartPart", typeof(UserChartPartEntity) },
                    { "UserQueryPart", typeof(UserQueryPartEntity) },
                    { "LinkListPart", typeof(LinkListPartEntity) },
                    { "ValueUserQueryListPart", typeof(ValueUserQueryListPartEntity) },
                });

                sb.Include <DashboardEntity>()
                .WithQuery(() => cp => new
                {
                    Entity = cp,
                    cp.Id,
                    cp.DisplayName,
                    cp.EntityType,
                    cp.Owner,
                    cp.DashboardPriority,
                });

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserQueryPartEntity)))
                {
                    sb.Schema.EntityEvents <UserQueryEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserQueryPartEntity)mle.Element.Content).UserQuery)).UnsafeDeleteMList();
                        Database.Query <UserQueryPartEntity>().Where(uqp => query.Contains(uqp.UserQuery)).UnsafeDelete();
                        return(null);
                    };

                    sb.Schema.Table <UserQueryEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uq = (UserQueryEntity)arg;

                        var parts = Administrator.UnsafeDeletePreCommandMList((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                              .Where(mle => ((UserQueryPartEntity)mle.Element.Content).UserQuery == uq));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <UserQueryPartEntity>()
                                                                          .Where(mle => mle.UserQuery == uq));

                        return(SqlPreCommand.Combine(Spacing.Simple, parts, parts2));
                    };
                }

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserChartPartEntity)))
                {
                    sb.Schema.EntityEvents <UserChartEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserChartPartEntity)mle.Element.Content).UserChart)).UnsafeDeleteMList();
                        Database.Query <UserChartPartEntity>().Where(uqp => query.Contains(uqp.UserChart)).UnsafeDelete();
                        return(null);
                    };

                    sb.Schema.Table <UserChartEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uc = (UserChartEntity)arg;

                        var parts = Administrator.UnsafeDeletePreCommandMList((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                              .Where(mle => ((UserChartPartEntity)mle.Element.Content).UserChart == uc));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <UserChartPartEntity>()
                                                                          .Where(mle => mle.UserChart == uc));

                        return(SqlPreCommand.Combine(Spacing.Simple, parts, parts2));
                    };
                }

                DashboardGraph.Register();


                Dashboards = sb.GlobalLazy(() => Database.Query <DashboardEntity>().ToDictionary(a => a.ToLite()),
                                           new InvalidateWith(typeof(DashboardEntity)));

                DashboardsByType = sb.GlobalLazy(() => Dashboards.Value.Values.Where(a => a.EntityType != null)
                                                 .SelectCatch(d => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(d.EntityType !.Id), d.ToLite()))
                                                 .GroupToDictionary(),
                                                 new InvalidateWith(typeof(DashboardEntity)));
            }
        }
コード例 #35
0
        public IActionResult Snimi(KorisniciDodajVM korisnik)
        {
            if (!ModelState.IsValid)
            {
                KorisniciDodajVM korisnici = new KorisniciDodajVM();
                korisnici.uloge = new List <Uloge>();

                List <Uloge> uloge = _context.Uloge.ToList();

                foreach (Uloge u in uloge)
                {
                    korisnici.uloge.Add(u);
                }
                return(View("Dodaj", korisnici));
            }



            Uloge uloga = _context.Uloge.FirstOrDefault(x => x.Id == korisnik.UlogaId);

            if (uloga.NazivUloge == "Administrator")
            {
                Administrator administrator = new Administrator
                {
                    Ime             = korisnik.Ime,
                    Prezime         = korisnik.Prezime,
                    Telefon         = korisnik.Telefon,
                    JMBG            = korisnik.JMBG,
                    Adresa          = korisnik.Adresa,
                    KorisnickiNalog = new KorisnickiNalog
                    {
                        KorisnickoIme = korisnik.KorisnickoIme,
                        Lozinka       = korisnik.Lozinka,
                        UlogaID       = korisnik.UlogaId
                    }
                };

                _context.Administrator.Add(administrator);
                _context.SaveChanges();
                return(RedirectToAction("Prikazi"));
            }

            if (uloga.NazivUloge == "Referent za klijente")
            {
                ReferentKlijenti Rklijenti = new ReferentKlijenti
                {
                    Ime             = korisnik.Ime,
                    Prezime         = korisnik.Prezime,
                    Telefon         = korisnik.Telefon,
                    JMBG            = korisnik.JMBG,
                    Adresa          = korisnik.Adresa,
                    KorisnickiNalog = new KorisnickiNalog
                    {
                        KorisnickoIme = korisnik.KorisnickoIme,
                        Lozinka       = korisnik.Lozinka,
                        UlogaID       = korisnik.UlogaId
                    }
                };
                _context.ReferentKlijenti.Add(Rklijenti);
                _context.SaveChanges();
                return(RedirectToAction("Prikazi"));
            }



            if (uloga.NazivUloge == "Serviser")
            {
                Serviser serviser = new Serviser
                {
                    Ime             = korisnik.Ime,
                    Prezime         = korisnik.Prezime,
                    Telefon         = korisnik.Telefon,
                    JMBG            = korisnik.JMBG,
                    Adresa          = korisnik.Adresa,
                    KorisnickiNalog = new KorisnickiNalog
                    {
                        KorisnickoIme = korisnik.KorisnickoIme,
                        Lozinka       = korisnik.Lozinka,
                        UlogaID       = korisnik.UlogaId
                    }
                };
                _context.Serviser.Add(serviser);
                _context.SaveChanges();
                return(RedirectToAction("Prikazi"));
            }


            return(RedirectToAction("Prikazi"));
        }
コード例 #36
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Session["AdministratorRegistery"] != null)
            {
                ProfileProperty propfileinfo = new ProfileProperty()
                {
                    avatarImageSrc = ((Administrator)Session["AdministratorRegistery"]).ad_avatarprofile,
                    name           = ((Administrator)Session["AdministratorRegistery"]).ad_NickName,
                    fullname       = ((Administrator)Session["AdministratorRegistery"]).ad_firstname + " " + ((Administrator)Session["AdministratorRegistery"]).ad_lastname,
                    ipAdmin        = Request.UserHostAddress,
                    Firstname      = ((Administrator)Session["AdministratorRegistery"]).ad_firstname,
                    Lastname       = ((Administrator)Session["AdministratorRegistery"]).ad_lastname,
                    email          = ((Administrator)Session["AdministratorRegistery"]).ad_email,
                    phone          = ((Administrator)Session["AdministratorRegistery"]).ad_phone,
                    mobile         = ((Administrator)Session["AdministratorRegistery"]).ad_mobile,
                    Username       = ((Administrator)Session["AdministratorRegistery"]).Username
                };
                ViewBag.ProfileInfo = propfileinfo;
                //End of Admin Profile
                //start PAGE - TITLE
                string actionName     = filterContext.RouteData.Values["action"].ToString();
                string controllerName = filterContext.RouteData.Values["controller"].ToString();
                ViewBag.pageTitle = TitleFounder.GetAdminPanelTitle(controllerName, actionName);
                //END of PAGE - TITLE


                base.OnActionExecuting(filterContext);
            }
            else if (HttpContext.Request.Cookies.Get(ProjectProperies.AuthCoockieCode()) != null)
            {
                var           coockie          = HttpContext.Request.Cookies.Get(ProjectProperies.AuthCoockieCode());
                Administrator administratorobj = CoockieController.SayMyName(coockie.Value);

                if ((DateTime.Now - administratorobj.SayMyTime).TotalHours > 6)
                {
                    string actionName1     = filterContext.RouteData.Values["action"].ToString();
                    string controllerName1 = filterContext.RouteData.Values["controller"].ToString();
                    string urlRedirection  = controllerName1 + "-A_" + actionName1;
                    if (!urlRedirection.Contains("AdminLoginAuth-A_index"))
                    {
                        TempData["urlRedirection"] = urlRedirection;
                        filterContext.Result       = RedirectToAction("index", "AdminLoginAuth", new { @urlRedirection = urlRedirection });
                    }
                    else
                    {
                        filterContext.Result = RedirectToAction("index", "AdminLoginAuth");
                    }
                }

                ProfileProperty propfileinfo = new ProfileProperty()
                {
                    avatarImageSrc = administratorobj.ad_avatarprofile,
                    name           = administratorobj.ad_NickName,
                    fullname       = administratorobj.ad_firstname + " " + administratorobj.ad_lastname,
                    ipAdmin        = Request.UserHostAddress,
                    Firstname      = administratorobj.ad_firstname,
                    Lastname       = administratorobj.ad_lastname,
                    email          = administratorobj.ad_email,
                    phone          = administratorobj.ad_phone,
                    mobile         = administratorobj.ad_mobile,
                    Username       = administratorobj.Username
                };
                administratorobj.SayMyTime = DateTime.Now;

                var userCookieIDV = new HttpCookie(ProjectProperies.AuthCoockieCode());
                userCookieIDV.Value   = CoockieController.SetCoockie(administratorobj);;
                userCookieIDV.Expires = DateTime.Now.AddYears(5);
                Response.SetCookie(userCookieIDV);

                ViewBag.ProfileInfo = propfileinfo;
                //End of Admin Profile
                //start PAGE - TITLE
                string actionName     = filterContext.RouteData.Values["action"].ToString();
                string controllerName = filterContext.RouteData.Values["controller"].ToString();
                ViewBag.pageTitle = TitleFounder.GetAdminPanelTitle(controllerName, actionName);
                //END of PAGE - TITLE
                base.OnActionExecuting(filterContext);
            }
            else
            {
                string actionName     = filterContext.RouteData.Values["action"].ToString();
                string controllerName = filterContext.RouteData.Values["controller"].ToString();
                string urlRedirection = controllerName + "-A_" + actionName;
                if (!urlRedirection.Contains("AdminLoginAuth-A_index"))
                {
                    TempData["urlRedirection"] = urlRedirection;
                    filterContext.Result       = RedirectToAction("index", "AdminLoginAuth", new { @urlRedirection = urlRedirection });
                }
                else
                {
                    filterContext.Result = RedirectToAction("index", "AdminLoginAuth");
                }
            }
        }
コード例 #37
0
 public static string GetPassword(this Administrator administrator)
 {
     return(DefaultPassword);
 }
コード例 #38
0
        /// <summary>
        /// Purpose: Grabs all administrators
        /// Accepts: Boolean
        /// Returns: List<Administrator>
        /// </summary>
        public List<Administrator> GetAllAdministrators(bool onlyActive)
        {
            List<Administrator> administrators = new List<Administrator>();
            try
            {
                AdministratorData data = new AdministratorData();
                List<QSRDataObjects.Administrator> dataAdministrators = data.GetAllAdministrators(onlyActive);

                foreach (QSRDataObjects.Administrator a in dataAdministrators)
                {
                    Administrator admin = new Administrator();
                    admin.AdministratorID = a.AdministratorID;
                    admin.Username = a.Username;
                    admin.Password = a.Password;
                    admin.FirstName = a.FirstName;
                    admin.LastName = a.LastName;
                    admin.IsActive = a.IsActive;
                    administrators.Add(admin);
                }
            }
            catch (Exception ex)
            {
                ErrorRoutine(ex, "Administrator", "GetAllAdministrators");
            }
            return administrators;
        }
コード例 #39
0
ファイル: AddTicket.cs プロジェクト: HendrikoDuToit/Dotslash
 public frmAddTicket(Administrator admin)
 {
     InitializeComponent();
     this.admin = admin;
 }
コード例 #40
0
        public IActionResult Izmjeni(int id)
        {
            KorisnickiNalog  nalog  = _context.KorisnickiNalog.FirstOrDefault(x => x.Id == id);
            KorisniciDodajVM korisn = new KorisniciDodajVM();
            Uloge            u      = _context.Uloge.FirstOrDefault(x => x.Id == nalog.UlogaID);

            if (u.NazivUloge == "Administrator")
            {
                Administrator a = _context.Administrator.SingleOrDefault(x => x.KorisnickiNalogId == nalog.Id);


                korisn.Ime           = a.Ime;
                korisn.Prezime       = a.Prezime;
                korisn.Telefon       = a.Telefon;
                korisn.JMBG          = a.JMBG;
                korisn.Adresa        = a.Adresa;
                korisn.KorisnickoIme = nalog.KorisnickoIme;
                korisn.Lozinka       = nalog.Lozinka;
                korisn.UlogaId       = Convert.ToInt32(nalog.UlogaID);


                korisn.uloge = new List <Uloge>();
                List <Uloge> ulog = _context.Uloge.ToList();

                foreach (Uloge ulo in ulog)
                {
                    korisn.uloge.Add(ulo);
                }
            }
            if (u.NazivUloge == "Referent za klijente")
            {
                ReferentKlijenti a = _context.ReferentKlijenti.SingleOrDefault(x => x.KorisnickiNalogId == nalog.Id);


                korisn.Ime           = a.Ime;
                korisn.Prezime       = a.Prezime;
                korisn.Telefon       = a.Telefon;
                korisn.JMBG          = a.JMBG;
                korisn.Adresa        = a.Adresa;
                korisn.KorisnickoIme = nalog.KorisnickoIme;
                korisn.Lozinka       = nalog.Lozinka;
                korisn.UlogaId       = Convert.ToInt32(nalog.UlogaID);


                korisn.uloge = new List <Uloge>();
                List <Uloge> ulog = _context.Uloge.ToList();

                foreach (Uloge ulo in ulog)
                {
                    korisn.uloge.Add(ulo);
                }
            }

            if (u.NazivUloge == "Serviser")
            {
                Serviser a = _context.Serviser.SingleOrDefault(x => x.KorisnickiNalogId == nalog.Id);


                korisn.Ime           = a.Ime;
                korisn.Prezime       = a.Prezime;
                korisn.Telefon       = a.Telefon;
                korisn.JMBG          = a.JMBG;
                korisn.Adresa        = a.Adresa;
                korisn.KorisnickoIme = nalog.KorisnickoIme;
                korisn.Lozinka       = nalog.Lozinka;
                korisn.UlogaId       = Convert.ToInt32(nalog.UlogaID);


                korisn.uloge = new List <Uloge>();
                List <Uloge> ulog = _context.Uloge.ToList();

                foreach (Uloge ulo in ulog)
                {
                    korisn.uloge.Add(ulo);
                }
            }

            return(View("Izmjeni", korisn));
        }
コード例 #41
0
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the form values
            Int32 id = Convert.ToInt32(collection["txtId"]);
            string product_code = collection["txtProductCode"];
            string name = collection["txtName"];
            decimal fee = 0;
            decimal.TryParse(collection["txtFee"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out fee);
            Int32 unit_id = Convert.ToInt32(collection["selectUnit"]);
            bool price_based_on_mount_time = Convert.ToBoolean(collection["cbPriceBasedOnMountTime"]);
            Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]);
            string account_code = collection["txtAccountCode"];
            bool inactive = Convert.ToBoolean(collection["cbInactive"]);

            // Get the default admin language id
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Get the additional service
            AdditionalService additionalService = AdditionalService.GetOneById(id, adminLanguageId);

            // Check if the additional service exists
            if (additionalService == null)
            {
                // Create a empty additional service
                additionalService = new AdditionalService();
            }

            // Update values
            additionalService.product_code = product_code;
            additionalService.name = name;
            additionalService.fee = fee;
            additionalService.unit_id = unit_id;
            additionalService.price_based_on_mount_time = price_based_on_mount_time;
            additionalService.value_added_tax_id = value_added_tax_id;
            additionalService.account_code = account_code;
            additionalService.inactive = inactive;

            // Create a error message
            string errorMessage = string.Empty;

            // Check for errors in the additional service
            if (additionalService.product_code.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("product_code"), "50") + "<br/>";
            }
            if (additionalService.name.Length > 100)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>";
            }
            if (additionalService.fee < 0 || additionalService.fee > 9999999999.99M)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_range"), tt.Get("fee"), "9 999 999 999.99") + "<br/>";
            }
            if (additionalService.account_code.Length > 10)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>";
            }
            if (additionalService.unit_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("unit").ToLower()) + "<br/>";
            }
            if (additionalService.value_added_tax_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == "")
            {
                // Check if we should add or update the additional service
                if (additionalService.id == 0)
                {
                    // Add the additional service
                    Int64 insertId = AdditionalService.AddMasterPost(additionalService);
                    additionalService.id = Convert.ToInt32(insertId);
                    AdditionalService.AddLanguagePost(additionalService, adminLanguageId);
                }
                else
                {
                    // Update the additional service
                    AdditionalService.UpdateMasterPost(additionalService);
                    AdditionalService.UpdateLanguagePost(additionalService, adminLanguageId);
                }

                // Redirect the user to the list
                return Redirect("/admin_additional_services" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.Units = Unit.GetAll(adminLanguageId, "name", "ASC");
                ViewBag.AdditionalService = additionalService;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
コード例 #42
0
 public static void SignIn(Administrator admin)
 {
     currentAdmin = admin;
 }
コード例 #43
0
        // Testing Database
        private async void PopulateForTest()
        {
            // Test for administrator
            Debug.WriteLine("Begin adm");
            Administrator administrator = new Administrator();

            Debug.WriteLine("Adm constructor called");
            administrator.Name         = "Adm";
            administrator.Password     = "******";
            administrator.Registration = "456";
            administrator.Email        = "*****@*****.**";
            administrator.CreatedOn    = DateTime.Now;
            Debug.WriteLine("Adminstrator attr created");

            await AdministratorDatabase.getAdmDB.Save(administrator);

            Debug.WriteLine("End adm");

            Debug.WriteLine("Begin coord");
            // Test for coordinator
            Coordinator coordinator = new Coordinator();

            coordinator.Name         = "Maria";
            coordinator.Password     = "******";
            coordinator.Registration = "456";
            coordinator.Email        = "*****@*****.**";
            coordinator.CreatedOn    = DateTime.Now;

            await CoordinatorDatabase.getCoordinatorDB.Save(coordinator);

            Debug.WriteLine("End coord");

            Debug.WriteLine("Begin Forum");
            // Test for Forum
            Forum forum = new Forum();

            forum.Title     = "Forum 1";
            forum.Place     = "Reitoria";
            forum.Schedules = "Varias pautas.";
            forum.Hour      = DateTime.Now.TimeOfDay;
            forum.Date      = DateTime.Now;

            await ForumDatabase.getForumDB.Save(forum);

            Debug.WriteLine("End Forum");

            Debug.WriteLine("Begin Form");
            // Test for Form
            Form form = new Form();

            form.ForumId   = forum.Id;
            form.CreatedOn = DateTime.Now;

            await FormDatabase.getFormDB.Save(form);

            Debug.WriteLine("End Form");

            Debug.WriteLine("Begin FormAsk1");
            // Test for FormAsk
            FormAsk formAsk1 = new FormAsk();

            formAsk1.AskType = 1;
            formAsk1.Options = "opçao1; opçao2; opçao3;";
            formAsk1.FormId  = form.Id;

            await FormAskDatabase.getFormDB.Save(formAsk1);

            Debug.WriteLine("End FormAsk1");

            Debug.WriteLine("Begin FormAsk2");
            FormAsk formAsk2 = new FormAsk();

            formAsk2         = new FormAsk();
            formAsk2.AskType = 2;
            formAsk2.Options = "opçao1; opçao2; opçao3;";
            formAsk2.FormId  = form.Id;

            await FormAskDatabase.getFormDB.Save(formAsk2);

            Debug.WriteLine("End FormAsk2");

            Debug.WriteLine("Begin FormAsk3");
            FormAsk formAsk3 = new FormAsk();

            formAsk3         = new FormAsk();
            formAsk3.AskType = 3;
            formAsk3.Options = "Opçao dissertativa";
            formAsk3.FormId  = form.Id;

            await FormAskDatabase.getFormDB.Save(formAsk3);

            Debug.WriteLine("End FormAsk3");

            Debug.WriteLine("Begin ForumConfirmation");
            // Test for forum confirmation
            ForumConfirmation forumConfirmation = new ForumConfirmation();

            forumConfirmation.ForumId = forum.Id;
            forumConfirmation.UserId  = coordinator.Id;

            await ForumConfirmationDatabase.getForumConfirmationDB.Save(forumConfirmation);

            Debug.WriteLine("End ForumConfirmation");

            Debug.WriteLine("Begin FormAn1");
            // Test for form answers
            FormAnswer formAnswer1 = new FormAnswer();

            formAnswer1.FormAskId            = formAsk1.Id;
            formAnswer1.OptionAnswerPosition = 1;
            formAnswer1.UserId = coordinator.Id;

            await FormAnswerDatabase.getFormDB.Save(formAnswer1);

            Debug.WriteLine("End FormAn1");

            Debug.WriteLine("Begin FormAn2");
            FormAnswer formAnswer2 = new FormAnswer();

            formAnswer2.FormAskId = formAsk2.Id;
            formAnswer2.MultipleAnswerPositions = "1; 2;";
            formAnswer2.UserId = coordinator.Id;

            await FormAnswerDatabase.getFormDB.Save(formAnswer2);

            Debug.WriteLine("End FormAn2");

            Debug.WriteLine("Begin FormAn3");
            FormAnswer formAnswer3 = new FormAnswer();

            formAnswer3.FormAskId  = formAsk3.Id;
            formAnswer3.TextAnswer = "Resposta da pergunta.";
            formAnswer3.UserId     = coordinator.Id;

            await FormAnswerDatabase.getFormDB.Save(formAnswer3);

            Debug.WriteLine("End FormAn3");
        }
コード例 #44
0
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get form values
            Int32 id = Convert.ToInt32(collection["txtId"]);
            Int32 parentCategoryId = Convert.ToInt32(collection["selectCategory"]);
            string title = collection["txtTitle"];
            string description = collection["txtDescription"];
            string metaDescription = collection["txtMetaDescription"];
            string metaKeywords = collection["txtMetaKeywords"];
            string pageName = collection["txtPageName"];
            string metaRobots = collection["selectMetaRobots"];
            bool useLocalImages = Convert.ToBoolean(collection["cbLocalImages"]);
            DateTime date_added = DateTime.MinValue;
            DateTime.TryParse(collection["txtDateAdded"], out date_added);
            bool inactive = Convert.ToBoolean(collection["cbInactive"]);

            // Get the default admin language id
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get the category
            Category category = Category.GetOneById(id, adminLanguageId);

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Check if the category exists
            if (category == null)
            {
                // Create a new category
                category = new Category();
            }

            // Set values for the category
            category.parent_category_id = parentCategoryId;
            category.title = title;
            category.main_content = description;
            category.meta_description = metaDescription;
            category.meta_keywords = metaKeywords;
            category.page_name = pageName;
            category.meta_robots = metaRobots;
            category.use_local_images = useLocalImages;
            category.date_added = AnnytabDataValidation.TruncateDateTime(date_added);
            category.inactive = inactive;

            // Create a error message
            string errorMessage = string.Empty;

            // Get a category on page name
            Category categoryOnPageName = Category.GetOneByPageName(category.page_name, adminLanguageId);

            // Check the page name
            if (categoryOnPageName != null && category.id != categoryOnPageName.id)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_language_unique"), tt.Get("page_name")) + "<br/>";
            }
            if (category.page_name == string.Empty)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_required"), tt.Get("page_name")) + "<br/>";
            }
            if (AnnytabDataValidation.CheckPageNameCharacters(category.page_name) == false)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_bad_chars"), tt.Get("page_name")) + "<br/>";
            }
            if (category.page_name.Length > 100)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("page_name"), "100") + "<br/>";
            }
            if (category.title.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("title"), "200") + "<br/>";
            }
            if (category.meta_description.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("meta_description"), "200") + "<br/>";
            }
            if (category.meta_keywords.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("keywords"), "200") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the category
                if (category.id != 0)
                {
                    // Update the category
                    Category.UpdateMasterPost(category);
                    Category.UpdateLanguagePost(category, adminLanguageId);
                }
                else
                {
                    // Add the category
                    Int64 insertId = Category.AddMasterPost(category);
                    category.id = Convert.ToInt32(insertId);
                    Category.AddLanguagePost(category, adminLanguageId);
                }

                // Redirect the user to the list
                return Redirect("/admin_categories" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.Category = category;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
コード例 #45
0
        public ActionResult translate(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get the default admin language
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Get all the form values
            Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]);
            Int32 categoryId = Convert.ToInt32(collection["hiddenCategoryId"]);
            string title = collection["txtTranslatedTitle"];
            string description = collection["txtTranslatedDescription"];
            string metadescription = collection["txtTranslatedMetadescription"];
            string metakeywords = collection["txtTranslatedMetakeywords"];
            string pagename = collection["txtTranslatedPagename"];
            bool use_local_images = Convert.ToBoolean(collection["cbLocalImages"]);
            bool inactive = Convert.ToBoolean(collection["cbInactive"]);

            // Create the translated category
            Category translatedCategory = new Category();
            translatedCategory.id = categoryId;
            translatedCategory.title = title;
            translatedCategory.main_content = description;
            translatedCategory.meta_description = metadescription;
            translatedCategory.meta_keywords = metakeywords;
            translatedCategory.page_name = pagename;
            translatedCategory.use_local_images = use_local_images;
            translatedCategory.inactive = inactive;

            // Create a error message
            string errorMessage = string.Empty;

            // Get a category on page name
            Category categoryOnPageName = Category.GetOneByPageName(translatedCategory.page_name, translationLanguageId);

            // Check for errors
            if (categoryOnPageName != null && translatedCategory.id != categoryOnPageName.id)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_language_unique"), tt.Get("page_name")) + "<br/>";
            }
            if (translatedCategory.page_name == string.Empty)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_required"), tt.Get("page_name")) + "<br/>";
            }
            if (AnnytabDataValidation.CheckPageNameCharacters(translatedCategory.page_name) == false)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_bad_chars"), tt.Get("page_name")) + "<br/>";
            }
            if (translatedCategory.page_name.Length > 100)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("page_name"), "100") + "<br/>";
            }
            if (translatedCategory.title.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("title"), "200") + "<br/>";
            }
            if (translatedCategory.meta_description.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("meta_description"), "200") + "<br/>";
            }
            if (translatedCategory.meta_keywords.Length > 200)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("keywords"), "200") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Get the saved category
                Category category = Category.GetOneById(categoryId, translationLanguageId);

                if (category == null)
                {
                    // Add a new translated category
                    Category.AddLanguagePost(translatedCategory, translationLanguageId);
                }
                else
                {
                    // Update values for the saved category
                    category.title = translatedCategory.title;
                    category.main_content = translatedCategory.main_content;
                    category.meta_description = translatedCategory.meta_description;
                    category.meta_keywords = translatedCategory.meta_keywords;
                    category.page_name = translatedCategory.page_name;
                    category.use_local_images = translatedCategory.use_local_images;
                    category.inactive = translatedCategory.inactive;

                    // Update the category translation
                    Category.UpdateLanguagePost(category, translationLanguageId);
                }

                // Redirect the user to the list
                return Redirect("/admin_categories" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.LanguageId = translationLanguageId;
                ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC");
                ViewBag.StandardCategory = Category.GetOneById(categoryId, adminLanguageId);
                ViewBag.TranslatedCategory = translatedCategory;
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the translate view
                return View("translate");
            }

        } // End of the translate method
コード例 #46
0
        public IActionResult EditAdmin([FromBody] Administrator body)
        {
            var response = _repo.UpdateAdmin(body);

            return(Ok(response));
        }
コード例 #47
0
 public void CleanUp()
 {
     administrator = new Administrator();
 }
コード例 #48
0
ファイル: Administrator.cs プロジェクト: raphaelivo/a-webshop
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a administrator post
    /// </summary>
    /// <param name="post">A reference to a administrator post</param>
    public static void Update(Administrator post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.administrators SET admin_user_name = @admin_user_name, admin_role = @admin_role WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The Using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@admin_user_name", post.admin_user_name);
                cmd.Parameters.AddWithValue("@admin_role", post.admin_role);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
コード例 #49
0
ファイル: asd.cs プロジェクト: lsyzhly/xiangmu
 public static Person login(string id, string password)
 {
     Person p;
     cmd.CommandText=@"select name,password,type from person where id="+@"'"+id+@"';";
     DbDataReader data=cmd.ExecuteReader();
     if (data.Read())
     {
         string r_name=data.GetString(0);
         string r_password=data.GetString(1);
         int type=data.GetInt32(2);
         if (password==r_password)
         {
             switch (type)
             {
             case 0:
                 p=new Administrator(id,r_name,password);
                 break;
             case 1:
                 p=new Teacher(id,r_name,password);
                 break;
             case 2:
                 p=new Student(id,r_name,password);
                 break;
             default:
                 System.Console.WriteLine("wrong!!");
                 return null;
             }
             return p;
         }
         else
             return null;
     }
     return null;
 }
コード例 #50
0
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the form values
            Int32 id = Convert.ToInt32(collection["txtId"]);
            string userName = collection["txtUserName"];
            string password = collection["txtPassword"];
            string role = collection["selectAdminRole"];

            // Get the default admin language id
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Get the administrator
            Administrator administrator = Administrator.GetOneById(id);
            bool postExists = true;

            // Check if the administrator exists
            if (administrator == null)
            {
                // Create an empty administrator
                administrator = new Administrator();
                postExists = false;
            }

            // Update values
            administrator.admin_user_name = userName;
            administrator.admin_role = role;

            // Create a error message
            string errorMessage = string.Empty;

            // Get a administrator on user name
            Administrator adminOnUserName = Administrator.GetOneByUserName(userName);

            // Check for errors in the administrator
            if (adminOnUserName != null && administrator.id != adminOnUserName.id)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_unique"), tt.Get("user_name")) + "<br/>";
            }
            if (administrator.admin_user_name.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("user_name"), "50") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the administrator
                if (postExists == false)
                {
                    // Add the administrator
                    Int32 insertId = (Int32)Administrator.Add(administrator);
                    Administrator.UpdatePassword(insertId, PasswordHash.CreateHash(password));
                }
                else
                {
                    // Update the administrator
                    Administrator.Update(administrator);

                    // Only update the password if it has changed
                    if (password != "")
                    {
                        Administrator.UpdatePassword(administrator.id, PasswordHash.CreateHash(password));
                    }
                }

                // Redirect the user to the list
                return Redirect("/admin_administrators" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.Administrator = administrator;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
コード例 #51
0
        public ActionResult delete(Int32 id = 0, string returnUrl = "")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query paramaters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get the language id
            int languageId = 0;
            if (Request.Params["lang"] != null)
            {
                Int32.TryParse(Request.Params["lang"], out languageId);
            }

            // Create an error code variable
            Int32 errorCode = 0;

            // Check if we should delete the full post or just the translation
            if (languageId == 0 || languageId == currentDomain.back_end_language)
            {
                // Delete the category and all the posts connected to this category (CASCADE)
                errorCode = Category.DeleteOnId(id);

                // Check if there is an error
                if (errorCode != 0)
                {
                    ViewBag.AdminErrorCode = errorCode;
                    ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                    return View("index");
                }

                // Delete all files
                DeleteAllFiles(id);

            }
            else
            {
                // Delete the translated post
                errorCode = Category.DeleteLanguagePostOnId(id, languageId);

                // Check if there is an error
                if (errorCode != 0)
                {
                    ViewBag.AdminErrorCode = errorCode;
                    ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                    return View("index");
                }

                // Delete all the language specific files
                DeleteLanguageFiles(id, languageId);
            }

            // Redirect the user to the list
            return Redirect("/admin_categories" + returnUrl);

        } // End of the delete method
コード例 #52
0
        public ActionResult translate(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get the admin default language
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Get all the form values
            Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]);
            Int32 id = Convert.ToInt32(collection["hiddenAdditionalServiceId"]);
            string name = collection["txtTranslatedName"];
            Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]);
            string account_code = collection["txtAccountCode"];
            bool inactive = Convert.ToBoolean(collection["cbInactive"]);

            // Create the translated additional service
            AdditionalService translatedAdditionalService = new AdditionalService();
            translatedAdditionalService.id = id;
            translatedAdditionalService.name = name;
            translatedAdditionalService.value_added_tax_id = value_added_tax_id;
            translatedAdditionalService.account_code = account_code;
            translatedAdditionalService.inactive = inactive;

            // Create a error message
            string errorMessage = string.Empty;

            // Check for errors
            if (translatedAdditionalService.name.Length > 100)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>";
            }
            if (translatedAdditionalService.value_added_tax_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>";
            }
            if (translatedAdditionalService.account_code.Length > 10)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Get the saved additional service
                AdditionalService additionalService = AdditionalService.GetOneById(id, translationLanguageId);

                if (additionalService == null)
                {
                    // Add a new translated additional service
                    AdditionalService.AddLanguagePost(translatedAdditionalService, translationLanguageId);
                }
                else
                {
                    // Update the translated additional service
                    additionalService.name = translatedAdditionalService.name;
                    additionalService.value_added_tax_id = translatedAdditionalService.value_added_tax_id;
                    additionalService.account_code = translatedAdditionalService.account_code;
                    additionalService.inactive = translatedAdditionalService.inactive;
                    AdditionalService.UpdateLanguagePost(additionalService, translationLanguageId);
                }

                // Redirect the user to the list
                return Redirect("/admin_additional_services" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.LanguageId = translationLanguageId;
                ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC");
                ViewBag.StandardAdditionalService = AdditionalService.GetOneById(id, adminLanguageId);
                ViewBag.TranslatedAdditionalService = translatedAdditionalService;
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the translate view
                return View("translate");
            }

        } // End of the translate method
コード例 #53
0
ファイル: AccountGroupRemove.cs プロジェクト: GGulati/IRCBot
 public AccountGroupRemove(Administrator plugin)
     : base(plugin, "AccountGroup.Remove")
 {
 }
コード例 #54
0
 protected void AssertCredits <T>(Administrator administrator, Employer employer, Member member, ICreditOwner owner, bool hasExercisedCredit, Allocation allocation, Allocation[] allAllocations)
     where T : Credit
 {
     AssertCredits <T>(administrator, employer, new UsedOnMember(member), owner, hasExercisedCredit, allocation, allAllocations);
 }
コード例 #55
0
ファイル: Administrator.cs プロジェクト: raphaelivo/a-webshop
    } // End of the GetOneById method

    /// <summary>
    /// Get one administrator based on user name
    /// </summary>
    /// <param name="userName">The user name for the post</param>
    /// <returns>A reference to a administrator post</returns>
    public static Administrator GetOneByUserName(string userName)
    {
        // Create the post to return
        Administrator post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.administrators WHERE admin_user_name = @admin_user_name;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The Using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@admin_user_name", userName);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new Administrator(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
コード例 #56
0
ファイル: ImportManager.cs プロジェクト: ywscr/extensions
        public virtual Lite <DisconnectedImportEntity> BeginImportDatabase(DisconnectedMachineEntity machine, Stream?file = null)
        {
            Lite <DisconnectedImportEntity> import = new DisconnectedImportEntity
            {
                Machine = machine.ToLite(),
                Copies  = uploadTables.Select(t => new DisconnectedImportTableEmbedded
                {
                    Type = t.Type.ToTypeEntity().ToLite(),
                    DisableForeignKeys = t.Strategy.DisableForeignKeys.Value,
                }).ToMList()
            }.Save().ToLite();

            if (file != null)
            {
                using (FileStream fs = File.OpenWrite(BackupNetworkFileName(machine, import)))
                {
                    file.CopyTo(fs);
                    file.Close();
                }
            }

            var threadContext = Statics.ExportThreadContext();

            var cancelationSource = new CancellationTokenSource();

            var user = UserEntity.Current;

            var token = cancelationSource.Token;

            var task = Task.Factory.StartNew(() =>
            {
                lock (SyncLock)
                    using (UserHolder.UserSession(user))
                    {
                        OnStartImporting(machine);

                        DisconnectedMachineEntity.Current = machine.ToLite();

                        try
                        {
                            if (file != null)
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.RestoreDatabase, s => l).Execute()))
                                {
                                    DropDatabaseIfExists(machine);
                                    RestoreDatabase(machine, import);
                                }
                            }

                            string connectionString = GetImportConnectionString(machine);

                            var newDatabase = new SqlConnector(connectionString, Schema.Current, ((SqlConnector)Connector.Current).Version);

                            using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.SynchronizeSchema, s => l).Execute()))
                                using (Connector.Override(newDatabase))
                                    using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                        AvoidDatabaseName = true
                                    }))
                                        using (ExecutionMode.DisableCache())
                                        {
                                            var script = Administrator.TotalSynchronizeScript(interactive: false, schemaOnly: true);

                                            if (script != null)
                                            {
                                                string fileName = BackupNetworkFileName(machine, import) + ".sql";
                                                script.Save(fileName);
                                                throw new InvalidOperationException("The schema has changed since the last export. A schema sync script has been saved on: {0}".FormatWith(fileName));
                                            }
                                        }

                            try
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DisableForeignKeys, s => l).Execute()))
                                    foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys.Value))
                                    {
                                        DisableForeignKeys(item.Table);
                                    }

                                foreach (var tuple in uploadTables)
                                {
                                    ImportResult?result = null;
                                    using (token.MeasureTime(l =>
                                    {
                                        if (result != null)
                                        {
                                            import.MListElementsLite(_ => _.Copies).Where(mle => mle.Element.Type.Is(tuple.Type.ToTypeEntity())).UnsafeUpdateMList()
                                            .Set(mle => mle.Element.CopyTable, mle => l)
                                            .Set(mle => mle.Element.DisableForeignKeys, mle => tuple.Strategy.DisableForeignKeys.Value)
                                            .Set(mle => mle.Element.InsertedRows, mle => result.Inserted)
                                            .Set(mle => mle.Element.UpdatedRows, mle => result.Updated)
                                            .Execute();
                                        }
                                    }))
                                    {
                                        result = tuple.Strategy.Importer !.Import(machine, tuple.Table, tuple.Strategy, newDatabase);
                                    }
                                }

                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.Unlock, s => l).Execute()))
                                    UnlockTables(machine.ToLite());
                            }
                            finally
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.EnableForeignKeys, s => l).Execute()))
                                    foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys.Value))
                                    {
                                        EnableForeignKeys(item.Table);
                                    }
                            }

                            using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DropDatabase, s => l).Execute()))
                                DropDatabase(newDatabase);

                            token.ThrowIfCancellationRequested();

                            import.InDB().UnsafeUpdate()
                            .Set(s => s.State, s => DisconnectedImportState.Completed)
                            .Set(s => s.Total, s => s.CalculateTotal())
                            .Execute();

                            machine.InDB().UnsafeUpdate()
                            .Set(m => m.State, m => file == null ? DisconnectedMachineState.Fixed : DisconnectedMachineState.Connected)
                            .Execute();
                        }
                        catch (Exception e)
                        {
                            var ex = e.LogException();

                            import.InDB().UnsafeUpdate()
                            .Set(m => m.Exception, m => ex.ToLite())
                            .Set(m => m.State, m => DisconnectedImportState.Error)
                            .Execute();

                            machine.InDB().UnsafeUpdate()
                            .Set(m => m.State, m => DisconnectedMachineState.Faulted)
                            .Execute();

                            OnImportingError(machine, import, e);
                        }
                        finally
                        {
                            runningImports.Remove(import);

                            DisconnectedMachineEntity.Current = null;

                            OnEndImporting();
                        }
                    }
            });


            runningImports.Add(import, new RunningImports(task, cancelationSource));

            return(import);
        }
コード例 #57
0
        public async Task CreateAsync(Administrator entity)
        {
            await m_dataContext.Administrators.AddAsync(entity);

            await m_dataContext.SaveChangesAsync();
        }
コード例 #58
0
 public static string GetLoginId(this Administrator administrator)
 {
     return(administrator.EmailAddress.Address.Substring(0, administrator.EmailAddress.Address.IndexOf("@")));
 }
コード例 #59
0
 public RenderAdministrator(Administrator a)
 {
     AdministratorID = a.AdministratorID;
     Username = Convert.ToString(a.Username);
     Password = Convert.ToString(a.Password);
     FirstName = Convert.ToString(a.FirstName);
     LastName = Convert.ToString(a.LastName);
     IsActive = Convert.ToBoolean(a.IsActive);
 }
コード例 #60
0
 public async Task DeleteAsync(Administrator entity)
 {
     m_dataContext.Administrators.Remove(entity);
     await m_dataContext.SaveChangesAsync();
 }