Inheritance: MonoBehaviour
    protected void BindSite()
    {
        colSite = objSite.Get_All();
        for (int i = 0; i < colSite.Count; i++)
        {
            for (int j = i; j < colSite.Count; j++)
            {

                if (String.Compare(colSite[i].Sitename, colSite[j].Sitename) > 0)
                {
                    Site_mst obj = new Site_mst();
                    obj = colSite[i];
                    colSite[i] = colSite[j];
                    colSite[j] = obj;

                }
            }

        }
        drpsite.DataTextField = "sitename";
        drpsite.DataValueField = "siteid";
        drpsite.DataSource = colSite;
        drpsite.DataBind();
        ListItem item = new ListItem();
        item.Text = "All";
        item.Value = "0";
        drpsite.Items.Add(item);
        //item.Text = "---Select Site---";
        //item.Value = "0";
        //drpsite.Items.Add(item);
        drpsite.SelectedValue = "0";
    }
Example #2
1
    protected void btnGonder_Click(object sender, EventArgs e)
    {
        int i;
        pnlPanel.Height = Unit.Percentage(75);
        pnlPanel.Width = Unit.Pixel(200);
        lblAd.BorderStyle = BorderStyle.Dotted;
        lblAd.BackColor = Color.LawnGreen;
        lblAd.BorderColor = Color.FromArgb(255, 255, 0, 0);
        txtAD.ForeColor = ColorTranslator.FromHtml("#00ff00");
        ListItem  Li=new ListItem("nolsun","denemeeee");
        chklCheckDeneme.Items.Add( Li);
        ///*****************************************************
        ///
        tbl.Controls.Clear();
        tbl.BorderStyle = BorderStyle.Double;
        tbl.BorderWidth = Unit.Pixel(1);

        int rows = 3, cols = 4;
        TableCell tc;
        for (int sat = 0; sat < rows; sat++)
        {
            TableRow tr = new TableRow();
            tbl.Controls.Add(tr);

            for (int sut = 0; sut < cols; sut++)
            {
                tc = new TableCell();
                tc.BorderStyle = BorderStyle.Double;
                tc.BorderWidth = Unit.Pixel(1);
                tc.Text = sat.ToString() + "  " + sut.ToString();
                tr.Controls.Add(tc);
            }

        }
    }
Example #3
1
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            // renk
            string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor));
            lstBackColor.DataSource = colorArray;
            lstBackColor.DataBind();

            // font
            System.Drawing.Text.InstalledFontCollection fonts = new System.Drawing.Text.InstalledFontCollection();
            foreach (FontFamily family in fonts.Families)
            {
                lstFontName.Items.Add(family.Name);
            }

            ListItem item = new ListItem();
            string[] borderStyleArray = Enum.GetNames(typeof(BorderStyle));
            lstBorder.DataSource = borderStyleArray;
            lstBorder.DataBind();

            lstBorder.SelectedIndex = 0;

            imgDefault.ImageUrl = "images/default-user-image.png";
            imgDefault.Visible = false;
        }
    }
Example #4
1
        /// <summary>
        /// Helper Method to set a Taxonomy Field on a list item
        /// </summary>
        /// <param name="ctx">The Authenticated ClientContext</param>
        /// <param name="listItem">The listitem to modify</param>
        /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param>
        public static void SetTaxonomyField(ClientContext ctx, ListItem listItem, Hashtable model)
        {
          
            FieldCollection _fields = listItem.ParentList.Fields;
            ctx.Load(_fields);
            ctx.ExecuteQuery();

            foreach(var _key in model.Keys)
            {
               var _termName = model[_key].ToString();
               TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(_key.ToString()));
               ctx.Load(_field);
               ctx.ExecuteQuery();
               Guid _id = _field.TermSetId;
               string _termID = AutoTaggingHelper.GetTermIdByName(ctx, _termName, _id );
               var _termValue = new TaxonomyFieldValue()
               {
                   Label = _termName,
                   TermGuid = _termID,
                   WssId = -1
               };

               _field.SetFieldValueByValue(listItem, _termValue);
               listItem.Update();
               ctx.ExecuteQuery();
            }
        }
Example #5
1
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!base.IsPostBack)
     {
         if (this.Session["admin"] == null)
         {
             base.Response.Redirect("/account/Login.aspx");
         }
         if (GeneralMethods.GetPermissions(HttpContext.Current.Request.Url.ToString(), this.Session["admin"].ToString()))
         {
             base.Response.Redirect("/Index.aspx");
         }
         Model.SelectRecord selectRecord = new Model.SelectRecord("Role", "", "*", "where isState=1 order by id desc");
         DataTable table = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0];
         if (table.Rows.Count > 0)
         {
             for (int i = 0; i < table.Rows.Count; i++)
             {
                 ListItem li=new ListItem(table.Rows[i][1].ToString(),table.Rows[i][0].ToString());
                 this.selIsState.Items.Add(li);
                 if (i == 0)
                 {
                     this.selIsState.SelectedValue = table.Rows[0][0].ToString();
                 }
             }
         }
         BLL.Organizational.BindToListBox(List_Organ, "");
     }
 }
Example #6
1
 private void CreateCheckBoxListGroup()
 {
     if (DataGridUser.EditItemIndex != -1)
     {
         CheckBoxList groupList = DataGridUser.Items[DataGridUser.EditItemIndex].Cells[6].FindControl("CheckBoxListGroup") as CheckBoxList;
         FSEye.Security.User user = TheAdminServer.SecurityManager.GetUser((int)Store.Rows[DataGridUser.EditItemIndex].ItemArray[0]);
         if (groupList != null)
         {
             Group[] groups = TheAdminServer.SecurityManager.GetAllGroups();
             if (groups != null && groups.Length != 0)
                 foreach (Group group in groups)
                 {
                     ListItem item = new ListItem(group.SecurityObject.Name, group.SecurityObject.Id.ToString());
                     if(user!=null)
                     {
                         foreach (int groupId in user.Groups)
                         {
                             if (groupId == group.SecurityObject.Id) item.Selected = true;
                         }
                     }
                     
                     groupList.Items.Add(item);
                 }
         }
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.cadenaconexion =
            "Data Source=LOCALHOST;Initial Catalog=HOSPITAL;User ID=SA";
        this.cn = new SqlConnection(this.cadenaconexion);
        this.com = new SqlCommand();

        //LA PRIMERA VEZ...
        if (this.Page.IsPostBack == false)
        {
            this.lstdepartamentos.AutoPostBack = true;
            this.com.Connection = this.cn;
            this.com.CommandType = System.Data.CommandType.Text;
            this.com.CommandText = "SELECT * FROM DEPT";
            this.cn.Open();
            this.lector = this.com.ExecuteReader();
            while (this.lector.Read())
            {
                ListItem it = new ListItem();
                it.Text = this.lector["DNOMBRE"].ToString();
                it.Value = this.lector["DEPT_NO"].ToString();
                this.lstdepartamentos.Items.Add(it);
            }
            this.lector.Close();
            this.cn.Close();
    }
}
    protected void FillDropDownList()
    {
        //从web.config中获取数据库连接
        string connectionStr = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        //创建与数据库的连接
        using (SqlConnection conn = new SqlConnection(connectionStr))
        {
            conn.Open();
            //新建一个SqlCommand对象
            SqlCommand cmd = new SqlCommand("Select * from Customers", conn);
            //创建一个SqlDataReader对象
            SqlDataReader sdr = cmd.ExecuteReader();
            //一次一行读取SqlDataReader对象并添加到DropDownList中去。
            while (sdr.Read())
            {
                ListItem newItem = new ListItem();
                newItem.Text = sdr["CompanyName"] as string;
                newItem.Value = sdr["CustomerID"].ToString();
                DropDownList1.Items.Add(newItem);
            }
            //使用完毕记得关毕SqlDataReader对象
            sdr.Close();

        }
    }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast<JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F3851068";

            if (!string.IsNullOrEmpty(typedDefinition.Standalone))
                item["DisplayTemplateJSTemplateType"] = typedDefinition.Standalone;

            if (!string.IsNullOrEmpty(typedDefinition.TargetControlType))
                item["DisplayTemplateJSTargetControlType"] = typedDefinition.TargetControlType;

            if (!string.IsNullOrEmpty(typedDefinition.TargetListTemplateId))
                item["DisplayTemplateJSTargetListTemplate"] = typedDefinition.TargetListTemplateId;

            if (!string.IsNullOrEmpty(typedDefinition.TargetScope))
                item["DisplayTemplateJSTargetScope"] = typedDefinition.TargetScope;

            if (!string.IsNullOrEmpty(typedDefinition.IconUrl))
            {
                var iconValue = new FieldUrlValue { Url = typedDefinition.IconUrl };

                if (!string.IsNullOrEmpty(typedDefinition.IconDescription))
                    iconValue.Description = typedDefinition.IconDescription;

                item["DisplayTemplateJSIconUrl"] = iconValue;
            }
        }
        protected override void MapProperties(object modelHost, ListItem item, ContentPageDefinitionBase definition)
        {
            base.MapProperties(modelHost, item, definition);

            var typedDefinition = definition.WithAssertAndCast<FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            item[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F38510660400F643FF79F6BD764F8A469B6F153396EE";


            if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileURL))
            {
                var crawlerXSLFileValue = new FieldUrlValue { Url = typedDefinition.CrawlerXSLFileURL };

                if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileDescription))
                    crawlerXSLFileValue.Description = typedDefinition.CrawlerXSLFileDescription;

                item["CrawlerXSLFile"] = crawlerXSLFileValue;
            }

            if (!string.IsNullOrEmpty(typedDefinition.CompatibleManagedProperties))
                item["CompatibleManagedProperties"] = typedDefinition.CompatibleManagedProperties;

            if (typedDefinition.CompatibleSearchDataTypes.Count > 0)
            {
                item["CompatibleSearchDataTypes"] = typedDefinition.CompatibleSearchDataTypes.ToArray();
            }
        }
    public void getfiles(string dir)
    {
        ddFilesMovie.Items.Clear();

        ListItem li1 = new ListItem();
        li1.Text = "-- select --";
        li1.Value = "-1";

        ddFilesMovie.Items.Add(li1);

        ArrayList af = new ArrayList();
        string[] Filesmovie = Directory.GetFiles(dir);
        foreach (string file in Filesmovie)
        {
            string appdir = Server.MapPath("~/App_Uploads_Img/") + ddCatMovie.SelectedValue;
            string filename = file.Substring(appdir.Length + 1);

            if ((!filename.Contains("_svn")) && (!filename.Contains(".svn")))
            {
                if (filename.ToLower().Contains(".mov") || filename.ToLower().Contains(".flv") || filename.ToLower().Contains(".wmv") )
                {
                    ListItem li = new ListItem();
                    li.Text = filename;
                    li.Value = filename;
                    ddFilesMovie.Items.Add(li);
                }
            }
        }
        UpdatePanel1Movie.Update();
    }
Example #12
1
 protected override void SetProperties(ListItem item)
 {
     BaseSet(item, FIELD_FIRSTNAME, SpeakerFirstName);
     BaseSet(item, FIELD_LASTNAME, SpeakerLastName);
     BaseSet(item, FIELD_EMAIL, SpeakerEmail);            
     BaseSet(item, FIELD_ID, SpeakerId);            
 }
    public void fill_list()
    {
        DropDownList2.Items.Clear();
        DropDownList3.Items.Clear();
        DropDownList2.Items.Add("Select");
        DropDownList3.Items.Add("Select");
        //string s = Request.Cookies["fdet"].Values["city"];
        //Response.Write(s);

        string cnstr = @"Data Source=.\sqlexpress;AttachDbFilename=E:\projects\FIR\fir_sys\fir.mdf;Integrated Security=True";
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        con.ConnectionString = cnstr;
        cmd.Connection = con;
        string query = "select distinct zone from stations where city='" + DropDownList1.SelectedItem.ToString() + "'";
        con.Open();

        cmd.CommandText = query;
        SqlDataReader r = cmd.ExecuteReader();
        while (r.Read())
        {
            ListItem z = new ListItem();

            z.Text = r[0].ToString();

            DropDownList2.Items.Add(z);

            //DropDownList2.Items.Add(r[0].ToString);

        }
        con.Close();
           TextBox5.Focus();
    }
Example #14
0
        public static Event Parse(ListItem sharepointListItem)
        {
            Event e = new Event()
            {
                ID = (int)sharepointListItem["ID"],
                Title = (string)sharepointListItem["Title"],
                Created = DateTime.Parse(sharepointListItem["Created"].ToString()),
                Description = (string)sharepointListItem["Description"],
                Location = (string)sharepointListItem["Location"],
                Category = (string)sharepointListItem["Category"],
                UID = sharepointListItem["UID"] == null ? Guid.NewGuid().ToString() : sharepointListItem["UID"].ToString(),
                EventDate = DateTime.Parse(sharepointListItem["EventDate"].ToString()),
                EndDate = DateTime.Parse(sharepointListItem["EndDate"].ToString()),
                Duration = (int)sharepointListItem["Duration"],
                Recurrence = (bool)sharepointListItem["fRecurrence"],
                RecurrenceData = (string)sharepointListItem["RecurrenceData"],
                RecurrenceID = sharepointListItem["RecurrenceID"] != null ? DateTime.Parse(sharepointListItem["RecurrenceID"].ToString()) : DateTime.MinValue,
                MasterSeriesItemID = sharepointListItem["MasterSeriesItemID"] == null ? -1 : (int)sharepointListItem["MasterSeriesItemID"],
                EventType = (EventType)Enum.Parse(typeof(EventType), sharepointListItem["EventType"].ToString()),
                AllDayEvent = (bool)sharepointListItem["fAllDayEvent"],
                LastModified = DateTime.Parse(sharepointListItem["Last_x0020_Modified"].ToString())
            };

            return e;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ret"]))
            {
                dt = objKat.HentAlleKategorier();

                foreach (DataRow kategori in dt.Rows)
                {
                    ListItem li = new ListItem(kategori["fldKategori"].ToString(), kategori["fldKatID"].ToString());
                    ddlKat.Items.Add(li);
                }
                objNyhed._id = Convert.ToInt32(Request.QueryString["ret"]);

                dt = objNyhed.HentNyhedFraID();

                if (!IsPostBack)
                {
                    ShowSubject();

                }

                txtOverskrift.Text = dt.Rows[0]["fldOverskrift"].ToString();
                txtTeaser.Text = dt.Rows[0]["fldTeaser"].ToString();
                txtTekst.Text = dt.Rows[0]["fldTekst"].ToString();
                ddlKat.SelectedValue = dt.Rows[0]["fldKatID_fk"].ToString();

            }
            else
            {
                Response.Redirect("NyhedRetSlet.aspx");
            }
        }
    }
    public void BindDrpDepartment()
    {
        BLLCollection<Department_mst> col = new BLLCollection<Department_mst>();
        Department_mst Objdepartment = new Department_mst();
        int Selectedsiteval = Convert.ToInt16(DrpSite.SelectedValue);
        if (Selectedsiteval==0)
        {
            DrpDepartment.DataSource = col;
            DrpDepartment.DataBind();
            ListItem item = new ListItem();
            item.Text = "--------------Select---------------";
            item.Value = "0";
            DrpDepartment.Items.Add(item);
            DrpDepartment.SelectedValue = "0";
         }
          else
         {
             col = Objdepartment.Get_All_By_SiteId(Selectedsiteval);

             DrpDepartment.DataTextField = "departmentName";
             DrpDepartment.DataValueField = "deptid";
             DrpDepartment.DataSource = col;
             DrpDepartment.DataBind();
             ListItem item = new ListItem();
             item.Text = Resources.MessageResource.errSelectDept.ToString();
             item.Value = "0";
             DrpDepartment.Items.Add(item);
             DrpDepartment.SelectedValue = "0";
        }
    }
    public void LoadJobType()
    {
        DataAccess dataaccess = new DataAccess();

        using (SqlConnection Sqlcon = dataaccess.OpenConnection())
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                cmd.Connection = Sqlcon;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "GetJobType";
                cmd.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar, 50));
                cmd.Parameters["@Action"].Value = "select";
                cmd.Parameters.Add("@Exists", SqlDbType.Int).Direction = ParameterDirection.Output;
                SqlAda = new SqlDataAdapter(cmd);
                ds = new DataSet();
                SqlAda.Fill(ds);
                ddlJobType.DataSource = ds;
                ddlJobType.DataTextField = "JobTypeName";
                ddlJobType.DataValueField = "JobTypeId";
                ddlJobType.DataBind();
                if (ddlJobType.Items.Count >= 1)
                {
                    ListItem lstitem = new ListItem();
                    lstitem.Text = "[Select]";
                    lstitem.Value = "0";
                    ddlJobType.Items.Insert(0, lstitem);
                }
            }
        }
    }
Example #18
0
    /// <summary>
    /// Fill year drop down with the avaliable news year
    /// </summary>
    private void FillYearDropDown()
    {
        var allNewsArticles = SiteDataManager.GetLatestNews();
        if (allNewsArticles != null && allNewsArticles.Any())
        {
            var yearList = allNewsArticles.Select(x => x.SmartForm.Date.Year).Distinct().ToList();
            if(yearList != null && yearList.Any())
            {
                int currentYear = DateTime.Now.Year;
                lblYearSelected.Text = currentYear.ToString();

                ListItem item = null;
                //initial item
                item = new ListItem("-Select a year-", "");
                ddlArchiveYear.Items.Add(item);

                foreach(var y in yearList)
                {
                    item = new ListItem(y.ToString(), y.ToString());
                    if (y == currentYear)
                        item.Selected = true;
                    ddlArchiveYear.Items.Add(item);
                }
            }
        }
    }
Example #19
0
 private void CreateCheckBoxListRoleType()
 {
     ListItem item = new ListItem(string.Format("{0}[{1}]", StringDef.Jiashi, StringDef.ProfessionalNotChoose), "0,-1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Jiashi, StringDef.XuanFeng), "0,0");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Jiashi, StringDef.XingTian), "0,1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Daoshi, StringDef.ProfessionalNotChoose), "1,-1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Daoshi, StringDef.ZhenRen), "1,0");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Daoshi, StringDef.TianShi), "1,1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Yiren, StringDef.ProfessionalNotChoose), "2,-1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Yiren, StringDef.ShouShi), "2,0");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
     item = new ListItem(string.Format("{0}[{1}]", StringDef.Yiren, StringDef.YiShi), "2,1");
     item.Selected = true;
     CheckBoxListRoleType.Items.Add(item);
 }
