Exemplo n.º 1
0
        /// <summary>
        /// The main entry point of the application - initializes database drivers, checks access rights, detects the current page type and does more setting accordingly.
        /// </summary>
        protected void Page_Init(object sender, EventArgs e)
        {
            DbServer = (DbServer)Enum.Parse(typeof(DbServer), System.Configuration.ConfigurationManager.AppSettings["ServerType"] as string);

            bool isFirstRun = System.Configuration.ConfigurationManager.AppSettings["FirstRun"] as string == "True";

            // detect the site type based on the beginning of the URL
            string lp = Request.Url.LocalPath;

            if (lp.StartsWith("/architect")){
                Common.Environment.GlobalState = GlobalState.Architect;
            }
            else if (lp.StartsWith("/admin")) {
                Common.Environment.GlobalState = GlobalState.Administer;
            }
            else if(lp == "/sys/users"){
                Common.Environment.GlobalState = GlobalState.UsersManagement;
            }
            else if(lp == "/sys/projects"){
                Common.Environment.GlobalState = GlobalState.ProjectsManagement;
            }
            else if(lp.StartsWith("/account")){
                Common.Environment.GlobalState = GlobalState.Account;
            }
            else if(lp.StartsWith("/FirstRun")){
                Common.Environment.GlobalState = GlobalState.FirstRun;
            }
            else
                Common.Environment.GlobalState = GlobalState.Error;

            bool firstRunMono = System.Configuration.ConfigurationManager.AppSettings["FirstRunMono"] == "True";

            if(isFirstRun && Common.Environment.GlobalState != GlobalState.FirstRun && !firstRunMono)
            {
                Response.Redirect("~/FirstRun/FirstRun.aspx");
            }
            if(!isFirstRun && Common.Environment.GlobalState == GlobalState.FirstRun)
            {
                Response.RedirectToRoute("DefaultRoute");
            }

            // set the warning only for logged in users
            System.Configuration.ConfigurationManager.AppSettings["SessionWarning"] =
                (user is MembershipUser) ? (Session.Timeout - 5).ToString() : "-1";

            if (isFirstRun)
            {
                return;
            }

            user = Membership.GetUser();

            // session expiry means logout, even if the provider would keep the user logged in
            if ((Session.IsNewSession || user == null)
                && CE.GlobalState != GlobalState.Account && CE.GlobalState != GlobalState.Error)
            {
                FormsAuthentication.SignOut();
                Response.RedirectToRoute("LockoutRoute", new { message = 7 });
            }

            IBaseDriver systemBaseDriver = null;

            // initialize the system driver based on the server type read from the configuration
            switch (DbServer)
            {
                case DbServer.MySql:
                    systemBaseDriver = new BaseDriverMySql(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString);
                    break;
                case DbServer.MsSql:
                    systemBaseDriver = new BaseDriverMsSql(ConfigurationManager.ConnectionStrings["MsSqlServer"].ConnectionString);
                    break;
                default:
                    break;
            }

            SysDriver = new SystemDriver(systemBaseDriver);

            if (firstRunMono && CE.GlobalState != GlobalState.FirstRun)
            {
                Response.Redirect("~/FirstRun/FirstRunMono.aspx");
            }
            if (!firstRunMono && CE.GlobalState == GlobalState.FirstRun)
            {
                Response.RedirectToRoute("DefaultRoute");
            }

            if (firstRunMono)
            {
                return;
            }

            // global service

            // is there a need for a reload of the project architecture?
            bool NewProjectLoad = false;

            // get current project and init drivers and architect
            if (Page.RouteData.Values.ContainsKey("projectName"))
            {
                ProjectName = Page.RouteData.Values["projectName"] as string;
                CE.Project actProject = SysDriver.GetProject(ProjectName);

                if (CE.project == null || actProject.Id != CE.project.Id || actProject.Version != CE.project.Version)
                {
                    Session.Clear();    // may not be neccessary in all cases, but better be safe
                    NewProjectLoad = true;
                }

                CE.project = SysDriver.GetProject(ProjectName);

                IBaseDriver statsBaseDriver = null;
                IBaseDriver webBaseDriver = null;

                switch (CE.project.ServerType)
                {
                    case DbServer.MySql:
                        statsBaseDriver = new BaseDriverMySql(CE.project.ConnstringIS);
                        Stats = new StatsMySql((BaseDriverMySql)statsBaseDriver, CE.project.WebDbName);
                        webBaseDriver = new BaseDriverMySql(CE._project.ConnstringWeb);
                        break;
                    case DbServer.MsSql:
                        statsBaseDriver = new BaseDriverMsSql(CE.project.ConnstringIS);
                        Stats = new StatsMsSql((BaseDriverMsSql)statsBaseDriver);
                        webBaseDriver = new BaseDriverMsSql(CE._project.ConnstringWeb);
                        break;
                    default:
                        break;
                }
                WebDriver = new WebDriver(webBaseDriver);

                Architect = new _min.Models.Architect(SysDriver, Stats);

                if ((!Page.IsPostBack || NewProjectLoad) && CE.GlobalState != GlobalState.Error)
                    // new version or differnet page ~ othervise access must have remained
                    // at least "allowable", if not allowed
                {
                    LockingAccess();    // just check
                }
                // check whether there is something to load at all
                if (Page.RouteData.Route != RouteTable.Routes["ArchitectInitRoute"])
                {
                    if (!SysDriver.ProposalExists())
                    {
                        if (CE.GlobalState == GlobalState.Architect)
                        {
                            Response.RedirectToRoute("ArchitectInitRoute", new { projectName = Page.RouteData.Values["projectName"] });
                            Response.End();
                        }
                        else
                        {
                            // change to some kind of "Not found" page
                            Response.RedirectToRoute("DefaultRoute", new { projectName = Page.RouteData.Values["projectName"] });
                            Response.End();
                        }
                    }

                    // get the current architecture - either extract from Session or directry from the DB, if project version has changed
                    int actVersion = CE.project.Version;
                    if (Session[CC.SESSION_ARCHITECTURE] is _min.Models.Panel
                        && Session[CC.SESSION_ARCHITECTURE_VERSION] is int
                        && (int)Session[CC.SESSION_ARCHITECTURE_VERSION] == actVersion)
                    {
                        SysDriver.SetArchitecture((MPanel)Session[CC.SESSION_ARCHITECTURE]);
                    }
                    else
                    {
                        SysDriver.FullProjectLoad();
                        Session[CC.SESSION_ARCHITECTURE] = SysDriver.MainPanel;
                        Session[CC.SESSION_ARCHITECTURE_VERSION] = CE.project.Version;
                    }
                }
            }

            // local issues

            if (!Page.IsPostBack)
            {

                if (user != null)
                {

                    List<string> adminOf;
                    List<string> architectOf;
                    List<CE.Project> allProjects = SysDriver.GetProjectObjects();
                    List<string> allNames = (from CE.Project p in allProjects select p.Name).ToList<string>();

                    object userId = user.ProviderUserKey;
                    int globalRights = SysDriver.GetUserRights(userId, null);
                    // by default, fetch only the sites to which the access rights are set explicitly,
                    // if global rights are sufficient, replace them with the complete lists
                    SysDriver.UserMenuOptions(userId, out adminOf, out architectOf);
                    if (globalRights % 100 >= 10) adminOf = allNames;
                    if (globalRights % 1000 >= 100) architectOf = allNames;

                    // decide on the upper menu content

                    MenuItem administerItem = new MenuItem("Administer", "admin");
                    foreach (string site in adminOf)
                    {
                        administerItem.ChildItems.Add(new MenuItem(site, site, null, "/admin/" + site));
                    }
                    if (adminOf.Count > 0)
                        NavigationMenu.Items.AddAt(0, administerItem);

                    // architect menu
                    MenuItem architectItem = new MenuItem("Architect", "architect");
                    foreach (string site in architectOf)
                    {
                        architectItem.ChildItems.Add(new MenuItem(site, site, null, "/architect/show/" + Server.UrlEncode(site)));
                    }
                    if (architectOf.Count > 0)
                        NavigationMenu.Items.AddAt(1, architectItem);

                    // user & projects management

                    NavigationMenu.Items.Add(new MenuItem("Manage users", "users", null, "/sys/users"));

                    if (globalRights >= 10000)   // this is the one and only project manager for this application instance
                        NavigationMenu.Items.Add(new MenuItem("Manage projects", "projects", null, "/sys/projects"));

                    // account settings for logged in users
                    MenuItem accountItem = new MenuItem("Account", "account");
                    accountItem.ChildItems.Add(new MenuItem("Change password", null, null, "/account/change-password"));
                    accountItem.ChildItems.Add(new MenuItem("Logout", null, null, "/account/logout"));
                    NavigationMenu.Items.Add(accountItem);
                }
                else {
                    MenuItem accountItem = new MenuItem("Account", "account");
                    accountItem.ChildItems.Add(new MenuItem("Login", null, null, "/account/login"));
                    accountItem.ChildItems.Add(new MenuItem("Register", null, null, "/account/register"));

                    NavigationMenu.Items.Add(accountItem);
                }
                NavigationMenu.RenderingMode = MenuRenderingMode.Table;
            }
        }