Example #20
0
        public void InnerListTest()
        {
            List li				= new List(this._td, "L1", ListStyles.Bullet, "L1P1");
            ListItem lit		= new ListItem(li);
            lit.Paragraph.TextContent.Add(new SimpleText(lit, "Hello"));
            li.Content.Add(lit);

            //The ListItem will become a inner list !!
            lit					= new ListItem(li);
            lit.Paragraph.TextContent.Add(new SimpleText(lit, "Hello Again"));

            //Inner List - see the constrctor usage !
            List liinner		= new List(this._td, li);

            Assert.IsNull(liinner.Style, "Style must be null! The inner list inherited his style from the outer list!");

            ListItem litinner	= new ListItem(liinner);
            litinner.Paragraph.TextContent.Add(new SimpleText(lit, "Hello i'm in the inner list"));
            liinner.Content.Add(litinner);

            //Add the inner list to ListItem lit
            lit.Content.Add(liinner);

            //Add the ListItem with inner list inside
            li.Content.Add(lit);

            //Add the whole list to the document
            this._td.Content.Add(li);

            this._td.SaveTo("innerlist.odt");
        }
Example #21
0
 protected override void ReadProperties(ListItem item)
 {
     SpeakerId = BaseGet<string>(item, FIELD_ID);
     SpeakerFirstName = BaseGet<string>(item, FIELD_FIRSTNAME);
     SpeakerLastName = BaseGet<string>(item, FIELD_LASTNAME);
     SpeakerEmail = BaseGet<string>(item, FIELD_EMAIL);           
 }
    protected void btnAdd_Click(object sender, System.EventArgs e)
    {
        //如果Text文本框输入的数据为空
        if (txtItemText.Text.Trim() == "")
        {
            //显示错误提示
            lblInfo.Text ="Text值不能为空";
        }
        //如果Value文本框输入的数据为空
        else if (txtItemValue.Text.Trim() == "")
        {
            lblInfo.Text = "Value值不能为空";
        }
        else
        {
            //创建一个新的选项
            ListItem li = new ListItem();

            li.Text = txtItemText.Text.Trim();
            li.Value = txtItemValue.Text.Trim();

            //将选项添加到下拉列表中
            dplItems.Items.Add(li);

            //选中最后一个选项(即新添加进的选项)
            dplItems.SelectedIndex = dplItems.Items.Count - 1;

            //显示信息并设置按钮可用状态
            DisplayInfoAndSetButtonEnabled();

            //清空Text与Value文本框
            txtItemText.Text = "";
            txtItemValue.Text = "";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Title = "问答题管理";
        if (!IsPostBack)
        {
            if (Session["userID"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                string userId = Session["userID"].ToString();
                string userName = userService.GetUserName(userId);
                Label i1 = (Label)Page.Master.FindControl("labUser");
                i1.Text = userName;

                //展示绑定的数据并将它展示在下拉列表中
                ddlCourse.Items.Clear();
                Course course = new Course();
                Course[] list = singleSelectedService.ListCourse();

                for (int i = 0; i < list.Length; i++)
                {
                    ListItem item = new ListItem(list[i].DepartmentName.ToString(), list[i].DepartmentId.ToString());
                    ddlCourse.Items.Add(item);
                }

                string selectvalue = this.ddlCourse.SelectedValue;
                this.GridView1.DataSource = questionProblemService.GetQuestionProblem(selectvalue);
                this.GridView1.DataBind();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["auth"] == null)
        {
            Response.Redirect("Homepage.aspx");
        }
        Button1.Text = "Delete";
        ListItem newItem = new ListItem();
        string constr = Session["connection"].ToString();
        OdbcConnection cn = new OdbcConnection(constr);
        cn.Open();
        string sql = "select agent_id from AGENT";
        OdbcCommand cmd = new OdbcCommand(sql, cn);
        OdbcDataReader reader;

        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            newItem = new ListItem();
            newItem.Text = reader["agent_id"].ToString();
            DropDownList1.Items.Add(newItem);
        }
        reader.Close();
        cn.Close();
    }
		protected void Add()
		{
			if (!this.Disabled)
			{
				string viewStateString = base.GetViewStateString("ID");
				TreeviewEx ex = this.FindControl(viewStateString + "_all") as TreeviewEx;
				Assert.IsNotNull(ex, typeof(DataTreeview));
				Listbox listbox = this.FindControl(viewStateString + "_selected") as Listbox;
				Assert.IsNotNull(listbox, typeof(Listbox));
				Item selectionItem = ex.GetSelectionItem();
				if (selectionItem == null)
				{
					SheerResponse.Alert("Select an item in the Content Tree.", new string[0]);
				}
				else if (!this.HasExcludeTemplateForSelection(selectionItem))
				{
					if (this.IsDeniedMultipleSelection(selectionItem, listbox))
					{
						SheerResponse.Alert("You cannot select the same item twice.", new string[0]);
					}
					else if (this.HasIncludeTemplateForSelection(selectionItem))
					{
						SheerResponse.Eval("scForm.browser.getControl('" + viewStateString + "_selected').selectedIndex=-1");
						ListItem control = new ListItem();
						control.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("L");
						Sitecore.Context.ClientPage.AddControl(listbox, control);
						control.Header = selectionItem.DisplayName;
						control.Value = control.ID + "|" + selectionItem.ID;
						SheerResponse.Refresh(listbox);
						SetModified();
					}
				}
			}
		}
        public override void AddPage(ListItem item, ProvisioningTemplate template)
        {
            string url = GetUrl(item, true);
            if (null == template.Pages.Find((p) => string.Equals(p.Url, url, System.StringComparison.OrdinalIgnoreCase)))
            {
                var fieldValues = item.FieldValues;

                var pageLayoutUrl = string.Empty;
                if (fieldValues.ContainsKey("PublishingPageLayout"))
                {
                    pageLayoutUrl = fieldValues["PublishingPageLayout"] == null ? "" : (fieldValues["PublishingPageLayout"] as FieldUrlValue).Url;
                }
                pageLayoutUrl = this.TokenParser.TokenizeUrl(pageLayoutUrl);

                string html = "";
                if (fieldValues.ContainsKey("PublishingPageContent"))
                {
                    html = fieldValues["PublishingPageContent"] == null ? " " : fieldValues["PublishingPageContent"].ToString();
                }

                var title = fieldValues["Title"] == null ? "" : fieldValues["Title"].ToString();

                bool needToOverwrite = NeedOverride(item);
                var webParts = GetWebParts(item);
                bool isHomePage = IsWelcomePage(item);
                PublishingPage page = new PublishingPage(url, title, html, pageLayoutUrl, needToOverwrite, webParts, isHomePage);
                template.Pages.Add(page);
            }
        }
 public void OnMenuChanged(object sender, EventArgs e)
 {
     using (DBDataContext db = new DBDataContext())
     {
         var menudata = from LM in db.LeftMenu
                        orderby LM.Order
                        select LM;
         int i;
         if (int.TryParse(ddlMenu.SelectedValue, out i))
         {
             cblSubmenu.Items.Clear();
             foreach (var sd in menudata)
             {
                 if (sd.id != i && (sd.ParetnId == i || sd.ParetnId == null))
                 {
                     ListItem l = new ListItem();
                     l.Selected = sd.ParetnId == i;
                     l.Text = sd.ItemName;
                     l.Value = sd.id.ToString();
                     cblSubmenu.Items.Add(l);
                 }
             }
         }
     }
 }
Example #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //site içi sayfa linkleri listeleniyor
            Snlg_DBConnect vt = new Snlg_DBConnect(true);

            Snlg_DBParameter[] DBPrms = new Snlg_DBParameter[1];
            DBPrms[0] = new Snlg_DBParameter("@Dil", SqlDbType.SmallInt, DBNull.Value);
            using (SqlDataReader sdr = vt.DBReaderOlustur("snlg_V1.msp_LinkListele", CommandType.StoredProcedure, DBPrms))
            {
                while (sdr.Read())
                {
                    ListItem item = new ListItem(sdr["LinkText"].ToString(), sdr["Link"].ToString());
                    item.Selected = sdr["Link"].ToString() == "/" + Snlg_ConfigValues.startPage;
                    DDLLinks.Items.Add(item);
                }
            }

            DataTable dtLang= vt.DataTableOlustur("SELECT DId, Name FROM snlg_V1.TblDiller WHERE Aktif = 1 ORDER BY Name", CommandType.Text);
            DDLDefLang.DataSource = dtLang;
            DDLDefLang.DataBind();
            DDLAdminLang.DataSource = dtLang;
            DDLAdminLang.DataBind();

            vt.Kapat();
            CBExtension.Checked = !string.IsNullOrEmpty(Snlg_ConfigValues.urlExtension);
            try { DDLDefLang.SelectedValue = Snlg_ConfigValues.defaultLangId; }
            catch { }
            try { DDLAdminLang.SelectedValue = Snlg_ConfigValues.adminDefaultLangId.ToString(); }
            catch { }
        }
    }
Example #29
0
        static void Main(string[] args)
        {
            var firstItem = new ListItem<int>(5, null);
            var linkedList = new LinkedList<int>(firstItem);

            //TODO: IMPLEMENT FUNCTIONS
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (LoginSession.IsLogin())
                {
                    if (!LoginSession.IsAdmin())
                    {
                        if (!LoginSession.IsView("MN-00016"))
                        {
                            Response.Redirect("NoPermitsion.aspx");
                        }
                    }
                }
                else
                {
                    Response.Redirect("/Account/Login.aspx?Url=" + Request.Url.PathAndQuery);
                }
                hidUserName.Value = LoginSession.UserName();

                #region
                UsersMN     aUsersMN     = new UsersMN();
                CategorysMN aCategorysMN = new CategorysMN();
                ListItem    aListItem    = new ListItem();
                string      CatTypeCode  = string.Empty;
                CatTypeCode = "CT-00003"; //Application Site
                ddlApplicationSite.DataSource     = aCategorysMN.ListCategorys(string.Empty, string.Empty, CatTypeCode);
                ddlApplicationSite.DataValueField = "CatCode";
                ddlApplicationSite.DataTextField  = "CatName";
                ddlApplicationSite.DataBind();

                //CatTypeCode = "CT-00004"; //Doc Type
                //ddlDocType.DataSource = aCategorysMN.ListCategorys(string.Empty, string.Empty, CatTypeCode);
                //ddlDocType.DataValueField = "CatCode";
                //ddlDocType.DataTextField = "CatName";
                //ddlDocType.DataBind();

                #endregion

                #region
                string PublishDocument   = Convert.ToString(Request.QueryString["PublishDocument"]);
                string ObsoletedDocument = Convert.ToString(Request.QueryString["ObsoletedDocument"]);

                if (!String.IsNullOrEmpty(PublishDocument))
                {
                    #region
                    RegisterPublishDocumentMN aRegisterPublishDocumentMN = new RegisterPublishDocumentMN();
                    txtApplicationName.Text  = LoginSession.FullName();
                    txtApplicationNO.Text    = string.Empty;
                    txtApplicationDate.Text  = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    hidPublishDocument.Value = PublishDocument;

                    DataTable aData = aRegisterPublishDocumentMN.ListRegisterPublishDocument(PublishDocument, string.Empty, "C26", string.Empty,
                                                                                             string.Empty, string.Empty, string.Empty, string.Empty, Convert.ToDateTime("1900-01-01"), Convert.ToDateTime("1900-01-01"));
                    if (aData.Rows.Count > 0)
                    {
                        ddlApplicationSite.Text = Convert.ToString(aData.Rows[0]["ApplicationSite"]);
                        //hidApplicableSite.Value = Convert.ToString(aData.Rows[0]["ApplicableSite"]);
                        txtDocNO.Text   = Convert.ToString(aData.Rows[0]["DocumentNo"]);
                        txtREV.Text     = Convert.ToString(aData.Rows[0]["Rev"]);
                        txtDocName.Text = Convert.ToString(aData.Rows[0]["DocumentName"]);

                        txtReleaseDate.Text = Convert.ToString(aData.Rows[0]["EffectiveDate_Text"]);
                        //ddlDocType.Text = Convert.ToString(aData.Rows[0]["DocumentType"]);
                        //hidApplicableBU.Value = Convert.ToString(aData.Rows[0]["ApplicableBU"]);
                        //hidDepartmentCheck.Value = Convert.ToString(aData.Rows[0]["DepartmentCheck"]);

                        DataTable aTemp = new DataTable();
                        aTemp = aCategorysMN.ListCategorys(Convert.ToString(aData.Rows[0]["Department"]), string.Empty, string.Empty);
                        txtApplicationDep.Text = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["CatName"]) : string.Empty;
                        txtDepartment.Text     = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["CatName"]) : string.Empty;
                        aTemp           = aUsersMN.GetManagerCurrent();
                        txtManager.Text = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["HoTen"]) : string.Empty;
                    }

                    #endregion
                }
                else
                {
                    if (!String.IsNullOrEmpty(ObsoletedDocument))
                    {
                        #region

                        ApplicationObsoletedDocumentMN aApplicationObsoletedDocumentMN = new ApplicationObsoletedDocumentMN();
                        DataTable aData = aApplicationObsoletedDocumentMN.ListApplicationObsoletedDocument(ObsoletedDocument, string.Empty, string.Empty,
                                                                                                           string.Empty, string.Empty, string.Empty, string.Empty, Convert.ToDateTime("1900-01-01"), Convert.ToDateTime("1900-01-01"));
                        if (aData.Rows.Count > 0)
                        {
                            txtApplicationName.Text    = Convert.ToString(aData.Rows[0]["HoTen"]);
                            hidID.Value                = Convert.ToString(aData.Rows[0]["ID"]);
                            hidObsoletedDocument.Value = ObsoletedDocument;
                            hidStates.Value            = Convert.ToString(aData.Rows[0]["States"]);
                            txtApplicationNO.Text      = Convert.ToString(aData.Rows[0]["ObsoletedDocument"]);
                            hidPublishDocument.Value   = Convert.ToString(aData.Rows[0]["PublishDocument"]);
                            txtEffectiveDate.Text      = Convert.ToDateTime(aData.Rows[0]["EffectiveDate"]).Year > 1900 ? Convert.ToDateTime(aData.Rows[0]["EffectiveDate"]).ToString("yyyy/MM/dd") : string.Empty;
                            txtApplicationDate.Text    = Convert.ToString(aData.Rows[0]["ApplicationDate_Text"]);

                            ddlApplicationSite.Text = Convert.ToString(aData.Rows[0]["ApplicationSite"]);
                            //hidApplicableSite.Value = Convert.ToString(aData.Rows[0]["ApplicableSite"]);
                            txtDocNO.Text   = Convert.ToString(aData.Rows[0]["DocumentNo"]);
                            txtREV.Text     = Convert.ToString(aData.Rows[0]["Rev"]);
                            txtDocName.Text = Convert.ToString(aData.Rows[0]["DocumentName"]);

                            txtReleaseDate.Text = Convert.ToString(aData.Rows[0]["EffectiveDate_Text"]);
                            //ddlDocType.Text = Convert.ToString(aData.Rows[0]["DocumentType"]);
                            //hidApplicableBU.Value = Convert.ToString(aData.Rows[0]["ApplicableBU"]);
                            //hidDepartmentCheck.Value = Convert.ToString(aData.Rows[0]["DepartmentCheck"]);

                            DataTable aTemp = new DataTable();
                            aTemp = aCategorysMN.ListCategorys(Convert.ToString(aData.Rows[0]["Department"]), string.Empty, string.Empty);
                            txtApplicationDep.Text = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["CatName"]) : string.Empty;
                            txtDepartment.Text     = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["CatName"]) : string.Empty;
                            aTemp           = aUsersMN.GetManagerCurrent();
                            txtManager.Text = aTemp.Rows.Count > 0 ? Convert.ToString(aTemp.Rows[0]["HoTen"]) : string.Empty;

                            txtReasonObsoleted.Text = Convert.ToString(aData.Rows[0]["ReasonObsoleted"]);
                        }

                        #endregion
                    }
                }
                #endregion
            }
        }
Example #31
0
 /// <summary>
 /// Instantiates a wiki page object
 /// </summary>
 /// <param name="page">ListItem holding the page to analyze</param>
 /// <param name="pageTransformation">Page transformation information</param>
 public WikiPage(ListItem page, PageTransformation pageTransformation) : base(page, pageTransformation)
 {
     this.parser = new HtmlParser();
 }
        protected void InsertFisrtItem(DropDownList ddlList, string text)
        {
            ListItem item = new ListItem(text, "0");

            ddlList.Items.Insert(0, item);
        }
Example #33
0
        //Method to add user's answers to correct questions
        public void addAnswersToQuestion()
        {
            List <Question> questions = currentUser.newTest.questions;
            int             c         = questions.Count();

            for (int i = 0; i < c; i++)
            {
                Question      currentQuestion = questions[i];
                List <Answer> currentAnswers  = currentQuestion.answerList;
                List <Answer> userAnswers     = new List <Answer>();

                int     qId = questions[i].id;
                Control div = FindControl(qId.ToString());

                foreach (Control ctrl in div.Controls)
                {
                    if (ctrl is RadioButtonList)
                    {
                        RadioButtonList rblist = (RadioButtonList)ctrl;

                        for (int rb = 0; rb < rblist.Items.Count; rb++)
                        {
                            if (rblist.Items[rb].Selected)
                            {
                                ListItem li            = rblist.Items[rb];
                                Answer   currentAnswer = currentAnswers[rb];
                                Answer   userAnswer    = new Answer()
                                {
                                    id      = li.Value,
                                    correct = currentAnswer.correct,
                                    text    = currentAnswer.text
                                };
                                userAnswers.Add(userAnswer);
                            }
                        }
                    }
                    else if (ctrl is CheckBoxList)
                    {
                        CheckBoxList cblist = (CheckBoxList)ctrl;

                        for (int cb = 0; cb < cblist.Items.Count; cb++)
                        {
                            if (cblist.Items[cb].Selected)
                            {
                                ListItem li            = cblist.Items[cb];
                                Answer   currentAnswer = currentAnswers[cb];
                                Answer   userAnswer    = new Answer()
                                {
                                    id      = li.Value,
                                    correct = currentAnswer.correct,
                                    text    = currentAnswer.text
                                };
                                userAnswers.Add(userAnswer);
                            }
                        }
                    }
                    currentQuestion.userAnswerList = userAnswers;
                }
                questions[i] = currentQuestion;
            }
            currentUser.newTest.questions = questions;

            //System.Diagnostics.Debug.WriteLine(currentUser.newTest.questions[4].userAnswerList[0].id);
        }
Example #34
0
        private void HandleWikiPageProvision(ListItem listItem, WebPartDefinitionBase webpartModel)
        {
            if (!webpartModel.AddToPageContent)
            {
                return;
            }

            TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");

            var context = listItem.Context;

            var targetFieldName = string.Empty;

            if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.WikiField;
            }
            else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
                return;
            }

            var wikiTemplate = new StringBuilder();

            var wpId = webpartModel.Id
                       .Replace("g_", string.Empty)
                       .Replace("_", "-");

            var content = listItem[targetFieldName] == null
                ? string.Empty
                : listItem[targetFieldName].ToString();

            wikiTemplate.AppendFormat(
                "​​​​​​​​​​​​​​​​​​​​​​<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
            wikiTemplate.AppendFormat("     <div class='ms-rtestate-read {0}' id='div_{0}'>", wpId);
            wikiTemplate.AppendFormat("     </div>");
            wikiTemplate.AppendFormat("</div>");

            var wikiResult = wikiTemplate.ToString();

            if (string.IsNullOrEmpty(content))
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Page content is empty Generating new one.");

                content = wikiResult;

                listItem[targetFieldName] = content;
                listItem.Update();

                context.ExecuteQueryWithTrace();
            }
            else
            {
                if (content.ToUpper().IndexOf(wpId.ToUpper()) == -1)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Replacing web part with ID: [{0}] on the page content.", wpId);

                    content += wikiResult;

                    listItem[targetFieldName] = content;
                    listItem.Update();

                    context.ExecuteQueryWithTrace();
                }
                else
                {
                    TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                                               "Cannot find web part ID: [{0}] the page content. Provision won't add web part on the page content.",
                                               new object[]
                    {
                        wpId
                    });
                }
            }
        }
Example #35
0
        public void BindNumType(MapAttr mattr)
        {
            this.Pub1.AddTable("align=left");
            this.Pub1.AddCaptionLeft("数据获取 - 当一个字段值需要从其它表中得到时,请设置此功能。");
            this.Pub1.AddTR();
            this.Pub1.Add("<TD>");
            RadioBtn rb = new RadioBtn();

            rb.GroupName = "s";
            rb.Text      = "方式0:不做任何设置。";
            rb.ID        = "RB_Way_0";
            if (mattr.HisAutoFull == AutoFullWay.Way0)
            {
                rb.Checked = true;
            }
            this.Pub1.AddFieldSet(rb);
            this.Pub1.Add("不做任何设置。");
            this.Pub1.AddFieldSetEnd();

            this.Pub1.AddTDEnd();
            this.Pub1.AddTREnd();

            this.Pub1.AddTR();
            this.Pub1.Add("<TD>");

            rb           = new RadioBtn();
            rb.GroupName = "s";
            rb.Text      = "方式1:本表单中数据计算。"; //"";
            rb.ID        = "RB_Way_1";
            if (mattr.HisAutoFull == AutoFullWay.Way1_JS)
            {
                rb.Checked = true;
            }
            this.Pub1.AddFieldSet(rb);
            this.Pub1.Add("比如:@单价*@数量");
            this.Pub1.AddBR();

            TextBox tb = new TextBox();

            tb.ID       = "TB_JS";
            tb.Width    = 450;
            tb.TextMode = TextBoxMode.MultiLine;
            tb.Rows     = 5;
            if (mattr.HisAutoFull == AutoFullWay.Way1_JS)
            {
                tb.Text = mattr.AutoFullDoc;
            }
            this.Pub1.Add(tb);
            this.Pub1.AddFieldSetEnd();
            this.Pub1.AddTDEnd();
            this.Pub1.AddTREnd();

            // 方式2 利用SQL自动填充
            this.Pub1.AddTR();
            this.Pub1.Add("<TD>");

            rb           = new RadioBtn();
            rb.GroupName = "s";
            rb.Text      = "方式2:利用SQL自动填充。";
            rb.ID        = "RB_Way_2";
            if (mattr.HisAutoFull == AutoFullWay.Way2_SQL)
            {
                rb.Checked = true;
            }

            this.Pub1.AddFieldSet(rb);
            this.Pub1.Add("比如:Select Addr From 商品表 WHERE No=@FK_Pro  FK_Pro是本表中的任意字段名<BR>");

            tb          = new TextBox();
            tb.ID       = "TB_SQL";
            tb.Width    = 450;
            tb.TextMode = TextBoxMode.MultiLine;
            tb.Rows     = 5;
            if (mattr.HisAutoFull == AutoFullWay.Way2_SQL)
            {
                tb.Text = mattr.AutoFullDoc;
            }

            this.Pub1.Add(tb);

            this.Pub1.AddFieldSetEnd();
            this.Pub1.AddTDEnd();
            this.Pub1.AddTREnd();

            // 方式3 本表单中外键列
            this.Pub1.AddTR();
            this.Pub1.Add("<TD>");
            rb           = new RadioBtn();
            rb.GroupName = "s";
            rb.Text      = "方式3:本表单中外键列。";
            // rb.Text = "方式3:本表单中外键列</font></b>";
            rb.ID = "RB_Way_3";
            if (mattr.HisAutoFull == AutoFullWay.Way3_FK)
            {
                rb.Checked = true;
            }

            this.Pub1.AddFieldSet(rb);
            this.Pub1.Add("比如:表单中有商品编号列,需要填充商品地址、供应商电话。");
            this.Pub1.AddBR();


            // 让它等于外键表的一个值。
            Attrs   attrs = null;
            MapData md    = new MapData();

            md.No = mattr.FK_MapData;
            if (md.RetrieveFromDBSources() == 0)
            {
                attrs = md.GenerHisMap().HisFKAttrs;
            }
            else
            {
                MapDtl mdtl = new MapDtl();
                mdtl.No = mattr.FK_MapData;
                attrs   = mdtl.GenerMap().HisFKAttrs;
            }

            if (attrs.Count > 0)
            {
            }
            else
            {
                rb.Enabled = false;
                if (rb.Checked)
                {
                    rb.Checked = false;
                }
                this.Pub1.Add("@本表没有外键字段。");
            }

            foreach (Attr attr in attrs)
            {
                if (attr.IsRefAttr)
                {
                    continue;
                }

                rb           = new RadioBtn();
                rb.Text      = attr.Desc;
                rb.ID        = "RB_FK_" + attr.Key;
                rb.GroupName = "sd";

                if (mattr.AutoFullDoc.Contains(attr.Key))
                {
                    rb.Checked = true;
                }

                this.Pub1.Add(rb);
                DDL ddl = new DDL();
                ddl.ID = "DDL_" + attr.Key;

                string sql = "";
                switch (BP.SystemConfig.AppCenterDBType)
                {
                case DBType.Oracle:
                case DBType.Informix:
                    continue;
                    sql = "Select fname as 'No' ,fDesc as 'Name' FROM Sys_FieldDesc WHERE tableName='" + attr.HisFKEn.EnMap.PhysicsTable + "'";
                    break;

                default:
                    sql = "Select name as 'No' ,Name as 'Name' from syscolumns WHERE ID=OBJECT_ID('" + attr.HisFKEn.EnMap.PhysicsTable + "')";
                    break;
                }

                //  string sql = "Select fname as 'No' ,fDesc as 'Name' FROM Sys_FieldDesc WHERE tableName='" + attr.HisFKEn.EnMap.PhysicsTable + "'";
                //string sql = "Select NO , NAME  FROM Port_Emp ";

                DataTable dt = DBAccess.RunSQLReturnTable(sql);
                foreach (DataRow dr in dt.Rows)
                {
                    //  ddl.Items.Add(new ListItem(this.ToE("Field") + dr[0].ToString() + " " + this.ToE("Desc") + " " + dr[1].ToString(), dr[0].ToString()));
                    ListItem li = new ListItem(dr[0].ToString() + ";" + dr[1].ToString(), dr[0].ToString());
                    if (mattr.AutoFullDoc.Contains(dr[0].ToString()))
                    {
                        li.Selected = true;
                    }

                    ddl.Items.Add(li);
                }

                this.Pub1.Add(ddl);
                this.Pub1.AddBR();
            }

            this.Pub1.AddFieldSetEnd();
            this.Pub1.AddTDEnd();
            this.Pub1.AddTREnd();

            // 方式3 本表单中外键列
            this.Pub1.AddTR();
            this.Pub1.Add("<TD>");
            rb           = new RadioBtn();
            rb.GroupName = "s";
            rb.Text      = "方式4:对一个从表的列求值。";
            rb.ID        = "RB_Way_4";
            if (mattr.HisAutoFull == AutoFullWay.Way4_Dtl)
            {
                rb.Checked = true;
            }

            this.Pub1.AddFieldSet(rb);
            this.Pub1.Add("比如:对从表中的列求值。");
            this.Pub1.AddBR();

            // 让它对一个从表求和、求平均、求最大、求最小值。
            MapDtls dtls = new MapDtls(mattr.FK_MapData);

            if (dtls.Count > 0)
            {
            }
            else
            {
                rb.Enabled = false;
                if (rb.Checked)
                {
                    rb.Checked = false;
                }
                // this.Pub1.Add("@没有从表。");
            }
            foreach (MapDtl dtl in dtls)
            {
                DDL ddlF = new DDL();
                ddlF.ID = "DDL_" + dtl.No + "_F";
                MapAttrs mattrs1 = new MapAttrs(dtl.No);
                int      count   = 0;
                foreach (MapAttr mattr1 in mattrs1)
                {
                    if (mattr1.LGType != FieldTypeS.Normal)
                    {
                        continue;
                    }

                    if (mattr1.KeyOfEn == MapAttrAttr.MyPK)
                    {
                        continue;
                    }

                    if (mattr1.IsNum == false)
                    {
                        continue;
                    }
                    switch (mattr1.KeyOfEn)
                    {
                    case "OID":
                    case "RefOID":
                    case "FID":
                        continue;

                    default:
                        break;
                    }
                    count++;
                    ListItem li = new ListItem(mattr1.Name, mattr1.KeyOfEn);
                    if (mattr.HisAutoFull == AutoFullWay.Way4_Dtl)
                    {
                        if (mattr.AutoFullDoc.Contains("=" + mattr1.KeyOfEn))
                        {
                            li.Selected = true;
                        }
                    }
                    ddlF.Items.Add(li);
                }
                if (count == 0)
                {
                    continue;
                }

                rb           = new RadioBtn();
                rb.Text      = dtl.Name;
                rb.ID        = "RB_" + dtl.No;
                rb.GroupName = "dtl";
                if (mattr.AutoFullDoc.Contains(dtl.No))
                {
                    rb.Checked = true;
                }

                this.Pub1.Add(rb);

                DDL ddl = new DDL();
                ddl.ID = "DDL_" + dtl.No + "_Way";
                ddl.Items.Add(new ListItem("求合计", "SUM"));
                ddl.Items.Add(new ListItem("求平均", "AVG"));
                ddl.Items.Add(new ListItem("求最大", "MAX"));
                ddl.Items.Add(new ListItem("求最小", "MIN"));
                this.Pub1.Add(ddl);

                if (mattr.HisAutoFull == AutoFullWay.Way4_Dtl)
                {
                    if (mattr.AutoFullDoc.Contains("SUM"))
                    {
                        ddl.SetSelectItem("SUM");
                    }
                    if (mattr.AutoFullDoc.Contains("AVG"))
                    {
                        ddl.SetSelectItem("AVG");
                    }
                    if (mattr.AutoFullDoc.Contains("MAX"))
                    {
                        ddl.SetSelectItem("MAX");
                    }
                    if (mattr.AutoFullDoc.Contains("MIN"))
                    {
                        ddl.SetSelectItem("MIN");
                    }
                }

                this.Pub1.Add(ddlF);
                this.Pub1.AddBR();
            }

            this.Pub1.AddFieldSetEnd();
            this.Pub1.AddTDEnd();
            this.Pub1.AddTREnd();


            #region 方式5
            //this.Pub1.AddTD();
            //this.Pub1.AddTR();

            //this.Pub1.AddFieldSet(rb);
            //this.Pub1.Add(this.ToE("Way2D", "嵌入的JS"));
            //tb = new TextBox();
            //tb.ID = "TB_JS";
            //tb.Width = 450;
            //tb.TextMode = TextBoxMode.MultiLine;
            //tb.Rows = 5;
            //if (mattr.HisAutoFull == AutoFullWay.Way5_JS)
            //    tb.Text = mattr.AutoFullDoc;
            //this.Pub1.Add(tb);
            //this.Pub1.AddFieldSetEnd();

            //this.Pub1.AddTDEnd();
            //this.Pub1.AddTREnd();
            #endregion 方式5



            this.Pub1.AddTRSum();
            this.Pub1.AddTDBegin("aligen=center");
            Button btn = new Button();
            btn.ID       = "Btn_Save";
            btn.CssClass = "Btn";
            btn.Text     = " 保存 ";
            btn.Click   += new EventHandler(btn_Click);
            this.Pub1.Add(btn);

            btn          = new Button();
            btn.ID       = "Btn_SaveAndClose";
            btn.CssClass = "Btn";
            btn.Text     = " 保存并关闭 ";
            btn.Click   += new EventHandler(btn_Click);
            this.Pub1.Add(btn);
            this.Pub1.AddTREnd();
            this.Pub1.AddTableEnd();
            return;
        }
Example #36
0
        void BindChannel()
        {
            string enumState = "";

            if (Int32.Parse(InfomationType) < 2)
            {
                enumState = "0" + InfomationType;
            }
            else
            {
                enumState = InfomationType;
            }

            //此处加载权限过滤栏目
            List <Channel> channelList = new List <Channel>();

            if (We7Helper.IsEmptyID(AccountID))
            {
                channelList = ChannelHelper.GetChannelsByType(enumState);
            }
            else
            {
                List <string> channelIds = AccountHelper.GetObjectsByPermission(AccountID, "Channel.Input");
                if (channelIds != null && channelIds.Count > 0)
                {
                    channelList = ChannelHelper.GetChannelByIDList(enumState, channelIds);
                }
            }
            List <Channel> removeList = new List <Channel>();

            foreach (Channel ch in channelList)
            {
                if (String.IsNullOrEmpty(ch.ModelName))
                {
                    continue;
                }
                if (String.Compare(ch.ModelName, "Article", true) == 0)
                {
                    continue;
                }
                if (String.Compare(ch.ModelName, "System.Article", true) == 0)
                {
                    continue;
                }
                removeList.Add(ch);
            }
            foreach (Channel ch in removeList)
            {
                channelList.Remove(ch);
            }

            if (channelList != null && channelList.Count > 0)
            {
                channelList.Sort();
                foreach (Channel ch in channelList)
                {
                    string   name  = ch.FullPath.Replace("//", "/").Replace("/", " 》");
                    string   value = ch.ID;
                    ListItem item  = new ListItem(name, value);
                    ChannelDropDownList.Items.Add(item);
                }
            }
        }
Example #37
0
        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, Resource.ProfileLink);

            litSecurityTab.Text     = "<a href='#tabSecurity'>" + Resource.UserProfileSecurityTab + "</a>";
            litProfileTab.Text      = "<a href='#" + tabProfile.ClientID + "'>" + Resource.UserProfileProfileTab + "</a>";
            litOrderHistoryTab.Text = "<a href='#" + tabOrderHistory.ClientID + "'>" + Resource.CommerceOrderHistoryTab + "</a>";
            litNewsletterTab.Text   = "<a href='#" + tabNewsletters.ClientID + "'>" + Resource.UserProfileNewslettersTab + "</a>";

            lnkAllowLiveMessenger.Text = Resource.EnableLiveMessengerLink;

            btnUpdate.Text = Resource.UserProfileUpdateButton;
            SiteUtils.SetButtonAccessKey(btnUpdate, AccessKeys.UserProfileSaveButtonAccessKey);

            if ((siteSettings.AllowUserEditorPreference) && (ddEditorProviders.Items.Count == 0))
            {
                ddEditorProviders.DataSource = EditorManager.Providers;
                ddEditorProviders.DataBind();
                foreach (ListItem providerItem in ddEditorProviders.Items)
                {
                    providerItem.Text = providerItem.Text.Replace("Provider", string.Empty);
                }

                ListItem listItem = new ListItem();
                listItem.Value = string.Empty;
                listItem.Text  = Resource.SiteDefaultEditor;
                ddEditorProviders.Items.Insert(0, listItem);
            }

            //if ((!allowGravatars)&&(!disableOldAvatars)&&(!Page.IsPostBack))
            //{
            //    ddAvatars.DataSource = SiteUtils.GetAvatarList(this.siteSettings);
            //    ddAvatars.DataBind();

            //    ddAvatars.Items.Insert(0, new ListItem(Resource.UserProfileNoAvatarLabel, "blank.gif"));
            //    ddAvatars.Attributes.Add("onChange", "javascript:showAvatar(this);");
            //    ddAvatars.Attributes.Add("size", "6");
            //}

            // lnkPublicProfile.DialogCloseText = Resource.DialogCloseLink;
            //lnkPublicProfile.Text = Resource.PublicProfileLink;

            lnkPubProfile.Text    = Resource.PublicProfileLink;
            lnkPubProfile.ToolTip = Resource.PublicProfileLink;

            rfvName.ErrorMessage    = Resource.UserProfileNameRequired;
            regexEmail.ErrorMessage = Resource.UserProfileEmailValidation;
            rfvEmail.ErrorMessage   = Resource.UserProfileEmailRequired;

            QuestionRequired.ErrorMessage = Resource.RegisterSecurityQuestionRequiredMessage;
            AnswerRequired.ErrorMessage   = Resource.RegisterSecurityAnswerRequiredMessage;
            //regexAvatarFile.ErrorMessage = Resource.FileTypeNotAllowed;
            //regexAvatarFile.ValidationExpression = SecurityHelper.GetRegexValidationForAllowedExtensions(SiteUtils.ImageFileExtensions());

            //lnkAvatarUpload.Text = Resource.UploadAvatarLink;
            lnkAvatarUpld.Text    = Resource.UploadAvatarLink;
            lnkAvatarUpld.ToolTip = Resource.UploadAvatarLink;


            btnUpdateAvartar.ImageUrl = Page.ResolveUrl("~/Data/SiteImages/1x1.gif");
            btnUpdateAvartar.Attributes.Add("tabIndex", "-1");


            if (allowGravatars)
            {
                //gravatar1.Visible = true;
                //ddAvatars.Visible = false;
                //imgAvatar.Visible = false;
                avatarHelp.Visible = false;
                //lnkAvatarUpload.Visible = false;
                lnkAvatarUpld.Visible = false;
            }
            else
            {
                //gravatar1.Visible = false;

                if (disableAvatars)
                {
                    divAvatar.Visible = false;
                    //imgAvatar.Visible = false;
                    avatarHelp.Visible = false;
                    //lnkAvatarUpload.Visible = false;
                    lnkAvatarUpld.Visible = false;
                }
                else
                {
                    //lblMaxAvatarSize.Text = string.Format(Resource.AvatarMaxSizeLabelFormat, WebConfigSettings.AvatarMaxWidth.ToInvariantString(), WebConfigSettings.AvatarMaxHeight.ToInvariantString());
                    //imgAvatar.Visible = true;

                    if (!WebConfigSettings.AvatarsCanOnlyBeUploadedByAdmin)
                    {
                        avatarHelp.Visible = true;
                    }
                }
            }

            lnkOpenIDUpdate.Text        = Resource.OpenIDUpdateButton;
            lnkOpenIDUpdate.ToolTip     = Resource.OpenIDUpdateButton;
            lnkOpenIDUpdate.NavigateUrl = SiteRoot + "/Secure/UpdateOpenID.aspx";

            rpxLink.OverrideText = Resource.OpenIDUpdateButton;

            pnlSecurityQuestion.Visible = siteSettings.RequiresQuestionAndAnswer;
        }