Exemplo n.º 2
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            /*
            string connstring = "Server=109.74.158.75;Uid=dotnet;Pwd=dotnet;Database=ks;pooling=false";
            DataTable log = new DataTable();
            log.Columns.Add(new DataColumn("query", typeof(string)));
            log.Columns.Add(new DataColumn("time", typeof(int)));
            BaseDriverMySql driver = new BaseDriverMySql(connstring, log);
            DateTime actDate = DateTime.Now;
            int[] inlist = { 18, 28, 38, 39 };
            DataTable table = driver.fetchAll("SELECT DATEDIFF(DATE(", actDate, "), `date`)", " FROM `users` WHERE `id` IN ", inlist);

            label1.Content = table.Rows.Count.ToString();

            Field f1 = new Field(1, "col", 1, "type", 1);
            //label1.Content += f1.column + " " + f1.typeName;
            //f1.typeName = "dddd";

            DataTable tree = new DataTable("tree");
            tree.Columns.Add("id", typeof(int));
            tree.Columns.Add("parent", typeof(int));

            tree.Rows.Add(1, null);
            tree.Rows.Add(2, 1);
            tree.Rows.Add(3, 1);
            tree.Rows.Add(4, 2);
            DataSet ds = new DataSet();
            ds.Tables.Add(tree);
            ds.Relations.Add(new DataRelation("r", tree.Columns[0], tree.Columns[1]));
            DataRow[] children = ds.Tables["tree"].Rows[0].GetChildRows("r");
            foreach (DataRow r in children) {
                label1.Content += " ch " + r[0];
            }

            */
            MySqlConnection conn = new MySqlConnection("Server=109.74.158.75;Uid=django;Pwd=heslo;Database=django;pooling=false");
            //MySqlCommand cmd = new MySqlCommand("SELECT * FROM users LIMIT 1", conn);

            conn.Open();
            //MySqlDataAdapter adap = new MySqlDataAdapter("SELECT * FROM users LIMIT 1", conn);
            label1.Content = conn.State.ToString();
            DataTable tab = new DataTable();
            conn.Close();
            /*
            adap.Fill(tab);
            textBox2.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            foreach (DataColumn col in tab.Columns) {
                textBox2.Text += col.ColumnName + Environment.NewLine;
                foreach (var prop in col.GetType().GetProperties())
                {
                    textBox2.Text +=  prop.Name + " = " + prop.GetValue(col, null) + Environment.NewLine;
                }
            }

            */

            textBox2.Text += "Creating basic objects" + Environment.NewLine;

            string dbName = "naborycz";

            stats = new StatsMySql(
                dbName, "Server=109.74.158.75;Uid=dotnet;Pwd=dotnet;Database=information_schema;pooling=true");
            sysDriver = new SystemDriverMySql(
                "Server=109.74.158.75;Uid=dotnet;Pwd=dotnet;Database=deskmin;pooling=true");
            CE.project = sysDriver.getProject(1);
            webDriver = new WebDriverMySql(
                "Server=109.74.158.75;Uid=dotnet;Pwd=dotnet;Database=" + dbName + ";pooling=false");
            architect = new Architect(sysDriver, stats);

            architect.Notice += new ArchitectNotice(Architect_Notice);
            this.AdditionalArchitectNotice += new ArchitectNotice(Architect_Notice);
            architect.Question += new ArchitectQuestion(Architect_Question);
            architect.Error += new ArchitectureError(Architect_Error);
            architect.Warning += new ArchitectWarning(Architect_Warning);

            //AsyncProposeCaller caller = new AsyncProposeCaller(architect.propose);
            //AsyncCallback callback  = new AsyncCallback(ProposalReady);

            Task<IPanel> proposalTask = new Task<IPanel>(()=>
            {
                return architect.propose();
            }

            );

            proposalTask.ContinueWith((taskResult) => ProposalReady(taskResult));

            proposalTask.Start();

            /*
                Task<string> task = new Task<string>((obj) =>
            {
                return Work(data);
            }, state);

            if (callBack != null)
            {
                task.ContinueWith((tsk) => callBack(tsk));
            }
            */

            //IAsyncResult asyncResult = caller.BeginInvoke(callback, proposal);
            //IPanel proposal = architect.propose();

            //IPanel proposal = caller.EndInvoke(asyncResult);

            /*
            DataRow row = tab.Rows[0];
            foreach(DataColumn col in row.Table.Columns){
                label1.Content += Environment.NewLine + col.ColumnName + " "
                + row[col.ColumnName];
            }
            conn.Close();
             */
        }