Example #38
0
        /// <summary>Flush hanging leaves.</summary>
        /// <param name="container">a container element</param>
        public virtual void FlushHangingLeaves(IPropertyContainer container)
        {
            Paragraph p = CreateLeavesContainer();

            if (p != null)
            {
                IDictionary <String, String> map = new Dictionary <String, String>();
                map.Put(CssConstants.OVERFLOW, CommonCssConstants.VISIBLE);
                OverflowApplierUtil.ApplyOverflow(map, p);
                if (container is Document)
                {
                    ((Document)container).Add(p);
                }
                else
                {
                    if (container is Paragraph)
                    {
                        foreach (IElement leafElement in waitingLeaves)
                        {
                            if (leafElement is ILeafElement)
                            {
                                ((Paragraph)container).Add((ILeafElement)leafElement);
                            }
                            else
                            {
                                if (leafElement is IBlockElement)
                                {
                                    ((Paragraph)container).Add((IBlockElement)leafElement);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (container is Div)
                        {
                            ((Div)container).Add(p);
                        }
                        else
                        {
                            if (container is Cell)
                            {
                                ((Cell)container).Add(p);
                            }
                            else
                            {
                                if (container is List)
                                {
                                    ListItem li = new ListItem();
                                    li.Add(p);
                                    ((List)container).Add(li);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Unable to process hanging inline content");
                                }
                            }
                        }
                    }
                }
                waitingLeaves.Clear();
            }
        }
Example #39
0
        private bool getNewRandomJob()
        {
            double price   = 0;
            bool   success = Double.TryParse(Hidden_Price.Value, out price);

            if (!success)
            {
                price = 0;
            }
            SatyamTaskTableAccess taskTableDB = new SatyamTaskTableAccess();
            SatyamTaskTableEntry  entry       = null;

            if (Submit_Button.Enabled == true)
            {
                //entry = taskTableDB.getMinimumTriedNewEntryForWorkerIDByTemplateAndPrice(Hidden_AmazonWorkerID.Value,
                //    TaskConstants.TrackletLabeling_MTurk, price);
                entry = taskTableDB.getTopKNewEntryForWorkerIDByTemplateAndPrice(50, Hidden_AmazonWorkerID.Value,
                                                                                 TaskConstants.TrackletLabeling_MTurk, price);
            }
            else
            {
                entry = taskTableDB.getMinimumTriedEntryByTemplate(TaskConstants.TrackletLabeling_MTurk);
            }

            taskTableDB.close();


            if (entry == null)
            {
                return(false);
            }
            taskTableDB = new SatyamTaskTableAccess();
            taskTableDB.IncrementDoneScore(entry.ID);
            taskTableDB.close();

            SatyamTask task = JSonUtils.ConvertJSonToObject <SatyamTask>(entry.TaskParametersString);

            SatyamJobStorageAccountAccess satyamStorage = new SatyamJobStorageAccountAccess();

            string        videoDir  = URIUtilities.localDirectoryFullPathFromURI(task.SatyamURI);
            List <string> ImageURLs = satyamStorage.getURLListOfSpecificExtensionUnderSubDirectoryByURI(videoDir, new List <string>()
            {
                "jpg"
            });

            string annotationFilePath = task.SatyamURI;

            //string urls = "";
            //for (int i=0;i<ImageURLs.Count;i++)
            //{
            //    urls += ImageURLs[i];
            //    if (i == ImageURLs.Count - 1) break;
            //    urls += ',';
            //}
            Hidden_ImageURLList.Value = ObjectsToStrings.ListString(ImageURLs, ',');

            SatyamJob jobDefinitionEntry        = task.jobEntry;
            MultiObjectTrackingSubmittedJob job = JSonUtils.ConvertJSonToObject <MultiObjectTrackingSubmittedJob>(jobDefinitionEntry.JobParameters);

            Dictionary <string, List <string> > subcategories = job.Categories;
            List <string> categories = subcategories.Keys.ToList();

            //CategorySelection_RakdioButtonList.Items.Clear();
            for (int i = 0; i < categories.Count; i++)
            {
                ListItem l = new ListItem(categories[i]);
                //CategorySelection_RadioButtonList.Items.Add(l);
            }

            if (job.Description != "")
            {
                //DescriptionPanel.Visible = true;
                //DescriptionTextPanel.Controls.Add(new LiteralControl(job.Description));
            }
            //Hidden_BoundaryLines.Value = JSonUtils.ConvertObjectToJSon(job.BoundaryLines);


            Hidden_TaskEntryString.Value = JSonUtils.ConvertObjectToJSon <SatyamTaskTableEntry>(entry);
            Hidden_PageLoadTime.Value    = DateTime.Now.ToString();


            // pass parameters from old template
            Slug_Hidden.Value          = "null";
            Start_Hidden.Value         = "0";
            Stop_Hidden.Value          = (ImageURLs.Count - 1).ToString();
            Skip_Hidden.Value          = "0";
            PerObject_Hidden.Value     = "0.1";
            Completion_Hidden.Value    = "0.5";
            BlowRadius_Hidden.Value    = "0";
            JobId_Hidden.Value         = "1";
            LabelString_Hidden.Value   = ObjectsToStrings.ListString(categories.ToList(), ',');
            Attributes_Hidden.Value    = ObjectsToStrings.DictionaryStringListString(subcategories, ',', ':', '_');
            Training_Hidden.Value      = "0";
            fps_Hidden.Value           = job.FrameRate.ToString();
            Hidden_ChunkDuration.Value = job.ChunkDuration.ToString();

            var web = new WebClient();

            System.Drawing.Image x = System.Drawing.Image.FromStream(web.OpenRead(ImageURLs[0]));
            ImageWidth_Hidden.Value  = x.Width.ToString();
            ImageHeight_Hidden.Value = x.Height.ToString();

            // image boundary for now
            //string[] region = new string[] { "0-0-1242-0-1242-375-0-375-0-0" };
            string[] region = new string[] { "0-0-" + x.Width + "-0-" + x.Width + "-" + x.Height + "-0-" + x.Height + "-0-0" };
            RegionString_Hidden.Value = ObjectsToStrings.ListString(region, ',');

            // temp test
            List <VATIC_Tracklet> prevTracesTemp = new List <VATIC_Tracklet>();

            WebClient     client = new WebClient();
            Stream        stream = client.OpenRead(annotationFilePath);
            StreamReader  reader = new StreamReader(stream);
            List <string> trace  = new List <string>();

            while (reader.Peek() >= 0)
            {
                string content = reader.ReadLine();
                trace.Add(content);
            }


            Dictionary <string, VATIC_Tracklet> tracklets = VATIC_Tracklet.ReadTrackletsFromVIRAT(trace);

            foreach (string id in tracklets.Keys)
            {
                //string output = JSonUtils.ConvertObjectToJSon(tracklets[id]);
                prevTracesTemp.Add(tracklets[id]);
            }
            string output = JSonUtils.ConvertObjectToJSon(prevTracesTemp);

            PreviousTrackString_Hidden.Value = output;

            return(true);
        }
Example #40
0
        // Publish results from selected query to SharePoint Online
        private void publishToSharepoint()
        {
            // Perform search
            string    XMLOutput = this.EARepository.SQLQuery(tbQuery.Text);
            XDocument XMLDoc    = XDocument.Parse(XMLOutput);

            // Check whether the query returns any results
            if (XMLDoc.Root.Element("Dataset_0").Element("Data").HasElements)
            {
                // Update progress information
                statusStrip.Invoke((Action) delegate { lblStatus.Text = "Publishing ..."; });
                statusStrip.Invoke((Action) delegate { progressBar.Value = 10; });

                // Connect to SharePoint Online
                using (ClientContext clientContext = new ClientContext(new Uri(tbSharepointSite.Text)))
                {
                    try
                    {
                        // Connect to SharePoint (Office365)
                        clientContext.Credentials = this.sharepointCredentials;
                        Web web = clientContext.Web;

                        // Open list
                        string          selectedList    = (string)cbLists.Items[cbLists.SelectedIndex];
                        List            list            = web.Lists.GetByTitle(selectedList);
                        FieldCollection fieldCollection = list.Fields;
                        clientContext.Load(fieldCollection);
                        clientContext.ExecuteQuery();

                        // Retrieve and store list column information
                        Dictionary <string, string> Fields = new Dictionary <string, string>();
                        foreach (Field tmpField in fieldCollection)
                        {
                            if (!Fields.ContainsKey(tmpField.Title))
                            {
                                Fields[tmpField.Title] = tmpField.InternalName;
                            }
                        }

                        // Purge (empty) list if this option has been selected
                        if (cbPurgeList.Checked)
                        {
                            // Get all list items
                            ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
                            clientContext.Load(listItems, eachItem => eachItem.Include(item => item, item => item["ID"]));
                            clientContext.ExecuteQuery();

                            // Delete all list items
                            var totalListItems = listItems.Count;
                            if (totalListItems > 0)
                            {
                                for (var counter = totalListItems - 1; counter > -1; counter--)
                                {
                                    listItems[counter].DeleteObject();
                                }

                                // Execute query
                                clientContext.ExecuteQuery();
                            }
                        }

                        // Loop through query results
                        foreach (XElement Node in XMLDoc.Root.Element("Dataset_0").Element("Data").Elements())
                        {
                            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                            ListItem newItem = list.AddItem(itemCreateInfo);

                            foreach (XElement Field in Node.Elements())
                            {
                                if (Fields.ContainsKey(Field.Name.LocalName))
                                {
                                    string tmpInternalName = Fields[Field.Name.LocalName];
                                    newItem[tmpInternalName] = Field.Value;
                                }

                                // Save item
                                newItem.Update();

                                // Update progressbar
                                statusStrip.Invoke((Action) delegate { progressBar.Value += 1; });
                            }
                        }

                        // Execute query
                        clientContext.ExecuteQuery();
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show("An error has occured: " +
                                        System.Environment.NewLine + System.Environment.NewLine + exception.Message);
                    }
                }
            }

            // Update progress information
            statusStrip.Invoke((Action) delegate { lblStatus.Text = "Done"; });
            statusStrip.Invoke((Action) delegate { progressBar.Value = 100; });
        }
Example #41
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!CurrUser.userRole.CompanySetup)
                {
                    Response.Redirect("../Unauthorize.aspx");
                    Response.End();
                }

                this.imgUserPic.Attributes.Add("onload", string.Format("resizeImage('{0}')", this.imgUserPic.ClientID));
                // get UserId from query string
                int nUserId = -1;
                if (!int.TryParse(Request.QueryString["uid"], out nUserId))
                {
                    nUserId = -1;
                }
                if (-1 == nUserId)
                {
                    UserId = null;
                }
                else
                {
                    UserId = nUserId;
                }

                BLL.Company_General   comGeneral = new BLL.Company_General();
                Model.Company_General company    = comGeneral.GetModel();
                if (null != company)
                {
                    this.lbPrefix.Text = company.AD_OU_Filter;
                }

                // bind User Loan Rep gridview
                BindLoanRep();

                // bind Group gridview
                BindGroup();

                // bind Role dropdown list
                BLL.Roles RolesManager = new BLL.Roles();
                DataSet   dsRoles      = RolesManager.GetList(string.Empty);
                this.ddlRole.DataSource     = dsRoles;
                this.ddlRole.DataValueField = "RoleId";
                this.ddlRole.DataTextField  = "Name";
                this.ddlRole.DataBind();
                this.ddlRole.Items.Insert(0, new ListItem("Please Select", ""));
                Mode = Request.QueryString["mode"];
                if ("0" == Mode)
                {
                    this.btnDelete.Enabled = false;
                    this.btnClone.Enabled  = false;
                }
                if ("1" == Mode)
                {
                    // Load user info
                    if (!UserId.HasValue)
                    {
                        // if no UserId,thorw exception
                        LPLog.LogMessage(LogType.Logerror, "Invalid UserId");
                        throw new Exception("Invalid UserId");
                    }
                    else
                    {
                        Model.Users user = UsersManager.GetModel(UserId.Value);
                        if (null == user)
                        {
                            LPLog.LogMessage(LogType.Logerror, string.Format("Cannot find the user with UserId = {0}", UserId.Value));
                        }
                        else
                        {
                            this.ckbEnabled.Checked = user.UserEnabled;
                            this.tbUserName.Text    = user.Username;
                            this.tbEmail.Text       = user.EmailAddress;
                            this.tbFirstName.Text   = user.FirstName;
                            this.tbLastName.Text    = user.LastName;
                            ListItem item = this.ddlRole.Items.FindByValue(user.RoleId.ToString());
                            if (null != item)
                            {
                                this.ddlRole.ClearSelection();
                                item.Selected = true;
                            }
                            this.hiUserLoanCount.Value    = LoanTeamManager.GetUserLoanCount(UserId.Value).ToString();
                            this.hiUserContactCount.Value = ContactUsersManager.GetUserContactCount(UserId.Value).ToString();

                            //gdc 20110606 Add
                            this.txbPhone.Text = user.Phone;
                            this.txbFax.Text   = user.Fax;
                            this.txbCell.Text  = user.Cell;

                            this.txbBranchManagerCompensation.Text   = user.BranchMgrComp.ToString("00.000");
                            this.txbDivisionManagerCompensation.Text = user.DivisionMgrComp.ToString("00.000");
                            this.txbLoanOfficerCompenstation.Text    = user.LOComp.ToString("00.000");
                            this.txbRegionalManagerCompensation.Text = user.RegionMgrComp.ToString("00.000");

                            //ExchangePassword
                            this.txbExchangePassword.Text = user.ExchangePassword;
                            this.txbExchangePassword.Attributes.Add("value", user.ExchangePassword);
                        }
                    }
                }

                if (UserId.HasValue && Mode == "1")
                {
                    this.tbUserName.Enabled   = false;
                    this.tbUserName.BackColor = System.Drawing.Color.LightGray;
                }
                else
                {
                    this.tbUserName.Enabled   = true;
                    this.tbUserName.BackColor = System.Drawing.Color.Transparent;
                }
            }
        }
Example #42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userid = BasePage.GetRequestId(Cookies.GetCookie("User_Id").ToString());
        if (!Page.IsPostBack)
        {
            ((Literal)Master.FindControl("breadcrumbs")).Text = "<a href=\"AdminAdd.aspx\" class=\"home\">添加管理员</a>";
            string checklogin = new AdminBll().CheckLogin("no");
            if (checklogin != "true")
            {
                BasePage.Alertback(checklogin);
                Response.End();
            }
            txtadmin1.Visible = false;//模型权限勾选,只允许两个用户可设置
            txtadmin.Visible = false;
            if (userid == 1)
            {
                txtadmin.Visible = true;//设置其它管理员默认权限
                txtadmin1.Visible = true;
            }
            else if (userid == 2)
            {
                txtadmin1.Visible = true;
            }
            int id = BasePage.GetRequestId(Request.QueryString["id"]);

            ActionName.Text = "添加网站管理员";
            //动态模型,其它管理员不显示这个
            if (userid == 1)
            {
                DataSet ds = new DataSet();
                ds = new CommonBll().GetList("", "GL_Model", "ModelLock=0", "id asc");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ListItem ListItem1 = new ListItem(dr["ModelName"].ToString() + "内容管理", "m" + dr["id"].ToString());
                        string[] a = dr["ModeContent"].ToString().Split('`');
                        if (a[5] == "1")//需要审核时显示
                        {
                            ListItem ListItem2 = new ListItem(dr["ModelName"].ToString() + "发表审核", "ms" + dr["id"].ToString());
                            txtModelPower.Items.Add(ListItem2);
                        }
                        ListItem ListItem3 = new ListItem(dr["ModelName"].ToString() + "内容删除", "md" + dr["id"].ToString());
                        ListItem ListItem4 = new ListItem(dr["ModelName"].ToString() + "栏目添加", "ca" + dr["id"].ToString());
                        ListItem ListItem5 = new ListItem(dr["ModelName"].ToString() + "栏目编辑", "ce" + dr["id"].ToString());
                        ListItem ListItem6 = new ListItem(dr["ModelName"].ToString() + "栏目删除", "cd" + dr["id"].ToString());
                        ListItem ListItem7 = new ListItem(dr["ModelName"].ToString() + "字段管理", "z" + dr["id"].ToString());
                        txtModelPower.Items.Add(ListItem1);
                        txtModelPower.Items.Add(ListItem3);
                        txtModelPower.Items.Add(ListItem4);
                        txtModelPower.Items.Add(ListItem5);
                        txtModelPower.Items.Add(ListItem6);
                        txtModelPower.Items.Add(ListItem7);
                    }
                }
            }

            if (id != 0)//编辑
            {
                if (userid == 2)//二管理员
                {
                    string adminpur = new CommonBll().GetTitle("GL_Webconfig", "adminpur", 1);
                    if (!String.IsNullOrEmpty(adminpur))
                    {
                        string[] ap = adminpur.Split('|');
                        for (int i = 0; i < ap.Length; i++)
                        {
                            string[] ap2 = ap[i].Split(',');
                            ListItem ListItem1 = new ListItem(ap2[0], ap2[1]);
                            txtModelPower2.Items.Add(ListItem1);
                        }
                    }
                }


                AdminModel model = new AdminBll().GetModel(id);
                txtUserName.Text = model.UserName;
                txtEmail.Text = model.Email;
                txtPassWordOld.Value = model.PassWord;
                txtTTelPhone.Text = model.TelPhone;
                if (model.Sex == 0)
                {
                    TxtSex.Checked = true;
                }
                else
                {
                    TxtSex1.Checked = true;
                }
                if (model.Locked == 1)
                {
                    txtLocked.Checked = true;
                }
                if (Request.QueryString["id"] == "1")
                {
                    txtLocked.Enabled = false;//管理员时锁定
                }
                if (userid == 1)
                {
                    SetChecked(this.txtModelPower, model.ModelPower, ",");
                }
                else if (userid == 2)
                {
                    SetChecked(this.txtModelPower2, model.ModelPower, ",");
                }
                Literal1.Text = " 不修改密码请留空!";
                ActionName.Text = "修改" + txtUserName.Text + "资料";

                string other = "";
                other += "<tr><td class=\"align-right\">添加时间:</td><td class=\"align-left\">" +BasePage.formatDateTime(model.AddDate.ToString()) + "</td></tr>";
                other += "<tr><td class=\"align-right\">登录次数:</td><td class=\"align-left\">" + model.LoginTime + "</td></tr>";
                other += "<tr><td class=\"align-right\">最后登录:</td><td class=\"align-left\">" + BasePage.formatDateTime(model.LastLoginTime.ToString()) + "</td></tr>";
                other += "<tr><td class=\"align-right\">最后登录IP:</td><td class=\"align-left\">" + model.LastLoginIP + "</td></tr>";
                Literal2.Text = other;
                Button1.Text = "确认修改";
                HiddenFieldmp.Value = model.ModelPower;
            }
        }
    }
Example #43
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.Lists.Any())
                {
                    var rootWeb = (web.Context as ClientContext).Site.RootWeb;

                    web.EnsureProperties(w => w.ServerRelativeUrl);

                    web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                    web.Context.ExecuteQueryRetry();
                    var existingLists     = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                    var serverRelativeUrl = web.ServerRelativeUrl;

                    #region DataRows

                    foreach (var listInstance in template.Lists)
                    {
                        if (listInstance.DataRows != null && listInstance.DataRows.Any())
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title);
                            // Retrieve the target list
                            var list = web.Lists.GetByTitle(parser.ParseString(listInstance.Title));
                            web.Context.Load(list);

                            // Retrieve the fields' types from the list
                            Microsoft.SharePoint.Client.FieldCollection fields = list.Fields;
                            web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.TypeAsString));
                            web.Context.ExecuteQueryRetry();

                            var keyColumnType   = "Text";
                            var parsedKeyColumn = parser.ParseString(listInstance.DataRows.KeyColumn);
                            if (!string.IsNullOrEmpty(parsedKeyColumn))
                            {
                                var keyColumn = fields.FirstOrDefault(f => f.InternalName.Equals(parsedKeyColumn, StringComparison.InvariantCultureIgnoreCase));
                                if (keyColumn != null)
                                {
                                    switch (keyColumn.FieldTypeKind)
                                    {
                                    case FieldType.User:
                                    case FieldType.Lookup:
                                        keyColumnType = "Lookup";
                                        break;

                                    case FieldType.URL:
                                        keyColumnType = "Url";
                                        break;

                                    case FieldType.DateTime:
                                        keyColumnType = "DateTime";
                                        break;

                                    case FieldType.Number:
                                    case FieldType.Counter:
                                        keyColumnType = "Number";
                                        break;
                                    }
                                }
                            }

                            foreach (var dataRow in listInstance.DataRows)
                            {
                                try
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1);


                                    bool     create   = true;
                                    ListItem listitem = null;
                                    if (!string.IsNullOrEmpty(listInstance.DataRows.KeyColumn))
                                    {
                                        // if it is empty, skip the check
                                        if (!string.IsNullOrEmpty(dataRow.Key))
                                        {
                                            var query     = $@"<View><Query><Where><Eq><FieldRef Name=""{parsedKeyColumn}""/><Value Type=""{keyColumnType}"">{parser.ParseString(dataRow.Key)}</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>";
                                            var camlQuery = new CamlQuery()
                                            {
                                                ViewXml = query
                                            };
                                            var existingItems = list.GetItems(camlQuery);
                                            list.Context.Load(existingItems);
                                            list.Context.ExecuteQueryRetry();
                                            if (existingItems.Count > 0)
                                            {
                                                if (listInstance.DataRows.UpdateBehavior == UpdateBehavior.Skip)
                                                {
                                                    create = false;
                                                }
                                                else
                                                {
                                                    listitem = existingItems[0];
                                                    create   = true;
                                                }
                                            }
                                        }
                                    }

                                    if (create)
                                    {
                                        if (listitem == null)
                                        {
                                            var listitemCI = new ListItemCreationInformation();
                                            listitem = list.AddItem(listitemCI);
                                        }

                                        foreach (var dataValue in dataRow.Values)
                                        {
                                            Field dataField = fields.FirstOrDefault(
                                                f => f.InternalName == parser.ParseString(dataValue.Key));

                                            if (dataField != null)
                                            {
                                                String fieldValue = parser.ParseString(dataValue.Value);

                                                switch (dataField.FieldTypeKind)
                                                {
                                                case FieldType.Geolocation:
                                                    // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                                    var geolocationArray = fieldValue.Split(',');
                                                    if (geolocationArray.Length == 4)
                                                    {
                                                        var geolocationValue = new FieldGeolocationValue
                                                        {
                                                            Altitude  = Double.Parse(geolocationArray[0]),
                                                            Latitude  = Double.Parse(geolocationArray[1]),
                                                            Longitude = Double.Parse(geolocationArray[2]),
                                                            Measure   = Double.Parse(geolocationArray[3]),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = geolocationValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;

                                                case FieldType.Lookup:
                                                    // FieldLookupValue - Expected format: LookupID or LookupID,LookupID,LookupID...
                                                    if (fieldValue.Contains(","))
                                                    {
                                                        var lookupValues = new List <FieldLookupValue>();
                                                        fieldValue.Split(',').All(value =>
                                                        {
                                                            lookupValues.Add(new FieldLookupValue
                                                            {
                                                                LookupId = int.Parse(value),
                                                            });
                                                            return(true);
                                                        });
                                                        listitem[parser.ParseString(dataValue.Key)] = lookupValues.ToArray();
                                                    }
                                                    else
                                                    {
                                                        var lookupValue = new FieldLookupValue
                                                        {
                                                            LookupId = int.Parse(fieldValue),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = lookupValue;
                                                    }
                                                    break;

                                                case FieldType.URL:
                                                    // FieldUrlValue - Expected format: URL,Description
                                                    var urlArray  = fieldValue.Split(',');
                                                    var linkValue = new FieldUrlValue();
                                                    if (urlArray.Length == 2)
                                                    {
                                                        linkValue.Url         = urlArray[0];
                                                        linkValue.Description = urlArray[1];
                                                    }
                                                    else
                                                    {
                                                        linkValue.Url         = urlArray[0];
                                                        linkValue.Description = urlArray[0];
                                                    }
                                                    listitem[parser.ParseString(dataValue.Key)] = linkValue;
                                                    break;

                                                case FieldType.User:
                                                    // FieldUserValue - Expected format: loginName or loginName,loginName,loginName...
                                                    if (fieldValue.Contains(","))
                                                    {
                                                        var userValues = new List <FieldUserValue>();
                                                        fieldValue.Split(',').All(value =>
                                                        {
                                                            var user = web.EnsureUser(value);
                                                            web.Context.Load(user);
                                                            web.Context.ExecuteQueryRetry();
                                                            if (user != null)
                                                            {
                                                                userValues.Add(new FieldUserValue
                                                                {
                                                                    LookupId = user.Id,
                                                                });;
                                                            }
                                                            return(true);
                                                        });
                                                        listitem[parser.ParseString(dataValue.Key)] = userValues.ToArray();
                                                    }
                                                    else
                                                    {
                                                        var user = web.EnsureUser(fieldValue);
                                                        web.Context.Load(user);
                                                        web.Context.ExecuteQueryRetry();
                                                        if (user != null)
                                                        {
                                                            var userValue = new FieldUserValue
                                                            {
                                                                LookupId = user.Id,
                                                            };
                                                            listitem[parser.ParseString(dataValue.Key)] = userValue;
                                                        }
                                                        else
                                                        {
                                                            listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                        }
                                                    }
                                                    break;

                                                case FieldType.DateTime:
                                                    var dateTime = DateTime.MinValue;
                                                    if (DateTime.TryParse(fieldValue, out dateTime))
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = dateTime;
                                                    }
                                                    break;

                                                default:
                                                    listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    break;
                                                }
                                            }
                                        }
                                        listitem.Update();
                                        web.Context.ExecuteQueryRetry(); // TODO: Run in batches?

                                        if (dataRow.Security != null && (dataRow.Security.ClearSubscopes == true || dataRow.Security.CopyRoleAssignments == true || dataRow.Security.RoleAssignments.Count > 0))
                                        {
                                            listitem.SetSecurity(parser, dataRow.Security);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex.GetType().Equals(typeof(ServerException)) &&
                                        (ex as ServerException).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPDuplicateValuesFoundException", StringComparison.InvariantCultureIgnoreCase) &&
                                        applyingInformation.IgnoreDuplicateDataRowErrors)
                                    {
                                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_duplicate);
                                        continue;
                                    }
                                    else
                                    {
                                        scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace);
                                        throw;
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                }
            }

            return(parser);
        }
Example #44
0
        protected virtual string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var result  = string.Empty;
            var context = listItemModelHost.HostListItem.Context;

            if (!string.IsNullOrEmpty(webPartModel.WebpartFileName))
            {
                lock (_wpCacheLock)
                {
                    var wpKey = webPartModel.WebpartFileName.ToLower();

                    if (_wpCache.ContainsKey(wpKey))
                    {
                        result = _wpCache[wpKey];
                    }
                    else
                    {
                        var rootWeb        = listItemModelHost.HostSite.RootWeb;
                        var rootWebContext = rootWeb.Context;

                        var webPartCatalog =
                            rootWeb.QueryAndGetListByUrl(BuiltInListDefinitions.Calalogs.Wp.GetListUrl());
                        //var webParts = webPartCatalog.GetItems(CamlQuery.CreateAllItemsQuery());

                        //rootWebContext.Load(webParts);
                        //rootWebcontext.ExecuteQueryWithTrace();

                        ListItem targetWebPart = SearchItemByName(webPartCatalog, webPartCatalog.RootFolder,
                                                                  webPartModel.WebpartFileName);

                        //foreach (var webPart in webParts)
                        //    if (webPart["FileLeafRef"].ToString().ToUpper() == webPartModel.WebpartFileName.ToUpper())
                        //        targetWebPart = webPart;

                        if (targetWebPart == null)
                        {
                            throw new SPMeta2Exception(string.Format("Cannot find web part file by name:[{0}]",
                                                                     webPartModel.WebpartFileName));
                        }

                        var webPartFile = targetWebPart.File;

                        rootWebContext.Load(webPartFile);
                        rootWebContext.ExecuteQueryWithTrace();


                        // does not work for apps - https://github.com/SubPointSolutions/spmeta2/issues/174
                        //var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(listItemModelHost.HostclientContext, webPartFile.ServerRelativeUrl);

                        //using (var reader = new StreamReader(fileInfo.Stream))
                        //{
                        //    webPartXML = reader.ReadToEnd();
                        //}

                        var data = webPartFile.OpenBinaryStream();

                        context.Load(webPartFile);
                        context.ExecuteQueryWithTrace();

                        using (var reader = new StreamReader(data.Value))
                        {
                            result = reader.ReadToEnd();
                        }

                        if (!_wpCache.ContainsKey(wpKey))
                        {
                            _wpCache.Add(wpKey, result);
                        }
                        else
                        {
                            _wpCache[wpKey] = result;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(webPartModel.WebpartType))
            {
                throw new Exception("WebpartType is not supported yet.");
            }

            if (!string.IsNullOrEmpty(webPartModel.WebpartXmlTemplate))
            {
                result = webPartModel.WebpartXmlTemplate;
            }

            return(result);
        }
Example #45
0
        private void PopulateAddress()
		{
            if (_address != null)
            {
                _hasChanged = false;
                chkUserSaved.Checked = _address.UserSaved;
                chkPrimary.Checked = _address.PrimaryAddress;
                txtDescription.Text = _address.Description;
                txtFirstName.Text = _address.FirstName;
                txtLastName.Text = _address.LastName;
                txtStreet.Text = _address.Address1;
                txtUnit.Text = _address.Address2;
                txtPostal.Text = _address.PostalCode;
                txtCity.Text = _address.City;
                txtEmail.Text = _address.Email;
                txtTelephone.Text = _address.Phone1;
                txtCell.Text = _address.Phone2;
                if (UserController.Instance.GetCurrentUserInfo().UserID != _address.UserID)
                {
                    chkUserSaved.Checked = false;
                    ShowDescription = false;
                    chkPrimary.Checked = false;
                    txtDescription.Text = "";
                }

                cboCountry.ClearSelection();
                if (string.IsNullOrEmpty(_address.CountryCode))
                    cboCountry.SelectedIndex = 0;
                else
                {
                    ListItem country = null;
                    if (_settings.CountryData.ToLower() == "text")
                        country = cboCountry.Items.FindByText(_address.CountryCode);
                    else if (_settings.CountryData.ToLower() == "value")
                        country = cboCountry.Items.FindByValue(_address.CountryCode);
                    if (country != null)
                        country.Selected = true;
                }

                Localize();

                if (cboRegion.Items.Count > 0)
                {
                    cboRegion.ClearSelection();
                    if (string.IsNullOrEmpty(_address.RegionCode))
                        cboRegion.SelectedIndex = 0;
                    else
                    {
                        ListItem region = null;
                        if (_settings.RegionData.ToLower() == "text")
                            region = cboRegion.Items.FindByText(_address.RegionCode);
                        else if (_settings.RegionData.ToLower() == "value")
                            region = cboRegion.Items.FindByValue(_address.RegionCode);
                        if (region != null)
                            region.Selected = true;
                    }
                }
                else
                    txtRegion.Text = _address.RegionCode;
            }
            else
            {
                cboCountry.ClearSelection();
                Localize();
            }
        }
Example #46
0
        private PlaceHolder DetermineConfigEditControl(string StoreName, int StoreId, AppConfig config)
        {
            PlaceHolder plhConfigValueEditor = new PlaceHolder();
            String      editorId;
            Boolean     isnew = (config == null);

            if (isnew)
            {
                //return AddParameterControl(StoreName, StoreId, config);
                config   = AppLogic.GetAppConfigRouted(this.Datasource.Name, StoreId);
                editorId = string.Format("ctrlNewConfig{0}_{1}", StoreId, this.Datasource.AppConfigID);
                plhConfigValueEditor.Controls.Add(new LiteralControl("<small style=\"color:gray;\">(Unassigned for <em>{0}</em>. Currently using default.)</small><br />".FormatWith(Store.GetStoreName(StoreId))));
            }
            else
            {
                editorId = string.Format("ctrlConfigEditor{0}", config.AppConfigID);
            }


            if (config.ValueType.EqualsIgnoreCase("integer"))
            {
                TextBox txt = new TextBox();
                txt.ID        = editorId;
                txt.Text      = config.ConfigValue;
                m_configvalue = txt.Text;

                CompareValidator compInt = new CompareValidator();
                compInt.Type              = ValidationDataType.Integer;
                compInt.Operator          = ValidationCompareOperator.DataTypeCheck;
                compInt.ControlToValidate = txt.ID;
                compInt.ErrorMessage      = AppLogic.GetString("admin.editquantitydiscounttable.EnterInteger", ThisCustomer.LocaleSetting);

                plhConfigValueEditor.Controls.Add(txt);
                plhConfigValueEditor.Controls.Add(compInt);
            }
            else if (config.ValueType.EqualsIgnoreCase("decimal") || config.ValueType.EqualsIgnoreCase("double"))
            {
                TextBox txt = new TextBox();
                txt.ID        = editorId;
                txt.Text      = config.ConfigValue;
                m_configvalue = txt.Text;

                FilteredTextBoxExtender extFilterNumeric = new FilteredTextBoxExtender();
                extFilterNumeric.ID = DB.GetNewGUID();
                extFilterNumeric.TargetControlID = editorId;
                extFilterNumeric.FilterType      = FilterTypes.Numbers | FilterTypes.Custom;
                extFilterNumeric.ValidChars      = ".";

                plhConfigValueEditor.Controls.Add(txt);
                plhConfigValueEditor.Controls.Add(extFilterNumeric);
            }
            else if (config.ValueType.EqualsIgnoreCase("boolean"))
            {
                bool isYes = Localization.ParseBoolean(config.ConfigValue);

                RadioButtonList rbYesNo = new RadioButtonList();
                rbYesNo.ID = editorId;
                rbYesNo.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;

                ListItem optionYes = new ListItem("Yes");
                ListItem optionNo  = new ListItem("No");

                if (StoreId == 0)
                {
                    optionYes.Attributes.Add("onclick", "$(this).parents('.modal_popup_Content').find('span.defaultTrue input').each(function (index, value) {$(value).click();});");
                    optionNo.Attributes.Add("onclick", "$(this).parents('.modal_popup_Content').find('span.defaultFalse input').each(function (index, value) {$(value).click();});");
                }
                else if (isnew)
                {
                    optionYes.Attributes.Add("class", "defaultTrue");
                    optionNo.Attributes.Add("class", "defaultFalse");
                }

                optionYes.Selected = isYes;
                optionNo.Selected  = !isYes;

                rbYesNo.Items.Add(optionYes);
                rbYesNo.Items.Add(optionNo);

                m_configvalue = optionYes.Selected.ToString().ToLowerInvariant();

                plhConfigValueEditor.Controls.Add(rbYesNo);
            }
            else if (config.ValueType.EqualsIgnoreCase("enum"))
            {
                DropDownList cboValues = new DropDownList();
                cboValues.ID = editorId;
                foreach (string value in config.AllowableValues)
                {
                    cboValues.Items.Add(value);
                }
                cboValues.SelectedValue = config.ConfigValue;

                m_configvalue = cboValues.SelectedValue;

                plhConfigValueEditor.Controls.Add(cboValues);
            }
            else if (config.ValueType.EqualsIgnoreCase("invoke"))
            {
                DropDownList cboValues = new DropDownList();
                cboValues.ID = editorId;

                bool   invocationSuccessful = false;
                string errorMessage         = string.Empty;

                try
                {
                    if (config.AllowableValues.Count == 3)
                    {
                        // format should be
                        // {FullyQualifiedName},MethodName
                        // Fully qualified name format is Namespace.TypeName,AssemblyName
                        string typeName     = config.AllowableValues[0];
                        string assemblyName = config.AllowableValues[1];
                        string methodName   = config.AllowableValues[2];

                        string     fqName = typeName + "," + assemblyName;
                        Type       t      = Type.GetType(fqName);
                        object     o      = Activator.CreateInstance(t);
                        MethodInfo method = o.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
                        object     result = method.Invoke(o, new object[] { });

                        if (result is IEnumerable)
                        {
                            cboValues.DataSource = result;
                            cboValues.DataBind();

                            invocationSuccessful = true;

                            // now try to find which one is matching, case-insensitive
                            foreach (ListItem item in cboValues.Items)
                            {
                                item.Selected = item.Text.EqualsIgnoreCase(config.ConfigValue);
                            }
                        }
                        else
                        {
                            errorMessage         = "Invocation method must return IEnumerable";
                            invocationSuccessful = false;
                        }
                    }
                    else
                    {
                        errorMessage         = "Invalid invocation value";
                        invocationSuccessful = false;
                    }
                }
                catch (Exception ex)
                {
                    errorMessage         = ex.Message;
                    invocationSuccessful = false;
                }

                if (invocationSuccessful == false)
                {
                    cboValues.Items.Add(errorMessage);
                }

                m_configvalue = cboValues.SelectedValue;

                plhConfigValueEditor.Controls.Add(cboValues);
            }
            else if (config.ValueType.EqualsIgnoreCase("multiselect"))
            {
                CheckBoxList chkValues = new CheckBoxList();
                chkValues.ID = editorId;

                Func <string, bool> isIncluded = (optionValue) =>
                {
                    return(config.ConfigValue.Split(',').Any(val => val.Trim().EqualsIgnoreCase(optionValue)));
                };

                foreach (string optionValue in config.AllowableValues)
                {
                    ListItem option = new ListItem(optionValue, optionValue);
                    option.Selected = isIncluded(optionValue);
                    chkValues.Items.Add(option);
                }

                List <string> selectedValues = new List <string>();
                foreach (ListItem option in chkValues.Items)
                {
                    if (option.Selected)
                    {
                        selectedValues.Add(option.Value);
                    }
                }

                // format the selected values into a comma delimited string
                m_configvalue = selectedValues.ToCommaDelimitedString();

                plhConfigValueEditor.Controls.Add(chkValues);
            }
            else
            {
                // determine length for proper control to use
                string configValue = config.ConfigValue;

                TextBox txt = new TextBox();
                txt.ID   = editorId;
                txt.Text = configValue;

                if (configValue.Length >= MAX_COLUMN_LENGTH)
                {
                    // use textArea
                    txt.TextMode = TextBoxMode.MultiLine;
                    txt.Rows     = 4; // make it 4 rows by default
                }

                txt.Columns = DetermineProperTextColumnLength(configValue);

                m_configvalue = txt.Text;

                plhConfigValueEditor.Controls.Add(txt);
            }

            return(plhConfigValueEditor);
        }
Example #47
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //记录页面使用次数
            DB.RecordPageUseCount("Plant_DISPACCOUNT");

            date1   = "1910-01";
            newdate = false;

            int CurrentYear = Convert.ToInt32(DateTime.Now.Year);
            int i;
            for (i = CurrentYear - 5; i <= CurrentYear; i++)
            {
                ListItem Year = new ListItem();
                Year.Text  = Convert.ToString(i);
                Year.Value = Convert.ToString(i);
                if (i == CurrentYear)
                {
                    Year.Selected = true;
                }
                else
                {
                    Year.Selected = false;
                }
                ddlYear.Items.Add(Year);
                //EndYear.Items.Add(Year);
            }

            string CurrentDate = Convert.ToString(DateTime.Now.Month);
            if (CurrentDate.Length == 1)
            {
                CurrentDate = "0" + CurrentDate;
            }
            foreach (ListItem Month in ddlMonth.Items)
            {
                if (Month.Text == CurrentDate)
                {
                    Month.Selected = true;
                    ddlMonth.Text  = Month.Text;
                    //EndMonth.Text = Month.Text;
                    break;
                }
                else
                {
                    Month.Selected = false;
                }
            }
            AddDate(sender, e);
            CurrentDate = Convert.ToString(DateTime.Now.Day - 1);
            if (CurrentDate.Length == 1)
            {
                CurrentDate = "0" + CurrentDate;
            }
            foreach (ListItem day in ddlDay.Items)
            {
                if (day.Text == CurrentDate)
                {
                    day.Selected = true;
                    ddlDay.Text  = day.Text;
                    //EndDay.Text = day.Text;
                    break;
                }
                else
                {
                    day.Selected = false;
                }
            }
        }
        else
        {
            date1 = ddlYear.SelectedValue.ToString() + '-' + ddlMonth.SelectedValue.ToString() + '-' + ddlDay.SelectedValue.ToString();
            string           strCurrentDate = date1;
            OracleConnection conn           = DB.createConn();
            try
            {
                OracleDataAdapter da = new OracleDataAdapter();
                if (newdate)
                {
                    //CrystalReportViewer1.ResetReportPartNavigation();
                    newdate = false;
                }

                conn.Open();
                DataSet ds = new DataSet();
                //ReportDocument CRptHeatName = new ReportDocument();
                string j = ddlDISPACCOUNT.SelectedValue.ToString();
                if (j == "3")
                {
                    string strSQL = "Select * from TP_REHEAT_ACCOUNT where LOGTIME='" + strCurrentDate + "' ORDER BY CCMID";
                    da.SelectCommand = new OracleCommand(strSQL, conn);
                    da.Fill(ds, "TP_REHEAT_ACCOUNT");

                    rdt.Load(this.Server.MapPath("").ToString() + "\\REHEATACCOUNT.rpt");

                    //rdt.PrintOptions.PrinterName = "Microsoft Office Document Image Writer";
                    rdt.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperEsheet;

                    rdt.SetDataSource(ds);

                    CrystalReportViewer1.ReportSource = rdt;
                    CrystalReportViewer1.DataBind();
                }
                else
                {
                    string strSQL = "Select * from TP_DISP_ACCOUNT where PRODUCTDATE='" + strCurrentDate + "'AND ACCOUNTTYPE='" + ddlDISPACCOUNT.SelectedValue + "' ORDER BY UNITID";
                    da.SelectCommand = new OracleCommand(strSQL, conn);
                    da.Fill(ds, "TP_DISP_ACCOUNT");

                    rdt.Load(this.Server.MapPath("").ToString() + "\\DISPACCOUNT.rpt");

                    //rdt.PrintOptions.PrinterName = "Microsoft Office Document Image Writer";
                    rdt.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperEsheet;

                    rdt.SetDataSource(ds);

                    CrystalReportViewer1.ReportSource = rdt;
                    CrystalReportViewer1.DataBind();
                    rdt.SetParameterValue("p", ddlDISPACCOUNT.Items[ddlDISPACCOUNT.SelectedIndex].ToString() + ")");
                }
                ds.Dispose();
            }


            catch (Exception ee)
            {
                Response.Write(ee.ToString());//"出错");
            }
            finally
            {
                conn.Close();
            }
        }
    }
Example #48
0
        public static void AddNewListItem(CsvRecord record, List spList, ClientContext clientContext)
        {
            Dictionary <string, object> itemFieldValues = new Dictionary <string, object>();

            //Use reflection to iterate through the record's properties
            PropertyInfo[] properties = typeof(CsvRecord).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object propValue = property.GetValue(record, null);
                if (!String.IsNullOrEmpty(propValue.ToString()))
                {
                    Field matchingField = spList.Fields.GetByInternalNameOrTitle(property.Name);
                    clientContext.Load(matchingField);
                    clientContext.ExecuteQuery();

                    switch (matchingField.FieldTypeKind)
                    {
                    case FieldType.User:
                        FieldUserValue userFieldValue = GetUserFieldValue(propValue.ToString(), clientContext);
                        if (userFieldValue != null)
                        {
                            itemFieldValues.Add(matchingField.InternalName, userFieldValue);
                        }
                        else
                        {
                            throw new Exception("User field value could not be added: " + propValue.ToString());
                        }
                        break;

                    case FieldType.Lookup:
                        FieldLookupValue lookupFieldValue = GetLookupFieldValue(propValue.ToString(),
                                                                                ConfigurationManager.AppSettings["LookupListName"].ToString(),
                                                                                clientContext);
                        if (lookupFieldValue != null)
                        {
                            itemFieldValues.Add(matchingField.InternalName, lookupFieldValue);
                        }
                        else
                        {
                            throw new Exception("Lookup field value could not be added: " + propValue.ToString());
                        }
                        break;

                    case FieldType.Invalid:
                        switch (matchingField.TypeAsString)
                        {
                        default:
                            //Code for publishing site columns not implemented
                            continue;
                        }

                    default:
                        itemFieldValues.Add(matchingField.InternalName, propValue);
                        break;
                    }
                }
            }

            //Add new item to list
            ListItemCreationInformation creationInfo = new ListItemCreationInformation();
            ListItem oListItem = spList.AddItem(creationInfo);

            foreach (KeyValuePair <string, object> itemFieldValue in itemFieldValues)
            {
                //Set each field value
                oListItem[itemFieldValue.Key] = itemFieldValue.Value;
            }
            //Persist changes
            oListItem.Update();
            clientContext.ExecuteQuery();
        }
Example #49
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (EditedObject == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        Save += btnOK_Click;

        var user = MembershipContext.AuthenticatedUser;

        // Check permissions for Forms application
        if (!user.IsAuthorizedPerUIElement("cms.form", "Form"))
        {
            RedirectToUIElementAccessDenied("cms.form", "Form");
        }

        // Check 'ReadData' permission
        if (!user.IsAuthorizedPerResource("cms.form", "ReadData", SiteInfoProvider.GetSiteName(FormInfo.FormSiteID)))
        {
            RedirectToAccessDenied("cms.form", "ReadData");
        }

        // Check authorized roles for this form
        if (!FormInfo.IsFormAllowedForUser(MembershipContext.AuthenticatedUser.UserName, SiteContext.CurrentSiteName))
        {
            RedirectToAccessDenied(GetString("Bizforms.FormNotAllowedForUserRoles"));
        }

        List <String> columnNames  = null;
        DataClassInfo dci          = null;
        Hashtable     reportFields = new Hashtable();
        FormInfo      fi           = null;

        // Initialize controls
        PageTitle.TitleText = GetString("BizForm_Edit_Data_SelectFields.Title");
        CurrentMaster.DisplayActionsPanel = true;

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.SelectAll"),
            OnClientClick = "ChangeFields(true); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.DeselectAll"),
            OnClientClick = "ChangeFields(false); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        if (!RequestHelper.IsPostBack())
        {
            if (FormInfo != null)
            {
                // Get dataclass info
                dci = DataClassInfoProvider.GetDataClassInfo(FormInfo.FormClassID);

                if (dci != null)
                {
                    // Get columns names
                    fi = FormHelper.GetFormInfo(dci.ClassName, false);

                    columnNames = fi.GetColumnNames(false, i => i.System);
                }

                // Get report fields
                if (String.IsNullOrEmpty(FormInfo.FormReportFields))
                {
                    reportFields = LoadReportFields(columnNames);
                }
                else
                {
                    reportFields.Clear();

                    foreach (string field in FormInfo.FormReportFields.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                if (columnNames != null)
                {
                    FormFieldInfo ffi  = null;
                    ListItem      item = null;

                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + FormInfo.ClassName);

                    foreach (string name in columnNames)
                    {
                        ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
Example #50
0
        private void renderTest(List <Question> inputList)
        {
            testContent.Controls.Clear();

            foreach (Question q in inputList)
            {
                HtmlGenericControl div = new HtmlGenericControl("div");
                div.Attributes.Add("ID", q.id.ToString());

                Label  activeCategory = new Label();
                Label  activeQuestion = new Label();
                string catequest;

                if (q.category == 1)
                {
                    catequest = "Produkter och hantering av kundens affärer. ";
                }
                else if (q.category == 2)
                {
                    catequest = "Ekonomi. ";
                }
                else
                {
                    catequest = "Etik och regelverk. ";
                }
                activeCategory.Text = catequest;
                activeQuestion.Text = q.question;
                div.Controls.Add(activeCategory);
                div.Controls.Add(activeQuestion);

                testContent.Controls.Add(div);

                //Get radiobuttons if there is only one correct answer
                if (q.answerList.FindAll(x => x.correct == true).ToList().Count == 1)
                {
                    RadioButtonList rbList = new RadioButtonList();
                    rbList.ID = q.id.ToString();

                    foreach (var answer in q.answerList)
                    {
                        ListItem li = new ListItem();

                        if (answer.text.IndexOf(".jpg") > 0)
                        {
                            Image newImg = new Image();
                            newImg.ImageUrl = answer.text;
                            li.Value        = answer.id;
                            li.Text         = "<img src='" + newImg.ImageUrl + "'>";


                            rbList.Items.Add(li);
                            div.Controls.Add(rbList);
                            div.Controls.Add(newImg);
                        }
                        else
                        {
                            li.Text  = answer.text;
                            li.Value = answer.id;

                            rbList.Items.Add(li);
                            div.Controls.Add(rbList);
                        }
                    }
                }
                //Get checkbuttons if there is more than one correct answer
                else
                {
                    CheckBoxList cbList = new CheckBoxList();
                    cbList.ID = q.id.ToString();

                    foreach (var answer in q.answerList)
                    {
                        ListItem li = new ListItem();

                        if (answer.text.IndexOf(".jpg") > 0)
                        {
                            Image newImg = new Image();
                            newImg.ImageUrl = answer.text;
                            li.Value        = answer.id;
                            li.Text         = "<img src='" + newImg.ImageUrl + "'>";

                            cbList.Items.Add(li);
                            div.Controls.Add(cbList);
                        }
                        else
                        {
                            li.Text  = answer.text;
                            li.Value = answer.id;

                            cbList.Items.Add(li);
                            div.Controls.Add(cbList);
                        }
                    }
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["edit_message"] != null)
        {
            Response.Write(Session["edit_message"]);
            Session["edit_message"] = null;
        }

        string        connString = ConfigurationManager.ConnectionStrings["iWorkDBConn"].ToString();
        SqlConnection conn       = new SqlConnection(connString);

        SqlCommand cmd = new SqlCommand("View_prev_job_titles_of_Manager", conn);

        cmd.CommandType = System.Data.CommandType.StoredProcedure;

        cmd.Parameters.Add(new SqlParameter("@user", Session["username"]));

        conn.Open();

        SqlDataReader rdr     = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        int           counter = 0;

        while (rdr.Read())
        {
            ListItem listItem = new ListItem();
            listItem.Text = rdr.GetValue(rdr.GetOrdinal("job_title")).ToString();
            previous_jobtitles_ddl.Items.Add(listItem);
            counter++;
        }

        conn.Close();

        Label passwordLabel   = new Label(); passwordLabel.Text = "New Password: "******"New First Name: ";
        Label middlenameLabel = new Label(); middlenameLabel.Text = "New Middle Name: ";
        Label lastnameLabel   = new Label(); lastnameLabel.Text = "New Last Name: ";
        Label birthdateLabel  = new Label(); birthdateLabel.Text = "New Birthdate: ";
        Label emailLabel      = new Label(); emailLabel.Text = "New Email: ";
        Label yearsLabel      = new Label(); yearsLabel.Text = "New Years of Experience: ";

        passwordLabel.CssClass   = "labels";
        firstnameLabel.CssClass  = "labels";
        middlenameLabel.CssClass = "labels";
        lastnameLabel.CssClass   = "labels";
        birthdateLabel.CssClass  = "labels";
        emailLabel.CssClass      = "labels";
        yearsLabel.CssClass      = "labels";

        Button submit_update_button = new Button();

        submit_update_button.Text   = "Update Personal Info";
        submit_update_button.Click += new EventHandler(update_personal_info);

        Button add_jobtitle_button = new Button();

        add_jobtitle_button.Text   = "Add a New Title";
        add_jobtitle_button.Click += new EventHandler(add_new_title);

        Button delete_jobtitle_button = new Button();

        delete_jobtitle_button.Text   = "Delete Selected Title";
        delete_jobtitle_button.Click += new EventHandler(delete_title);


        edit_form.Controls.Add(new Literal {
            Text = "<H2>Update your personal information, " + Session["username"].ToString() + ".</H2>"
        });

        edit_form.Controls.Add(passwordLabel); edit_form.Controls.Add(password_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(firstnameLabel); edit_form.Controls.Add(first_name_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(middlenameLabel); edit_form.Controls.Add(middle_name_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(lastnameLabel); edit_form.Controls.Add(last_name_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(birthdateLabel); edit_form.Controls.Add(birthdate_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(emailLabel); edit_form.Controls.Add(email_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(yearsLabel); edit_form.Controls.Add(years_of_experience_textbox);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });
        edit_form.Controls.Add(submit_update_button);

        edit_form.Controls.Add(new Literal {
            Text = "<H3>Edit Previous Job Titles: </H3>"
        });
        edit_form.Controls.Add(add_new_jobtitle_textbox); edit_form.Controls.Add(add_jobtitle_button);
        edit_form.Controls.Add(new Literal {
            Text = "<br/>"
        });

        if (counter > 0)
        {
            edit_form.Controls.Add(previous_jobtitles_ddl); edit_form.Controls.Add(delete_jobtitle_button);
            edit_form.Controls.Add(new Literal {
                Text = "<br/>"
            });
        }
        else
        {
            edit_form.Controls.Add(new Literal {
                Text = "You have entered zero previous job titles so far.<br/>"
            });
        }
    }
Example #52
0
        protected void btnTestSurvey_Click(object sender, EventArgs e)
        {
            ListItem li = ddlSurveys.SelectedItem;

            Response.Redirect("TestSurvey.aspx?SurveyID=" + li.Value.ToString());
        }
Example #53
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // return to test start on refresh
        if (Page.IsPostBack && _isRefresh)
        {
            Response.Redirect(Request.RawUrl);
        }

        // do not update answers/questions on partial async postback (timer tick)
        if (Page.IsPostBack && ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
        {
            return;
        }

        string var_id = Request.QueryString["id"];

        //manage page content
        if (var_id != null)
        {
            TestsList_Form.Visible = false;

            if (var_id == "new")
            {
                //display new test UI
                if (Session["teacher"] == null)
                {
                    Response.Redirect("~/Content/Tests.aspx");
                }

                if (!Page.IsPostBack)
                {
                    GenerateEmptyGridView();
                }

                TestsList.Visible    = false;
                NewTest_Form.Visible = true;
            }
            else // display test
            {
                string     SQL_SELECT = "SELECT * FROM " + TestsDB + " WHERE TestID=" + Request.QueryString["id"];
                SqlCommand CMD_SELECT = new SqlCommand(SQL_SELECT, DB_Connection);
                CMD_SELECT.CommandType = CommandType.Text;

                int        TestID         = 0;
                int        QuestionsLimit = 0;
                int        ChancesLimit   = 0;
                int        ChancesUsed    = 0;
                int        TimeLimit      = 0;
                bool       IsFree         = false;
                List <int> Questions      = new List <int>();

                DB_Connection.Open();

                using (SqlDataReader Reader = CMD_SELECT.ExecuteReader())
                {
                    if (Reader.Read())
                    {
                        DisplayTest_Title.Text = Reader["Title"].ToString();
                        TestID         = int.Parse(Reader["TestID"].ToString());
                        QuestionsLimit = int.Parse(Reader["QuestionsLimit"].ToString());
                        ChancesLimit   = int.Parse(Reader["ChancesLimit"].ToString());
                        TimeLimit      = int.Parse(Reader["TimeLimit"].ToString());
                        IsFree         = Convert.ToBoolean(Reader["IsFreeTest"]);

                        if (!IsFree && Session["student"] == null && Session["teacher"] == null)
                        {
                            Response.Redirect("~/Content/Tests.aspx");
                        }
                    }
                }

                if (ViewState["CurrentQuestion"] == null)
                {
                    string     SQL_SELECT_2 = "SELECT * FROM " + TestQuestionsDB + " WHERE TestID=" + TestID;
                    SqlCommand CMD_SELECT_2 = new SqlCommand(SQL_SELECT_2, DB_Connection);
                    CMD_SELECT_2.CommandType = CommandType.Text;

                    //make list of question IDs
                    using (SqlDataReader Reader = CMD_SELECT_2.ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            Questions.Add(int.Parse(Reader["QuestionID"].ToString()));
                        }
                    }

                    int[] Questions_Array = new int[QuestionsLimit];

                    // shuffle questions
                    for (int i = 0; i < QuestionsLimit; ++i)
                    {
                        int q = Questions[new Random().Next(Questions.Count)];

                        if (Array.IndexOf(Questions_Array, q) < 0)
                        {
                            Questions_Array[i] = q;
                        }
                        else
                        {
                            --i;
                        }
                    }

                    // display test info
                    if (Session["student"] != null || Session["teacher"] != null)
                    {
                        string     SQL_SELECT_3 = "SELECT count(*) FROM " + MarksDB + " WHERE Username='******' AND TestID=" + TestID;
                        SqlCommand CMD_SELECT_3 = new SqlCommand(SQL_SELECT_3, DB_Connection);
                        CMD_SELECT_3.CommandType = CommandType.Text;

                        ChancesUsed            = int.Parse(CMD_SELECT_3.ExecuteScalar().ToString());
                        TestInfo_UserInfo.Text = Session["SurName"].ToString();
                    }

                    int QuestionTimer = (TimeLimit * 60) / QuestionsLimit;

                    TestInfo_QuestionsLimit.Text       = Questions_Array.Length.ToString();
                    TestInfo_TimeLimit.Text            = TimeLimit == 0 ? "Необмежено" : TimeLimit + " хв.";
                    TestInfo_TimePerQuestionLimit.Text = TimeLimit == 0 ? "Необмежено" : QuestionTimer.ToString() + " сек.";
                    TestInfo_TimesPassed.Text          = ChancesLimit == 0 ? "Необмежено" : ChancesUsed.ToString() + " / " + ChancesLimit.ToString();

                    int j = new Random().Next(Questions_Array.Length);

                    ViewState["CurrentQuestion"] = Questions_Array[j];
                    ViewState["Questions"]       = Questions_Array;
                    ViewState["QuestionTimer"]   = QuestionTimer;
                    ViewState["TestTimer"]       = TimeLimit * 60;

                    // no chances left
                    if (ChancesUsed >= ChancesLimit && ChancesLimit != 0)
                    {
                        TestInfo_TimesPassed.ForeColor = System.Drawing.Color.Red;
                        next_question.Enabled          = false;
                    }

                    DisplayTest_InfoForm.Visible = true;
                }
                else
                {
                    // save answer
                    if (ViewState["Answers"] != null && ViewState["PassedQuestions"] != null)
                    {
                        int[] answers     = ViewState["Answers"] as int[];
                        int[] answers_new = new int[answers.Length + 1];

                        for (int i = 0; i < answers.Length; ++i)
                        {
                            answers_new[i] = answers[i];
                        }

                        answers_new[answers_new.Length - 1] = int.Parse(DisplayTest_ChoicesList.SelectedValue);
                        ViewState["Answers"] = answers_new;
                    }
                    else
                    {
                        if (DisplayTest_ChoicesList.SelectedIndex >= 0)
                        {
                            int[] answers = new int[1] {
                                int.Parse(DisplayTest_ChoicesList.SelectedValue)
                            };
                            ViewState["Answers"] = answers;
                        }
                    }

                    //show result if finished test
                    if (ViewState["Answers"] != null && ViewState["Questions"] != null && (ViewState["Answers"] as int[]).Length == (ViewState["Questions"] as int[]).Length)
                    {
                        DisplayTest_TimerPeriodic.Enabled = false;

                        int[] answers = ViewState["Answers"] as int[];
                        int   correct = 0;
                        int   Mark    = 0;

                        for (int i = 0; i < answers.Length; ++i)
                        {
                            string     SQL_SELECT_2 = "SELECT IsCorrect FROM " + TestAnswersDB + " WHERE ChoiceID=" + answers[i];
                            SqlCommand CMD_SELECT_2 = new SqlCommand(SQL_SELECT_2, DB_Connection);
                            CMD_SELECT_2.CommandType = CommandType.Text;

                            using (SqlDataReader Reader = CMD_SELECT_2.ExecuteReader())
                            {
                                if (Reader.Read() && Convert.ToBoolean(Reader["IsCorrect"]))
                                {
                                    ++correct;
                                }
                            }
                        }

                        float Points = (float)100 / answers.Length * correct;
                        Mark = (int)Points;

                        // save to DB if not free and if student logged in
                        if (!IsFree && Session["student"] != null)
                        {
                            string     SQL_SelectGroupID = "(SELECT GroupID FROM " + UsersDB + " WHERE Username='******')";
                            string     SQL_INSERT        = "INSERT INTO " + MarksDB + " VALUES('" + Session["student"].ToString() + "', " + TestID + ", " + Mark + ", '" + DateTime.Now.ToString() + "', " + SQL_SelectGroupID + ")";
                            SqlCommand CMD_INSERT        = new SqlCommand(SQL_INSERT, DB_Connection);
                            CMD_INSERT.CommandType = CommandType.Text;

                            CMD_INSERT.ExecuteNonQuery();
                        }

                        DB_Connection.Close();
                        DisplayTest_Result.Text          = "Кількість правильних відповідей  " + correct + " з " + answers.Length + " запитань. Ви набрали " + Mark + " балів.";
                        DisplayTest_QuestionForm.Visible = false;
                        DisplayTest_ResultForm.Visible   = true;
                        next_question.Visible            = false;
                        return;
                    }

                    // display (next) question

                    // update timer
                    if (ViewState["TestTimer"] != null && ViewState["Questions"] != null)
                    {
                        DisplayTest_TimeLeft.ForeColor = System.Drawing.Color.LightGreen;
                        DisplayTest_TimeLeft.Text      = "Залишилось часу: " + ViewState["QuestionTimer"].ToString() + " сек.";
                        Timer1.Enabled = false;
                    }

                    // show question
                    int CurrentQuestion = int.Parse(ViewState["CurrentQuestion"].ToString());

                    string     SQL_SELECT_3 = "SELECT QuestionText FROM " + TestQuestionsDB + " WHERE QuestionID=" + CurrentQuestion;
                    SqlCommand CMD_SELECT_3 = new SqlCommand(SQL_SELECT_3, DB_Connection);
                    CMD_SELECT_3.CommandType = CommandType.Text;

                    string     SQL_SELECT_4 = "SELECT * FROM " + TestAnswersDB + " WHERE QuestionID=" + CurrentQuestion;
                    SqlCommand CMD_SELECT_4 = new SqlCommand(SQL_SELECT_4, DB_Connection);
                    CMD_SELECT_4.CommandType = CommandType.Text;

                    using (SqlDataReader Reader = CMD_SELECT_3.ExecuteReader())
                    {
                        int    PassedQuestions = ViewState["PassedQuestions"] != null ? (ViewState["PassedQuestions"] as int[]).Length + 1 : 1;
                        string QuestionIndex   = "<b>" + PassedQuestions + "/" + QuestionsLimit + " </b>";

                        if (Reader.Read())
                        {
                            DisplayTest_QuestionText.Text = QuestionIndex + Reader["QuestionText"].ToString() + "<br />";
                        }
                    }

                    using (SqlDataReader Reader = CMD_SELECT_4.ExecuteReader())
                    {
                        DisplayTest_ChoicesList.Items.Clear();

                        //fill list of choices
                        while (Reader.Read())
                        {
                            ListItem item = new ListItem();
                            item.Value = Reader["ChoiceID"].ToString();
                            item.Text  = Reader["ChoiceText"].ToString();
                            DisplayTest_ChoicesList.Items.Add(item);
                        }

                        //shuffle choices
                        for (int i = 0; i < DisplayTest_ChoicesList.Items.Count; ++i)
                        {
                            int      r    = new Random().Next(DisplayTest_ChoicesList.Items.Count);
                            ListItem temp = DisplayTest_ChoicesList.Items[i];
                            DisplayTest_ChoicesList.Items.Remove(temp);
                            DisplayTest_ChoicesList.Items.Insert(r, temp);
                        }

                        //add default selection
                        ListItem item0 = new ListItem();
                        item0.Text     = "<b>жоден із варіантів</b>";
                        item0.Value    = "0";
                        item0.Selected = true;
                        DisplayTest_ChoicesList.Items.Add(item0);
                    }
                }

                TestsList.Visible = false;
                DisplayTest_QuestionForm.Visible = true;
                DisplayTest_Form.Visible         = true;

                DB_Connection.Close();
            }
        }
        else
        {
            // display list of tests
            if (Session["teacher"] == null)
            {
                TestsList.Columns[5].Visible = false;
                TestsList.ShowFooter         = false;
            }

            string SQL_SELECT = "SELECT * FROM " + TestsDB + " WHERE IsFreeTest=1";

            // display full list of tests only for logged in users
            if (Session["student"] != null || Session["teacher"] != null)
            {
                SQL_SELECT = "SELECT * FROM " + TestsDB + " ORDER BY IsFreeTest DESC";
            }

            SqlDataAdapter da = new SqlDataAdapter(SQL_SELECT, DB_Connection);
            DataTable      dt = new DataTable();

            DB_Connection.Open();

            da.Fill(dt);
            TestsList.DataSource = dt;
            TestsList.DataBind();

            DB_Connection.Close();
        }
    }
Example #54
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");
            _channelId = AuthRequest.IsQueryExists("channelId") ? AuthRequest.GetQueryInt("channelId") : SiteId;

            _isCheckOnly   = AuthRequest.GetQueryBool("isCheckOnly");
            _isTrashOnly   = AuthRequest.GetQueryBool("isTrashOnly");
            _isWritingOnly = AuthRequest.GetQueryBool("isWritingOnly");
            _isAdminOnly   = AuthRequest.GetQueryBool("isAdminOnly");

            _channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);
            var tableName = ChannelManager.GetTableName(SiteInfo, _channelInfo);

            _styleInfoList       = TableStyleManager.GetContentStyleInfoList(SiteInfo, _channelInfo);
            _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(ChannelManager.GetContentAttributesOfDisplay(SiteId, _channelId));
            _allStyleInfoList    = ContentUtility.GetAllTableStyleInfoList(_styleInfoList);
            _pluginIds           = PluginContentManager.GetContentPluginIds(_channelInfo);
            _pluginColumns       = PluginContentManager.GetContentColumns(_pluginIds);
            _isEdit = TextUtility.IsEdit(SiteInfo, _channelId, AuthRequest.AdminPermissionsImpl);

            var state      = AuthRequest.IsQueryExists("state") ? AuthRequest.GetQueryInt("state") : CheckManager.LevelInt.All;
            var searchType = AuthRequest.IsQueryExists("searchType") ? AuthRequest.GetQueryString("searchType") : ContentAttribute.Title;
            var dateFrom   = AuthRequest.IsQueryExists("dateFrom") ? AuthRequest.GetQueryString("dateFrom") : string.Empty;
            var dateTo     = AuthRequest.IsQueryExists("dateTo") ? AuthRequest.GetQueryString("dateTo") : string.Empty;
            var keyword    = AuthRequest.IsQueryExists("keyword") ? AuthRequest.GetQueryString("keyword") : string.Empty;

            var checkedLevel = 5;
            var isChecked    = true;

            foreach (var owningChannelId in AuthRequest.AdminPermissionsImpl.ChannelIdList)
            {
                int checkedLevelByChannelId;
                var isCheckedByChannelId = CheckManager.GetUserCheckLevel(AuthRequest.AdminPermissionsImpl, SiteInfo, owningChannelId, out checkedLevelByChannelId);
                if (checkedLevel > checkedLevelByChannelId)
                {
                    checkedLevel = checkedLevelByChannelId;
                }
                if (!isCheckedByChannelId)
                {
                    isChecked = false;
                }
            }

            RptContents.ItemDataBound += RptContents_ItemDataBound;

            var allAttributeNameList = TableColumnManager.GetTableColumnNameList(tableName, DataType.Text);
            var onlyAdminId          = _isAdminOnly
                ? AuthRequest.AdminId
                : AuthRequest.AdminPermissionsImpl.GetOnlyAdminId(SiteInfo.Id, _channelInfo.Id);
            var whereString = DataProvider.ContentDao.GetPagerWhereSqlString(SiteInfo, _channelInfo,
                                                                             searchType, keyword,
                                                                             dateFrom, dateTo, state, _isCheckOnly, false, _isTrashOnly, _isWritingOnly, onlyAdminId,
                                                                             AuthRequest.AdminPermissionsImpl,
                                                                             allAttributeNameList);

            PgContents.Param = new PagerParam
            {
                ControlToPaginate = RptContents,
                TableName         = tableName,
                PageSize          = SiteInfo.Additional.PageSize,
                Page              = AuthRequest.GetQueryInt(Pager.QueryNamePage, 1),
                OrderSqlString    = ETaxisTypeUtils.GetContentOrderByString(ETaxisType.OrderByIdDesc),
                ReturnColumnNames = TranslateUtils.ObjectCollectionToString(allAttributeNameList),
                WhereSqlString    = whereString,
                TotalCount        = DataProvider.DatabaseDao.GetPageTotalCount(tableName, whereString)
            };

            if (IsPostBack)
            {
                return;
            }

            if (_isTrashOnly)
            {
                if (AuthRequest.IsQueryExists("IsDeleteAll"))
                {
                    //DataProvider.ContentDao.DeleteContentsByTrash(SiteId, _channelId, tableName);

                    var list = DataProvider.ContentDao.GetContentIdListByTrash(SiteId, tableName);
                    foreach (var(contentChannelId, contentId) in list)
                    {
                        ContentUtility.Delete(tableName, SiteInfo, contentChannelId, contentId);
                    }

                    AuthRequest.AddSiteLog(SiteId, "清空回收站");
                    SuccessMessage("成功清空回收站!");
                }
                else if (AuthRequest.IsQueryExists("IsRestore"))
                {
                    var idsDictionary = ContentUtility.GetIDsDictionary(Request.QueryString);
                    foreach (var channelId in idsDictionary.Keys)
                    {
                        var contentIdList = idsDictionary[channelId];
                        DataProvider.ContentDao.UpdateTrashContents(SiteId, channelId, ChannelManager.GetTableName(SiteInfo, channelId), contentIdList);
                    }
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原内容");
                    SuccessMessage("成功还原内容!");
                }
                else if (AuthRequest.IsQueryExists("IsRestoreAll"))
                {
                    DataProvider.ContentDao.UpdateRestoreContentsByTrash(SiteId, _channelId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原所有内容");
                    SuccessMessage("成功还原所有内容!");
                }
            }

            ChannelManager.AddListItems(DdlChannelId.Items, SiteInfo, true, true, AuthRequest.AdminPermissionsImpl);

            if (_isCheckOnly)
            {
                CheckManager.LoadContentLevelToCheck(DdlState, SiteInfo, isChecked, checkedLevel);
            }
            else
            {
                CheckManager.LoadContentLevelToList(DdlState, SiteInfo, _isCheckOnly, isChecked, checkedLevel);
            }

            ControlUtils.SelectSingleItem(DdlState, state.ToString());

            foreach (var styleInfo in _allStyleInfoList)
            {
                if (styleInfo.InputType == InputType.TextEditor)
                {
                    continue;
                }

                var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                DdlSearchType.Items.Add(listitem);
            }

            //ETriStateUtils.AddListItems(DdlState, "全部", "已审核", "待审核");

            if (SiteId != _channelId)
            {
                ControlUtils.SelectSingleItem(DdlChannelId, _channelId.ToString());
            }
            //ControlUtils.SelectSingleItem(DdlState, AuthRequest.GetQueryString("State"));
            ControlUtils.SelectSingleItem(DdlSearchType, searchType);
            TbKeyword.Text  = keyword;
            TbDateFrom.Text = dateFrom;
            TbDateTo.Text   = dateTo;

            PgContents.DataBind();

            LtlColumnsHead.Text += TextUtility.GetColumnsHeadHtml(_styleInfoList, _pluginColumns, _attributesOfDisplay);


            BtnSelect.Attributes.Add("onclick", ModalSelectColumns.GetOpenWindowString(SiteId, _channelId));

            if (_isTrashOnly)
            {
                LtlColumnsHead.Text  += @"<th class=""text-center text-nowrap"" width=""150"">删除时间</th>";
                BtnAddToGroup.Visible = BtnTranslate.Visible = BtnCheck.Visible = false;
                PhTrash.Visible       = true;
                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible    = false;
                    BtnDeleteAll.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, true, PageUrl));
                    BtnDeleteAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsDeleteAll", "True"), "确实要清空回收站吗?"));
                }
                BtnRestore.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValue(PageUtils.AddQueryString(PageUrl, "IsRestore", "True"), "IDsCollection", "IDsCollection", "请选择需要还原的内容!"));
                BtnRestoreAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsRestoreAll", "True"), "确实要还原所有内容吗?"));
            }
            else
            {
                LtlColumnsHead.Text += @"<th class=""text-center text-nowrap"" width=""100"">操作</th>";

                BtnAddToGroup.Attributes.Add("onclick", ModalAddToGroup.GetOpenWindowStringToContentForMultiChannels(SiteId));

                if (HasChannelPermissions(SiteId, ConfigManager.ChannelPermissions.ContentCheck))
                {
                    BtnCheck.Attributes.Add("onclick", ModalContentCheck.GetOpenWindowStringForMultiChannels(SiteId, PageUrl));
                    if (_isCheckOnly)
                    {
                        BtnCheck.CssClass = "btn m-r-5 btn-success";
                    }
                }
                else
                {
                    PhCheck.Visible = false;
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentTranslate))
                {
                    BtnTranslate.Visible = false;
                }
                else
                {
                    BtnTranslate.Attributes.Add("onclick", PageContentTranslate.GetRedirectClickStringForMultiChannels(SiteId, PageUrl));
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, false, PageUrl));
                }
            }
        }
Example #55
0
    private void BindGrdApplicationsPersons()
    {
        GrdApplicationsPersons.DataSource = null;
        GrdApplicationsPersons.DataBind();

        PnlSearch.BindControls(FilterDictionary, _TableName);

        FilterDictionary = new Dictionary <string, object>()
        {
            { "OrganizationsID", int.Parse(DListFltOrganizations.SelectedValue) },
            { "ID", TxtFltPersonID.Text },
            { "ApplicationsID", TxtFltApplicationsID.Text },
            { "ApplicationsTypesID", int.Parse(DListFltApplicationsTypes.SelectedValue) },
            { "ApplicationsPersonsTypesID", int.Parse(DListFltApplicationsPersonsType.SelectedValue) },
            { "DocumentTypesID", int.Parse(DListFltDocumentTypes.SelectedValue) },
            { "DocumentNumber", TxtFltDocumentNumber.Text },
            { "Surname(LIKE)", TxtFltSurname.Text },
            { "Name(LIKE)", TxtFltName.Text },
            { "Patronymic(LIKE)", TxtFltPatronymic.Text },
            { "SocialStatusID", int.Parse(DListFltSocialStatusID.SelectedValue) },
            { "RegisteredAddress(LIKE)", TxtFilterRegisteredAddress.Text },
            { "CurrentAddress(LIKE)", TxtFilterCurrentAddress.Text },
            { "Add_Dt(Between)", Config.DateTimeFilter(TxtFilterDate1.Text, TxtFilterDate2.Text) },
        };

        if (PnlOperations.Visible == true)
        {
            //Əməliyyatlar multi secim oldugu ucun onun axtarish algoritmasini elave olaraq burda yazdim
            for (int i = 0; i < DListFltListOperationTypes.Items.Count; i++)
            {
                ListItem Item = DListFltListOperationTypes.Items[i];
                if (Item.Selected == true)
                {
                    FilterDictionary.Add(((Tools.ListOperationTypes) int.Parse(Item.Value)).ToDescriptionString() + "(OR)", "IS NOT NULL");
                }
            }
        }
        else
        {
            switch (Config._GetQueryString("type"))
            {
            case "sibr-evaluations":
                FilterDictionary.Add("SIBRID", "IS NOT NULL");
                ((Literal)Master.FindControl("LtrTitle")).Text = "SIB-R Qiymətləndirilənlər";
                break;

            case "evaluations":
                FilterDictionary.Add("EvaluationsID", "IS NOT NULL");
                ((Literal)Master.FindControl("LtrTitle")).Text = "Qiymətləndirilənlər";
                break;

            case "evaluationsskill":
                FilterDictionary.Add("EvaluationsSkillID", "IS NOT NULL");
                ((Literal)Master.FindControl("LtrTitle")).Text = "Qiymətləndirilənlər";
                break;

            case "services":
                FilterDictionary.Add("ApplicationsPersonsServicesID", "IS NOT NULL");
                ((Literal)Master.FindControl("LtrTitle")).Text = "Xidmətlərdən istifadə edənlər";
                break;

            case "case":
                FilterDictionary.Add("ApplicationsCaseID", "IS NOT NULL");
                ((Literal)Master.FindControl("LtrTitle")).Text = "CASE açılanlar";
                break;

            default:
                break;
            }
        }

        int PageNum;
        int RowNumber = 20;

        if (!int.TryParse(Config._GetQueryString("p"), out PageNum))
        {
            PageNum = 1;
        }

        HdnPageNumber.Value = PageNum.ToString();

        DALC.DataTableResult FilterList = DALC.GetFilterList(_TableName, FilterDictionary, PageNum, RowNumber);

        if (FilterList.Count == -1)
        {
            return;
        }

        if (FilterList.Dt.Rows.Count < 1 && PageNum > 1)
        {
            Config.RedirectURL(string.Format("/tools/applicationspersons/?p={0}", PageNum - 1));
        }

        LblCount.Text = string.Format("Axtarış üzrə nəticə: {0}", FilterList.Count);
        int Total_Count = 0;

        if (FilterList.Count % RowNumber > 0)
        {
            Total_Count = (FilterList.Count / RowNumber) + 1;
        }
        else
        {
            Total_Count = FilterList.Count / RowNumber;
        }

        HdnTotalCount.Value = Total_Count.ToString();
        PnlPager.Visible    = FilterList.Count > RowNumber;
        GrdApplicationsPersons.DataSource = FilterList.Dt;
        GrdApplicationsPersons.DataBind();
    }
        private void loadEnterpriseFields()
        {
            Guid siteGuid = SPContext.Current.Site.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = SPContext.Current.Site)
                {
                    try
                    {
                        WebSvcCustomFields.CustomFields cf = new WebSvcCustomFields.CustomFields();
                        cf.Url = SPContext.Current.Site.Url + "/_vti_bin/PSI/customfields.asmx";
                        cf.UseDefaultCredentials = true;

                        WebSvcCustomFields.CustomFieldDataSet dsF = cf.ReadCustomFieldsByEntity(new Guid(PSLibrary.EntityCollection.Entities.TaskEntity.UniqueId));

                        ddlAssignedToField.Items.Add(new ListItem("[Not Specified]", ""));
                        ddlTimesheet.Items.Add(new ListItem("[Select Field]", ""));
                        ddlTimesheetHours.Items.Add(new ListItem("[Select Field]", ""));

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 21"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_UID"].ToString());
                            ddlAssignedToField.Items.Add(li);
                        }

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 15"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_ID"].ToString());
                            ddlTimesheetHours.Items.Add(li);
                        }

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 17"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_UID"].ToString());
                            ddlTimesheet.Items.Add(li);
                        }

                        ddlTimesheetHours.Items.Add(new ListItem("Actual Work", "251658250"));

                        using (var connection = new SqlConnection(CoreFunctions.getConnectionString(site.WebApplication.Id)))
                        {
                            connection.Open();

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='AssignedToField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlAssignedToField.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='TimesheetField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlTimesheet.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='TimesheetHoursField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlTimesheetHours.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='LockSynch'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkLockSynch.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ForceWS'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkForceWS.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ValidTemplates'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        loadTemplates(reader.GetString(0));
                                    }
                                    else
                                    {
                                        loadTemplates(string.Empty);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='CrossSite'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkCrossSite.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='DefaultURL'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        txtDefaultURL.Text = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ConnectedURLs'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        txtUrls.Text = reader.GetString(0);
                                    }
                                }
                        }

                        lblError.Visible = false;

                        WebSvcEvents.Events events = new EPMLiveEnterprise.WebSvcEvents.Events();
                        events.Url = SPContext.Current.Site.Url + "/_vti_bin/psi/events.asmx";
                        events.UseDefaultCredentials = true;

                        WebSvcEvents.EventHandlersDataSet ds = events.ReadEventHandlerAssociations();

                        if (ds.EventHandlers.Select("EventId = 53 and name = 'EPMLivePublisher'").Length <= 0)
                        {
                            lblProjectPublished.Text = "Not Installed";
                        }
                        else
                        {
                            lblProjectPublished.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 133 and name = 'EPMLiveStatusing'").Length <= 0)
                        {
                            lblStatusingApplied.Text = "Not Installed";
                        }
                        else
                        {
                            lblStatusingApplied.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 95 and name = 'EPMLiveResUpdated'").Length <= 0)
                        {
                            lblResUpdated.Text = "Not Installed";
                        }
                        else
                        {
                            lblResUpdated.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 89 and name = 'EPMLiveResCreated'").Length <= 0)
                        {
                            lblResCreated.Text = "Not Installed";
                        }
                        else
                        {
                            lblResCreated.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 92 and name = 'EPMLiveResDeleting'").Length <= 0)
                        {
                            lblResDeleted.Text = "Not Installed";
                        }
                        else
                        {
                            lblResDeleted.Text = "Installed";
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("401"))
                        {
                            lblError.Text    = "Error: 401 Unauthorized<br>This usually means the service account that is current running your SharePoint Application Pool does not have access to the Project Server Site.";
                            lblError.Visible = true;
                        }
                        else
                        {
                            Response.Write("Error: " + ex.Message + "<br>Current User: " + HttpContext.Current.User.Identity.Name);
                        }
                    }
                }
            });
        }
Example #57
0
 protected void Page_Load(object sender, EventArgs e)
 {
     this.TxtImageText.Columns = DataConverter.CLng(base.Settings[0]);
     this.m_ShowUploadFilePath = base.BasePath;
     this.m_ShowUploadFilePath = this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority + this.m_ShowUploadFilePath;
     if (base.IsAdminManage || PEContext.Current.User.Identity.IsAuthenticated)
     {
         if (base.IsAdminManage)
         {
             this.m_ShowUploadFilePath = this.m_ShowUploadFilePath + SiteConfig.SiteOption.ManageDir;
         }
         else
         {
             this.m_ShowUploadFilePath = this.m_ShowUploadFilePath + "User";
         }
         this.m_JSPrefix  = this.ClientID.Replace("$", "").Replace("_", "");
         this.m_FieldName = base.FieldName;
         if (DataConverter.CBoolean(base.Settings[3]) && base.IsAdminManage)
         {
             this.LblIsFromSelected.Text = "<input type=\"button\" class=\"button\" value=\"从已上传文件中选择\" onclick=\"" + this.m_JSPrefix + "SelectFiles();\" /><br />";
         }
         StringBuilder builder = new StringBuilder();
         if ((base.Settings.Count < 7) || (DataConverter.CBoolean(base.Settings[6]) && this.Visible))
         {
             builder.Append("<tr class='tdbg'><td valign=\"middle\" style=\"width: 12%;\" align=\"right\" >上传图片 :&nbsp;</td>");
             builder.Append("<td align=\"left\" style=\"width: 88%;\"><iframe id=\"" + this.m_JSPrefix + "Upload\" src=\"\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" width=\"80%\" height=\"30px\" scrolling=\"no\"></iframe></td></tr>");
             StringBuilder builder2 = new StringBuilder();
             builder2.Append("<script type=\"text/javascript\">");
             builder2.Append(" var nodeId = document.getElementById(nodeIdClientId).value;");
             builder2.Append(" document.getElementById('" + this.m_JSPrefix + "Upload').src = \"" + this.m_ShowUploadFilePath + "/Accessories/FileUpload.aspx?ReturnJSFunction=" + this.m_JSPrefix + "DealwithUpload&ModuleName=Node&NodeId=\"+nodeId+\"&ModelId=" + base.Request["ModelId"] + "&FieldName=" + this.m_FieldName + "\";");
             builder2.Append("</script>");
             this.Page.ClientScript.RegisterStartupScript(base.GetType(), this.m_JSPrefix + "Upload", builder2.ToString());
         }
         if ((base.Settings.Count > 6) && (base.FieldLevel == 0))
         {
             StringBuilder builder3 = new StringBuilder();
             builder3.Append("<script type=\"text/javascript\">");
             builder3.Append(" function homeImageAssignment(path){");
             builder3.Append(" document.getElementById('" + this.TxtImageText.ClientID + "').value = path;");
             builder3.Append(this.m_JSPrefix + "AddItem(path);");
             builder3.Append(" }");
             builder3.Append("</script>");
             this.Page.ClientScript.RegisterStartupScript(base.GetType(), this.m_JSPrefix + "Assignment", builder3.ToString());
         }
         if ((base.Settings.Count > 7) && DataConverter.CBoolean(base.Settings[7]))
         {
             this.ShowUploadFiles.Style.Add("display", "");
             StringBuilder builder4 = new StringBuilder();
             builder4.Append("document.getElementById(\"" + this.TxtImageText.ClientID + "\").value =this.value;eImgPreview.src=((this.value == '') ? '../../../Images/nopic.gif' : '");
             if (string.Compare(base.Request.ApplicationPath, "/", StringComparison.Ordinal) != 0)
             {
                 builder4.Append(base.Request.ApplicationPath + "/" + this.m_UploadDir);
             }
             else
             {
                 builder4.Append("/" + this.m_UploadDir);
             }
             builder4.Append("' + this.value);");
             this.DropUploadFiles.Attributes.Add("onchange", builder4.ToString());
             if (!string.IsNullOrEmpty(this.UploadFiles))
             {
                 foreach (string str in this.UploadFiles.Split(new char[] { '|' }))
                 {
                     ListItem item = new ListItem(str, str);
                     this.DropUploadFiles.Items.Add(item);
                     if (str == this.FieldValue)
                     {
                         this.DropUploadFiles.SelectedValue = item.Value;
                     }
                 }
             }
         }
         this.LblUpload.Text = builder.ToString();
     }
     if (!base.IsPostBack)
     {
         this.TxtImageText.Text = this.FieldValue;
     }
     else
     {
         this.FieldValue = this.TxtImageText.Text;
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Get the user id for check state of sign in
            HttpCookie myCookie = new HttpCookie("cook");

            myCookie = Request.Cookies["cook"];
            string userID = null;

            try
            {
                userID = myCookie.Values["UserID"].Replace(" ", string.Empty);
            }
            catch (Exception exep)
            {
                //Response.Write(exep.ToString());
                //Label1.Text = "尚未登入,無法進行投票";
                //Label1.Visible = true;
                exep.ToString();

                //return;
            }

            topic_click = Request.QueryString["topic"];
            if (topic_click == null)
            {
                return;
            }

            _Default.MySQLconnect();
            Sqlconnect = _Default.GetSqlConnection();
            string        SQLquery        = @"SELECT * FROM Online_Polling_DB.dbo.[vote] WHERE topic = '" + topic_click + "' ;";
            SqlCommand    MyCommand       = new SqlCommand(SQLquery, Sqlconnect);
            SqlDataReader MysqlDataReader = MyCommand.ExecuteReader();

            MysqlDataReader.Read();

            string option_IN;

            string topic          = MysqlDataReader["topic"].ToString().Replace(" ", string.Empty);
            string description_IN = MysqlDataReader["description"].ToString().Replace(" ", string.Empty);

            Label1.Text  = "主題 : " + topic + "<br />";
            Label1.Text += "敘述 : " + description_IN + "<br />";

            //read all
            do
            {
                if (MysqlDataReader["option"].ToString() != "")
                {
                    option_IN = MysqlDataReader["option"].ToString().Replace(" ", string.Empty);
                    ListItem temp = new ListItem(option_IN);
                    if (topic_click.Equals(topic))
                    {
                        if (!CheckBoxList1.Items.Contains(temp))
                        {
                            CheckBoxList1.Items.Add(option_IN);
                        }
                    }
                }
            } while (MysqlDataReader.Read());
            MysqlDataReader.Close();
        }
Example #59
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DtDoj.MaxDate = DateTime.Now;
            DtDOP.MaxDate = DateTime.Now;
            if (!Page.IsPostBack)
            {
                try
                {
                    var deplist = SPContext.Current.Web.Lists.TryGetList(Utilities.Department);

                    if (deplist != null)
                    {
                        DdlDep.Items.Clear();
                        DdlDep.Items.Add("--Select--");
                        var collection = deplist.GetItems();
                        foreach (SPListItem item in collection)
                        {
                            DdlDep.Items.Add(item["Department"].ToString());
                        }
                    }
                    var desiglist = SPContext.Current.Web.Lists.TryGetList(Utilities.Designation);

                    if (desiglist != null)
                    {
                        DdlDesignation.Items.Clear();
                        DdlDesignation.Items.Add("--Select--");
                        var collection = desiglist.GetItems();
                        foreach (SPListItem item in collection)
                        {
                            DdlDesignation.Items.Add(item["Designation"].ToString());
                        }
                    }
                    var leavetypelist = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeType);

                    if (leavetypelist != null)
                    {
                        DdlEmptype.Items.Clear();
                        DdlEmptype.Items.Add("--Select--");
                        var collection = leavetypelist.GetItems();
                        foreach (SPListItem item in collection)
                        {
                            DdlEmptype.Items.Add(item["Title"].ToString());
                        }
                    }

                    var managerlist   = SPContext.Current.Web.Lists.TryGetList(Utilities.ReportingTo);
                    var Activemanager = GetListItemCollection(managerlist, "Manager Status", "Active");

                    if (Activemanager != null)
                    {
                        ddlReportingTo.Items.Clear();
                        ddlReportingTo.Items.Add("--Select--");

                        foreach (SPListItem item in Activemanager)
                        {
                            var spv      = new SPFieldLookupValue(item["Reporting Managers"].ToString());
                            var listItem = new ListItem(spv.LookupValue,
                                                        item["Reporting Managers"].ToString());
                            ddlReportingTo.Items.Add(listItem);
                        }
                    }
                    var empid = System.Web.HttpContext.Current.Request.QueryString["EmpId"];
                    var inActivemanagerlist = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen);
                    var empitem             = inActivemanagerlist.GetItemById(Convert.ToInt16(empid));
                    empSPid.Value = empid;

                    txtempid.Text = empitem["Title"].ToString();
                    var curemp = txtempid.Text;

                    var InActivemanager = GetListItemCollection(inActivemanagerlist, "Employee ID", curemp, "Status", "In Active");
                    if (InActivemanager.Count > 0)
                    {
                        ddlReportingTo.Enabled = false;
                    }

                    var currentYear = SPContext.Current.Web.Lists.TryGetList(Utilities.CurrentYear).GetItems();
                    foreach (SPListItem currentYearValue in currentYear)
                    {
                        hdnCurrentYear.Value = currentYearValue["Title"].ToString();
                    }
                    var financialStartMont = SPContext.Current.Web.Lists.TryGetList(Utilities.Financialstartmonth).GetItems();
                    foreach (SPListItem finStrtmonth in financialStartMont)
                    {
                        hdnStrtFnclMnth.Value = finStrtmonth["Title"].ToString();
                    }
                    EmployeeDetails();
                }
                catch (Exception ex)
                {
                    LblError.Text = ex.Message;
                }
            }
        }
    /// <summary>
    /// Method to add Answers to the answer list box. This button will also work
    /// in combination with the edit button to resubmit and edited answer.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAddAnswer_Click(object sender, EventArgs e)
    {
        ansEditIndex = Convert.ToInt32(Session["ansEditIndex"]);
        // regular expression to enure only numbers are entered in the rank text field.
        Regex reg = new Regex(@"^[-10123456789]+$");

        if (tbAnswer.Text.Equals(string.Empty) || tbScore.Text.Equals(string.Empty) || (!reg.IsMatch(tbScore.Text))) {
            lblErrorAdd.Visible = true;
        }
        else {
            lblErrorAdd.Visible = false;
            //
            if (tbQuestion.Enabled == false) {
                lbAnswerList.Items[ansEditIndex].Text = tbAnswer.Text + " [" + tbScore.Text + "]";
                tbQualDesc.Enabled = true;
                tbQuestion.Enabled = true;
                lbAnswerList.Enabled = true;
                btnRemove.Enabled = true;
                btnClear.Enabled = true;
                btnEdit.Enabled = true;
                btnContinue.Enabled = true;
                btnFinished.Enabled = true;
                ansEditIndex = 0;

            }
            else {
                //the -1 should be the answer id if it has one
                ListItem item = new ListItem(tbAnswer.Text + " [" + tbScore.Text + "]", ((lbAnswerList.Items.Count+1)*-1).ToString());
                lbAnswerList.Items.Add(item);
            }

            tbAnswer.Text = string.Empty;
            tbScore.Text = string.Empty;
        }
    }