Example #1
0
    public void LoadData(int ObjectID)
    {
        if (!Page.IsPostBack)
        {
            List<BSTerm> terms = BSTerm.GetTerms(TermType);
            if (terms.Count > 0)
            {
                cblCats.DataSource = terms;
                cblCats.DataMember = "TermID";
                cblCats.DataTextField = "Name";
                cblCats.DataValueField = "TermID";
                cblCats.DataBind();
            }
            else
            {
                LiteralControl lC = new LiteralControl();
                lC.Text = Language.Admin["CategoryNotFound"] + "<br><br><a href=\"Categories.aspx?#Add\">" + Language.Admin["AddNewCategory"] + "</a>";
                divCats.Controls.Add(lC);
            }

            if (ObjectID != 0)
            {
                List<BSTerm> objectTerms = BSTerm.GetTermsByObjectID(ObjectID, TermType);
                foreach (BSTerm objectTerm in objectTerms)
                {
                    if (cblCats.Items.FindByValue(objectTerm.TermID.ToString()) != null)
                    {
                        cblCats.Items.FindByValue(objectTerm.TermID.ToString()).Selected = true;
                    }
                }
            }
        }
    }
Example #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
		//TO fix the bug related TO Perisan Culture
		if (System.Threading.Thread.CurrentThread.CurrentCulture.LCID == 1065)
			System.Threading.Thread.CurrentThread.CurrentCulture = new PersianCulture();
        // for supported of RTL languages
        if (Resources.labels.LangDirection.Equals("rtl", StringComparison.OrdinalIgnoreCase))
        {
            var lc = new LiteralControl("<link href=\"" + Utils.RelativeWebRoot + "Custom/Themes/Standard/css/rtl.css\" rel=\"stylesheet\" />");
            HeadContent.Controls.Add(lc);
        }

        // needed to make <%# %> binding work in the page header
        Page.Header.DataBind();

        if (Security.IsAuthenticated)
        {
            aLogin.InnerText = Resources.labels.logoff;
            aLogin.HRef = Utils.RelativeWebRoot + "Account/login.aspx?logoff";
        }
        else
        {
            aLogin.HRef = Utils.RelativeWebRoot + "Account/login.aspx";
            aLogin.InnerText = Resources.labels.login;
        }
    }
    //add the nav links to the placeholder
    private void writeNavLink(UserLink link)
    {
        String element = "<a href='" + link.getPath() + "'><div class='nav-item'>" + link.getTextValue() + "</div></a>";
        LiteralControl userLink = new LiteralControl(element);

        PlaceHolder1.Controls.Add(userLink);
    }
Example #4
0
 public void LoadLottoery(string DrawNum, string WinNum)
 {
     lbLottoName.Text = LotteryName;
     hlLotto.NavigateUrl = LotteryUrl;
     lbDrawNumber.Text = DrawNum;
     
     string[] wNum = WinNum.Split('+');
     string[] rdNum = wNum[0].Trim().Split(' ');
     LiteralControl lcRed = new LiteralControl();    
     for (int i = 0; i < rdNum.Length; i++)
     {
         lcRed.Text += "<span class=\"b b_png b_p2\">" + rdNum[i].Trim() + "</span>";
     }
     phWinNumRed.Controls.Add(lcRed);
     if (WinNum.IndexOf('+') > 0)
     {
         LiteralControl lcBlue = new LiteralControl();
         string[] blNum = wNum[1].Trim().Split(' ');
         for (int i = 0; i < blNum.Length; i++)
         {
             lcBlue.Text += "<span class=\"b b_png b_p1\">" + blNum[i].Trim() + "</span>";
         }
         phWinNumBlue.Controls.Add(lcBlue);
     }
 }
    public void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridCommandItem)
        {
            GridCommandItem commandItem = (e.Item as GridCommandItem);
            PlaceHolder container = (PlaceHolder)commandItem.FindControl("PlaceHolder1");
            Label label = new Label();
            label.Text = "&nbsp;&nbsp;";

            container.Controls.Add(label);

            for (int i = 65; i <= 65 + 25; i++)
            {
                LinkButton linkButton1 = new LinkButton();

                LiteralControl lc = new LiteralControl("&nbsp;&nbsp;");

                linkButton1.Text = "" + (char)i;

                linkButton1.CommandName = "alpha";
                linkButton1.CommandArgument = "" + (char)i;

                container.Controls.Add(linkButton1);
                container.Controls.Add(lc);
            }

            LiteralControl lcLast = new LiteralControl("&nbsp;");
            container.Controls.Add(lcLast);

            LinkButton linkButtonAll = new LinkButton();
            linkButtonAll.Text = "Tất cả";
            linkButtonAll.CommandName = "NoFilter";
            container.Controls.Add(linkButtonAll);
        }
    }
    private void writeNaveLink(Links link)
    {
        String element = "<a href='" + link.getPath() + "'><div class='nav-item'>" + link.getLinkText() + "</div></a>";
        LiteralControl userLink = new LiteralControl(element);

        linksPlaceHolder.Controls.Add(userLink);
    }
Example #7
0
		private static void PopulateWebPageObject(SourceWebPage pageObject, CSClass classObject)
		{
			pageObject.ClassFullName = classObject.ClassFullName;
			foreach (var fieldObject in classObject.FieldList)
			{
				switch (fieldObject.TypeFullName)
				{
					case "System.Web.UI.WebControls.Literal":
						{
							var control = new LiteralControl
							{
								FieldName = fieldObject.FieldName,
								ClassName = fieldObject.TypeName,
								NamespaceName = fieldObject.TypeNamespace
							};
							pageObject.Controls.Add(control);
						}
						break;
					default:
						{
							var control = new SourceWebControl()
							{
								FieldName = fieldObject.FieldName,
								ClassName = fieldObject.TypeName,
								NamespaceName = fieldObject.TypeNamespace
							};
							pageObject.Controls.Add(control);
						}
						break;
				}
			}
		}
Example #8
0
    public override void LoadWidget()
    {
        StringDictionary settings = GetSettings();
        int numberOfPosts = DEFAULT_NUMBER_OF_POSTS;
        if (settings.ContainsKey("numberofposts"))
            numberOfPosts = int.Parse(settings["numberofposts"]);

        if (HttpRuntime.Cache["widget_recentposts"] == null)
        {

            List<Post> visiblePosts = Post.Posts.FindAll(delegate(Post p)
            {
                return p.IsVisibleToPublic;
            });

            int max = Math.Min(visiblePosts.Count, numberOfPosts);
            List<Post> list = visiblePosts.GetRange(0, max);
            HttpRuntime.Cache.Insert("widget_recentposts", list);
        }

        string content = RenderPosts((List<Post>)HttpRuntime.Cache["widget_recentposts"], settings);

        LiteralControl html = new LiteralControl(content); //new LiteralControl((string)HttpRuntime.Cache["widget_recentposts"]);
        phPosts.Controls.Add(html);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // for supported of RTL languages
        if (Resources.labels.LangDirection.Equals("rtl", StringComparison.OrdinalIgnoreCase))
        {
            var lc = new LiteralControl("<link href=\"/themes/standard/include/rtl.css\" rel=\"stylesheet\" />");
            HeadContent.Controls.Add(lc);
        }

        // needed to make <%# %> binding work in the page header
        Page.Header.DataBind();
        if (!Utils.IsMono)
        {
            var lc = new LiteralControl("\n<!--[if lt IE 9]>" +
                "\n<script type=\"text/javascript\" src=\"/themes/standard/include/html5.js\"></script>" +
                "\n<![endif]-->\n");
            HeadContent.Controls.Add(lc);
        }
        if (Security.IsAuthenticated)
        {
            aLogin.InnerText = Resources.labels.logoff;
            aLogin.HRef = Utils.RelativeWebRoot + "Account/login.aspx?logoff";
        }
        else
        {
            aLogin.HRef = Utils.RelativeWebRoot + "Account/login.aspx";
            aLogin.InnerText = Resources.labels.login;
        }
    }
Example #10
0
    public override void LoadWidget()
    {
        StringDictionary settings = GetSettings();
        int numberOfComments = DEFAULT_NUMBER_OF_COMMENTS;
        if (settings.ContainsKey("numberofcomments"))
            numberOfComments = int.Parse(settings["numberofcomments"]);

        if (HttpRuntime.Cache["widget_recentcomments"] == null)
        {
            List<Comment> comments = new List<Comment>();

            foreach (Post post in Post.Posts)
            {
                if (post.IsVisible)
                {
                    comments.AddRange(post.Comments.FindAll(delegate(Comment c) { return c.IsApproved && c.Email.Contains("@"); }));
                }
            }

            comments.Sort();
            comments.Reverse();

            int max = Math.Min(comments.Count, numberOfComments);
            List<Comment> list = comments.GetRange(0, max);
            HttpRuntime.Cache.Insert("widget_recentcomments", list);
        }

        string content = RenderComments((List<Comment>)HttpRuntime.Cache["widget_recentcomments"], settings);

        LiteralControl html = new LiteralControl(content); //new LiteralControl((string)HttpRuntime.Cache["widget_recentcomments"]);
        phPosts.Controls.Add(html);
    }
Example #11
0
    private void CargarCarusel()
    {
        List<EntPelicula> lst = new List<EntPelicula>();
        lst = new BusPelicula().ObtenerEstrenos();
        LiteralControl literal = new LiteralControl();
        LiteralControl literal2 = new LiteralControl();
        literal.Text = "";
        literal2.Text = "";
        int contador = 0;

        foreach (EntPelicula ent in lst)
        {
            if (contador == 0)
                literal.Text += " <li data-target=\"#myCarousel\" data-slide-to=\"" + contador + "\" class=\"active\"></li>";

            else
                literal.Text += " <li data-target=\"#myCarousel\" data-slide-to=\"" + contador + "\" ></li>";

            if (contador == 0)
                literal2.Text += "<div  class=\"item active\">";
            else
                literal2.Text += "<div  class=\"item\">";

            literal2.Text += "       <img src=\"" + ent.FotoPortada + "\" style=\"margin: auto\" />";
            literal2.Text += "                            </div>";

            contador++;
        }
        phSliderUno.Controls.Add(literal);
        phSliderDos.Controls.Add(literal2);
    }
 protected void Page_Load(object sender, EventArgs e)
 {
     con.ConnectionString = ConfigurationManager.ConnectionStrings["la"].ConnectionString;
     con.Open();
     s = "Select * from questions where q_id=" +Request.QueryString["q_id"];
     dr = new SqlDataAdapter(s,con);
     dr.Fill(ds);
     s = ds.Tables[0].Rows[0]["title"].ToString();
     category_title.Text = s;
     s = ds.Tables[0].Rows[0]["q_body"].ToString();
     textDisplay.Text = s;
     
     pdate.Text = "post date: " + ds.Tables[0].Rows[0]["postdate"].ToString();
     Author.Text = "posted by: " + ds.Tables[0].Rows[0]["u_name"].ToString();
     n = (int)ds.Tables[0].Rows[0]["q_id"];
     s = "Select * from answers where q_id=" + n;
     commentscmd = new SqlCommand(s,con);
     commentReader=commentscmd.ExecuteReader();
     while (commentReader.Read())
     {
         LiteralControl t = new LiteralControl(commentReader["ans_body"].ToString());
         Label l = new Label(),l2=new Label();
         l.Text = commentReader["u_name"].ToString()+":";
         l.Style.Add("font-family", "Arial Black");
         l.Style.Add("font-style", "italic");
         l.Style.Add("font-weight", "bold");
         ph.Controls.Add(l);
         ph.Controls.Add(new LiteralControl("<br />"));
         ph.Controls.Add(t);
         ph.Controls.Add(new LiteralControl("<hr size=\"2pt\" />"));
        
        
     }
     con.Close();
 }
Example #13
0
    public void cargarcarrucel2()
    {
        List<entPelicula> lst = new List<entPelicula>();
        lst = new busPelicula().ObtenerEstrenos();

        LiteralControl literalTres = new LiteralControl();

        LiteralControl literalCua = new LiteralControl();
        literalTres.Text = "";
        literalCua.Text = "";
        int contador = 0;

        foreach (entPelicula ent in lst)
        {

            if (contador == 0)
                literalTres.Text += "<li data-target=\"#carouselUno\" data-slide-to=\"" + contador + "\" class=\"active\"></li>";
            else
                literalTres.Text += "<li data-target=\"#carouselUno\" data-slide-to=\"" + contador + "\"></li>";
            if (contador == 0)
                literalCua.Text += "<div class=\"item active\">";
            else
                literalCua.Text += "<div class=\"item\">";
            literalCua.Text += " <img src=\"" + ent.FotoPortada + "\" style=\"height:200px; width:400px; margin:auto;\"/>";
            literalCua.Text += " <span class=\"style\"><strong>" + ent.Nombre + "</strong></span>";
            literalCua.Text += "  <div class=\"carousel-caption\">";

            literalCua.Text += "  </div>";
            literalCua.Text += "</div>";

            contador++;
        }
        ph1.Controls.Add(literalTres);
        ph2.Controls.Add(literalCua);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(MapPath(sSERVICES));
        string sFloat = "floatLeft";
        if (User.Identity.IsAuthenticated)
        {
            LiteralControl lcTemp = new LiteralControl("<br />");
            services.Controls.Add(lcTemp);
            Button btnAddService = new Button();
            btnAddService.PostBackUrl = "http://www.fordscleaning.com/admin/AddEditService.aspx";
            btnAddService.UseSubmitBehavior = false;
            btnAddService.CausesValidation = false;
            btnAddService.Text = "Add New Service";
            btnAddService.ID = "btnAddeNewService";
            services.Controls.Add(btnAddService);
        }
        LiteralControl lc = new LiteralControl("<br /><table width=\"100%\">");
        services.Controls.Add(lc);
        int iX = 0;
        while (!sr.EndOfStream)
        {
            string sServiceAnchor = sr.ReadLine();
            string sServiceName = sr.ReadLine();
            string sServiceImage = sr.ReadLine();
            string sServiceSummary = sr.ReadLine();

            lc = new LiteralControl("<tr><td><div class=\"serviceTitle\"><table width=\"100%\"><tr><td><a style=\"color:#ffffff;\" href=\"http://www.fordscleaning.com/Service.aspx?sid=" + sServiceAnchor + "\" name=\"" + sServiceAnchor + "\">" + sServiceName + "</a></td><td style=\"text-align:right;\">");
            services.Controls.Add(lc);
            if (User.Identity.IsAuthenticated)
            {
                Button btnEdit = new Button();
                btnEdit.Text = "Edit";
                btnEdit.UseSubmitBehavior = false;
                btnEdit.CausesValidation = false;
                btnEdit.ID = "Edit" + sServiceAnchor;
                btnEdit.PostBackUrl = "http://www.fordscleaning.com/admin/AddEditService.aspx?Service=" + iX;
                services.Controls.Add(btnEdit);
            }
            lc = new LiteralControl("</td></tr></table></div>");
            services.Controls.Add(lc);
            if (sServiceImage != "No Image.")
            {
                Image img = new Image();
                img.ImageUrl = "http://www.fordscleaning.com/MakeThumbnail.aspx?Image=ServiceImages/" + sServiceImage + "&Size=250";
                img.CssClass = sFloat;
                services.Controls.Add(img);
            }
            lc = new LiteralControl("&nbsp &nbsp &nbsp " + sServiceSummary + "</td></tr>");
            services.Controls.Add(lc);
            if (sFloat == "floatLeft")
                sFloat = "floatRight";
            else
                sFloat = "floatLeft";
            iX++;
        }
        lc = new LiteralControl("</table>");
        services.Controls.Add(lc);
        sr.Close();
    }
Example #15
0
    protected void CreateButton_OnClick(object sender, EventArgs e)
    {
        MembershipCreateStatus userStatus;
        Membership.CreateUser(UserNameText.Text, PassText.Text, EmailText.Text, QuestionText.Text, AnswerText.Text, ActiveUser.Checked,
                                out userStatus);

        if (userStatus == MembershipCreateStatus.Success)
        {
            foreach (var control in CheckBoxRoles.Controls)
            {
                if (control is CheckBox)
                {
                    CheckBox box = (CheckBox)control;

                    if (box.Checked)
                    {
                        System.Web.Security.Roles.AddUserToRole(UserNameText.Text, box.ID);
                    }
                }
            }

            //additionally add userID to user_info table
            Activation.addToUserInfoTable(UserNameText.Text);

            UserNameText.Text = "";
            PassText.Text = "";
            PassConfirmText.Text = "";
            EmailText.Text = "";
            QuestionText.Text = "";
            AnswerText.Text = "";

            foreach (var control in CheckBoxRoles.Controls)
            {
                if (control is CheckBox)
                {
                    CheckBox box = (CheckBox)control;

                    box.Checked = false;
                }

            }

            LiteralControl literalControl = new LiteralControl("<p>User Successfully Added.</p>");
            PopUpText.Controls.Add(literalControl);
            CreateButton_ModalPopupExtender.Show();
        }
        else if (userStatus == MembershipCreateStatus.InvalidPassword)
        {
            LiteralControl literalControl = new LiteralControl("<p>Password must be a minimum of 6 characters.</p>");
            PopUpText.Controls.Add(literalControl);
            CreateButton_ModalPopupExtender.Show();
        }
        else if (userStatus == MembershipCreateStatus.DuplicateUserName)
        {
            LiteralControl literalControl = new LiteralControl("<p>This username is already in use.</p>");
            PopUpText.Controls.Add(literalControl);
            CreateButton_ModalPopupExtender.Show();
        }
    }
    private void printViewItem(InventoryItem item)
    {
        InventoryHtmlPrinter printer = new InventoryHtmlPrinter(item);
        String itemHtml = printer.getViewItemHtml(item);

        LiteralControl control = new LiteralControl(itemHtml);
        productsPlaceHolder.Controls.Add(control);
    }
 private void getLinks(int lastItemNumber, int firstItem)
 {
     List<int> itemIds = InventoryManager.getTotalItems();
     InventoryHtmlPrinter printer = new InventoryHtmlPrinter();
     String links = printer.getInventoryLinkHTML(lastItemNumber, firstItem, itemIds);
     LiteralControl control = new LiteralControl(links);
     productsLinksPlaceHolder.Controls.Add(control);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
       
        con.ConnectionString = ConfigurationManager.ConnectionStrings["la"].ConnectionString;
        con.Open();
        s = "Select * from articles where title='" +Request.QueryString["title"]+"'";
        dr = new SqlDataAdapter(s,con);
        dr.Fill(ds);
        s = ds.Tables[0].Rows[0]["title"].ToString();
        category_title.Text = s;
        Page.Title = s;
        s = ds.Tables[0].Rows[0]["a_body"].ToString();
        textDisplay.Text = s;
        
        pdate.Text = "post date: " + ds.Tables[0].Rows[0]["postdate"].ToString();

        rs = "SELECT SUM(rating) As RatingSum, COUNT(*) As RatingCount FROM ratings WHERE a_id=" + (int)ds.Tables[0].Rows[0]["a_id"];
        rdr = new SqlDataAdapter(rs, con);
        rdr.Fill(rds);
        if ((int)rds.Tables[0].Rows[0]["RatingCount"] == 0)
        {
            rating.Text = "RATING: not rated";
            Image1.Visible = false;
        }
        else
        {
            rating.Text = "RATING:" + (int)rds.Tables[0].Rows[0]["RatingSum"] / (int)rds.Tables[0].Rows[0]["RatingCount"];
            Image1.Visible = true;
        }
        Author.Text = "posted by: " + ds.Tables[0].Rows[0]["u_name"].ToString();
        n = (int)ds.Tables[0].Rows[0]["a_id"];
        s = "Select * from comments where a_id=" + n;
        commentscmd = new SqlCommand(s,con);
        commentReader=commentscmd.ExecuteReader();
        while (commentReader.Read())
        {
            LiteralControl t = new LiteralControl(commentReader["co_body"].ToString());
            Label l = new Label(),l2=new Label();
            Button b = new Button();
            b.ID = commentReader["co_id"].ToString();
            b.Click+=new EventHandler(b_Click);
            b.Text = "Report abuse";
            l.Text = commentReader["u_name"].ToString()+":";
            l.Style.Add("font-family", "Arial Black");
            l.Style.Add("font-style", "italic");
            l.Style.Add("font-weight", "bold");
            l2.ID = commentReader["co_id"].ToString()+"l";
            ph.Controls.Add(l);
            ph.Controls.Add(b);
            ph.Controls.Add(l2);
            ph.Controls.Add(new LiteralControl("<br />"));
            ph.Controls.Add(t);
            ph.Controls.Add(new LiteralControl("<hr size=\"2pt\" />"));
           
           
        }
        con.Close();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Id"] == null) Response.Redirect("Logon.aspx");
        string Iduser =  Convert.ToString(Session["Id"]);
        Label1.Visible = false;
        try
        {
            conexao = new MySqlConnection("server=localhost; port=3306; user id=root; password=root; database= lojaonline");
            conexao.Open();

            string sql = "SELECT produtos.*, comprasefetuadas.* from produtos INNER JOIN comprasefetuadas ON produtos.idprod=comprasefetuadas.idproduto WHERE comprasefetuadas.idusuario=@id ORDER BY produtos.nomeprod";

            stm = new MySqlCommand(sql, conexao);
            stm.Parameters.AddWithValue("@id", Iduser);
            stm.Prepare();

            dr = stm.ExecuteReader();

            String strHTML = "";
            if (dr.HasRows)
            { //mostramos o cabeçalho da <table> somente se temos registros
                strHTML = "<TABLE name=produts border=1 width='65%'> <TR style='font-size: 14px; font-family: verdana; text-align: center; font-weight: 900; color: #009;'>"
                    + "<TD>&nbsp;Código&nbsp;</TD><TD style='text-align: left'>&nbsp;Nome&nbsp;</TD>"
                    + "<TD>&nbsp;Preço&nbsp;</TD><TD>&nbsp;Quantidade&nbsp;</TD></TR>";
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "Este usuário não comprou produtos ainda nesta loja on-line";
            }

            while (dr.Read())
            {
                String codigo = dr.GetString("idprod");
                String nome = dr.GetString("nomeprod");
                String preco = dr.GetString("preco");
                String qtde = dr.GetString("qtdecomprada");
                strHTML += "<TR><TD style='font-size: 12px; font-family: verdana; text-align: center;'>" + codigo
                        + "</TD><TD style='font-size: 12px; font-family: verdana; text-align: left;'>&nbsp;&nbsp;"
                        + nome + "</TD><TD style='font-size: 12px; font-family: verdana; text-align: center;'>"
                        + preco + "</TD><TD style='font-size: 12px; font-family: verdana; text-align: center;'>"
                        + qtde + "</TD></TR>";
            }

            strHTML += "</TABLE> <br/><br/><br/>";
            LiteralControl lc = new LiteralControl(strHTML);
            Panel1.Controls.Add(lc);
            stm.Dispose();
            dr.Close();
            conexao.Close();
        }
        catch (Exception exc)
        {
            Label1.Visible = true;
            Label1.Text = "Erro no processamento do BD - " + exc.Message;
        }

    }
Example #20
0
 /// <summary>
 /// This method works as a substitute for Page_Load. You should use this method for
 /// data binding etc. instead of Page_Load.
 /// </summary>
 public override void LoadWidget()
 {
     StringDictionary settings = GetSettings();
     if (settings.ContainsKey("content"))
     {
         LiteralControl text = new LiteralControl(settings["content"]);
         this.Controls.Add(text);
     }
 }
Example #21
0
 private void AddReference(string subPath, bool script, string parms)
 {
     LiteralControl c = new LiteralControl();
     string ub = PathFunctions.GetFullPath(Request, subPath);
     if (!string.IsNullOrEmpty(parms))
         ub = ub + '?' + parms;
     c.Text = script
         ? string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", ub)
         : string.Format("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" media=\"screen\" />", ub);
     Page.Header.Controls.Add(c);
 }
    private void printItemsToPlaceHolder(List<InventoryItem> items)
    {
        foreach (InventoryItem item in items)
        {
            InventoryItem i = InventoryManager.getSingleItem(item.getInventoryId()); //price could have changed since the last time user viewed this item
            InventoryHtmlPrinter printer = new InventoryHtmlPrinter(i);
            String html = printer.getCartItemHtml();

            LiteralControl control = new LiteralControl(html);
            cartItemsPlaceholder.Controls.Add(control);
        }
    }
    public void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridCommandItem)
        {
            GridCommandItem commandItem = (e.Item as GridCommandItem);
            PlaceHolder container = (PlaceHolder)commandItem.FindControl("PlaceHolder1");
            Label label = new Label();
            label.Text = "&nbsp;&nbsp;";

            container.Controls.Add(label);

            for (int i = 65; i <= 65 + 25; i++)
            {
                LinkButton linkButton1 = new LinkButton();

                LiteralControl lc = new LiteralControl("&nbsp;&nbsp;");

                linkButton1.Text = "" + (char)i;

                linkButton1.CommandName = "alpha";
                linkButton1.CommandArgument = "" + (char)i;

                container.Controls.Add(linkButton1);
                container.Controls.Add(lc);
            }

            LiteralControl lcLast = new LiteralControl("&nbsp;");
            container.Controls.Add(lcLast);

            LinkButton linkButtonAll = new LinkButton();
            linkButtonAll.Text = "All";
            linkButtonAll.CommandName = "NoFilter";
            container.Controls.Add(linkButtonAll);
        }
        else if (e.Item is GridPagerItem)
        {
            GridPagerItem gridPager = e.Item as GridPagerItem;
            Control numericPagerControl = gridPager.GetNumericPager();

            Control placeHolder = gridPager.FindControl("NumericPagerPlaceHolder");
            placeHolder.Controls.Add(numericPagerControl);
        }
        else if (e.Item is GridNestedViewItem)
        {
            var nestedItem = (GridNestedViewItem)e.Item;
            var hdnEmail = (HiddenField)nestedItem.FindControl("hdnEmail");
            hdnEmail.Value = nestedItem.ParentItem["Email"].Text;

            var lvOrder = (RadListView)nestedItem.FindControl("lvOrder");
            var OdsOrder = (ObjectDataSource)nestedItem.FindControl("OdsOrder");
            lvOrder.DataSourceID = OdsOrder.ID;
        }
    }
    private void printAllItems(List<InventoryItem> items)
    {
        foreach(InventoryItem item in items)
        {
            InventoryHtmlPrinter printer = new InventoryHtmlPrinter(item);
            String itemHtml = printer.getMultiItemHtml();

            LiteralControl control = new LiteralControl(itemHtml);
            productsPlaceHolder.Controls.Add(control);

        }
    }
Example #25
0
    private void DirectHitSearch()
    {
        string from = Request.QueryString["aspxerrorpath"];
        int index = from.LastIndexOf("/") + 1;
        string title = from.Substring(index).Replace(".aspx", string.Empty).Replace("-", " ");

        List<IPublishable> items = Search.Hits(title, false);
        if (items.Count > 0)
        {
            LiteralControl result = new LiteralControl(string.Format("<li><a href=\"{0}\">{1}</a></li>", items[0].RelativeLink.ToString(), items[0].Title));
            phSearchResult.Controls.Add(result);
        }
    }
Example #26
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         loadCountries();
         setStartingCountry();
     }
     finally
     {
         try
         {
             btn_redeem_submit.Enabled = true;
             lblErrorMessage.Controls.Clear();
             try
             {
                 referralid = int.Parse(Server.UrlDecode(Cryptography.DecryptData(Request["ReferralId"])));    
                 badReferralId = false;                
             }
             catch (Exception ex)
             {
                 logService.LogAppEvent("", @"HarperNET", "Referral", "Unable to decrypt referral id, using default referrer instead. (referralid in url): " + Request["ReferralId"], ex.Message, ex.StackTrace, "", "Page_Load");
                 badReferralId = true;                
             }
             if (!badReferralId)
             {
                 Referral referral = new Referral(referralid);
                 if (referral.id <= 0)
                 {
                     throw new Exception(string.Format("Cannot redeem referral - referral id {0} does not exist", referralid));
                 }
                 if (referral.dateredeemed != null)
                 {
                     throw new Exception(string.Format("Referral id {0} has already been redeemed", referralid));
                 }
                 if (!Page.IsPostBack)
                 {
                     email_address.Text = referral.friendemail;
                 }
             }
         }
         catch (Exception ex)
         {
             logService.LogAppEvent("", @"HarperNET", "Referral", "Error in Page_Load Referralid in url): " + Request["ReferralId"], ex.Message, ex.StackTrace, "", "Page_Load");
             LiteralControl err = new LiteralControl();
             err.Text = "<p class=\"error-message\">An error has occurred.  Please contact the membership department at <a href=\"mailto:[email protected]\">[email protected]</a></p>";
             lblErrorMessage.Controls.Add(err);
             lblErrorMessage.Visible = true;
             btn_redeem_submit.Enabled = false;
         }
     }
 }
    private void CreateFields()
    {
        TextBox txt;
        LiteralControl MyControl;
        Panel MyPanel, BigPanel = null;

        foreach (dynamic obj1 in obj["SiteConfigurations"])
        {
            if (obj1["key"] == "siteicon")
            {
                imgSiteIcon.ImageUrl = "../" + obj1["value"];
            }
            else if (obj1["key"] == "siteimage")
            {
                imgSiteImage.ImageUrl = "../" + obj1["value"];
            }
            else
            {
                #region Create the big div
                BigPanel = new Panel();
                BigPanel.CssClass = "form-group";
                BigPanel.ID = "div_" + obj1["key"];
                #endregion
                #region Create the label -- propname
                MyControl = new LiteralControl();
                MyControl.Text = "<label>" + obj1["display"] + " :</label>";
                MyPanel = new Panel();
                MyPanel.CssClass = "controls";
                MyPanel.ID = "underdiv_" + obj1["key"];
                #endregion
                #region Create the textbox
                txt = new TextBox();
                txt.CssClass = "form-control";
                txt.ID = "field_" + obj1["key"];

                //Fill its value
                txt.Text = obj1["value"];

                MyPanel.Controls.Add(txt);
                #endregion
                #region Add everything to the big div
                BigPanel.Controls.Add(MyControl);
                BigPanel.Controls.Add(MyPanel);
                #endregion

                fields.Controls.Add(BigPanel);
            }
        }
                
    }
    /// <summary>
    /// PreRender event handler.
    /// </summary>
    /// <param name="e">EventArgs</param>
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (!StopProcessing)
        {
            // Add link to page header
            string url = CSSHelper.GetPhysicalCSSUrl(FilePath);
            string link = CSSHelper.GetCSSFileLink(url, Media);

            LiteralControl ltlCss = new LiteralControl(link);
            ltlCss.EnableViewState = false;

            Page.Header.Controls.Add(ltlCss);
        }
    }
    public void BindGrid()
    {
        try
        {
            SqlDataAdapter da = new SqlDataAdapter("Select * from loginDetails", con);
            DataSet ds = new DataSet();
            con.Open();
            da.Fill(ds, "abc");
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                Table1.GridLines = GridLines.Horizontal;
                TableRow r = new TableRow();
                r.BackColor = System.Drawing.Color.Aqua;
                r.ForeColor = System.Drawing.Color.Navy;
                r.Style.Add("text-align", "center");
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    TableCell c = new TableCell();
                    LiteralControl one = new LiteralControl(ds.Tables[0].Columns[i].ColumnName.ToString());
                    c.Controls.Add(one);
                    r.Controls.Add(c);
                }
                Table1.Controls.Add(r);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    TableRow r1 = new TableRow();
                    r1.BackColor = System.Drawing.Color.MistyRose;
                    r1.ForeColor = System.Drawing.Color.Red;
                    r1.Style.Add("text-align", "center");
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        TableCell c = new TableCell();
                        LiteralControl one = new LiteralControl(ds.Tables[0].Rows[i][j].ToString());
                        c.Controls.Add(one);
                        r1.Controls.Add(c);
                    }
                    Table1.Controls.Add(r1);
                }
            }
        }
        catch (Exception grid)
        {
            lblAns.Text = grid.Message.ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        int cnt=1;
        try
        {
            event_id = Request.QueryString["evtid"];

            con.Open();
            cmd = new MySqlCommand("select name,img1path from events where evt_id='" + event_id + "'", con);
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                imgpath = "../" + dr.GetString("img1path");

                HiddenField1.Value = imgpath;

                header1.Text = dr.GetString("name").Substring(0, 1).ToUpper() + dr.GetString("name").Substring(1).ToLower();

                DirectoryInfo files = new DirectoryInfo(Server.MapPath(imgpath + "thumbs/"));
                FileInfo[] f = files.GetFiles();

                foreach (FileInfo temp in f)
                {
                LiteralControl imgfile =new LiteralControl("<!-- start entry-->"
            +"<div class='thumbnailimage'><div class='thumb_container'><div class='large_thumb'>"
            +"<img src='"+ imgpath + "slides/" + temp.Name +"' class='large_thumb_image' alt='thumb' />"
            +"<img src='"+ imgpath + "slides/" + temp.Name +"' class='large_image' rel='Image-"+cnt+++"' />"
            +"<div class='large_thumb_border'></div><div class='large_thumb_shine'></div></div></div></div>"
            +"<!--end entry-->");

                showimgs.Controls.Add(imgfile);
                }
            }
            else
            {
                everr.Visible = true;
            }
            dr.Close();
            con.Close();
        }
        catch (Exception ex)
        {
            CreateLogFile log = new CreateLogFile();
            log.ErrorLog(Server.MapPath("../Logs/Errorlog"), "page load method of Eventlist page for " + Session["loginname"] + ":" + ex.Message);
        }
    }
Example #31
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            RockPage.AddCSSLink(ResolveRockUrl("~/Styles/fluidbox.css"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/imagesloaded.min.js"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/jquery.fluidbox.min.js"));

            if (CurrentPerson != null)
            {
                lName.Text = CurrentPerson.FullName;

                // Setup Image
                var imgTag = new LiteralControl(Rock.Model.Person.GetPersonPhotoImageTag(CurrentPerson, 188, 188));
                if (CurrentPerson.PhotoId.HasValue)
                {
                    var imgLink = new HyperLink();
                    imgLink.Attributes.Add("href", CurrentPerson.PhotoUrl);
                    phImage.Controls.Add(imgLink);
                    imgLink.Controls.Add(imgTag);
                }
                else
                {
                    phImage.Controls.Add(imgTag);
                }

                if (CurrentPerson.BirthDate.HasValue)
                {
                    var    dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
                    string mdp = dtf.ShortDatePattern;
                    mdp = mdp.Replace(dtf.DateSeparator + "yyyy", "").Replace("yyyy" + dtf.DateSeparator, "");

                    string ageText = (CurrentPerson.BirthYear.HasValue && CurrentPerson.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format("{0} yrs old ", CurrentPerson.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format("{0}<small>({1})</small><br/>", ageText, CurrentPerson.BirthDate.Value.ToMonthDayString());
                }

                lGender.Text = CurrentPerson.Gender != Gender.Unknown ? CurrentPerson.Gender.ToString() : string.Empty;

                if (CurrentPerson.PhoneNumbers != null)
                {
                    rptPhones.DataSource = CurrentPerson.PhoneNumbers.ToList();
                    rptPhones.DataBind();
                }

                lEmail.Text = CurrentPerson.Email;

                Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                if (locationTypeGuid.HasValue)
                {
                    var addressTypeDv = DefinedValueCache.Get(locationTypeGuid.Value);

                    var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();

                    if (familyGroupTypeGuid.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Get(familyGroupTypeGuid.Value);

                        RockContext rockContext = new RockContext();
                        var         address     = new GroupLocationService(rockContext).Queryable()
                                                  .Where(l => l.Group.GroupTypeId == familyGroupType.Id &&
                                                         l.GroupLocationTypeValueId == addressTypeDv.Id &&
                                                         l.Group.Members.Any(m => m.PersonId == CurrentPerson.Id))
                                                  .Select(l => l.Location)
                                                  .FirstOrDefault();
                        if (address != null)
                        {
                            lAddress.Text = string.Format("<div class='margin-b-md'><small>{0} Address</small><br />{1}</div>", addressTypeDv.Value, address.FormattedHtmlAddress);
                        }
                    }
                }

                if (GetAttributeValue("ShowHomeAddress").AsBoolean())
                {
                    var homeAddress = CurrentPerson.GetHomeLocation();
                    if (homeAddress != null)
                    {
                    }
                }
            }
        }
Example #32
0
        /// <devdoc>
        ///    <para>Initializes a cell within the field.</para>
        /// </devdoc>
        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);
            bool           showEditButton   = ShowEditButton;
            bool           showDeleteButton = ShowDeleteButton;
            bool           showInsertButton = ShowInsertButton;
            bool           showSelectButton = ShowSelectButton;
            bool           showCancelButton = ShowCancelButton;
            bool           isFirstButton    = true;
            bool           causesValidation = CausesValidation;
            string         validationGroup  = ValidationGroup;
            LiteralControl spaceControl;

            if (cellType == DataControlCellType.DataCell)
            {
                if ((rowState & (DataControlRowState.Edit | DataControlRowState.Insert)) != 0)
                {
                    if ((rowState & DataControlRowState.Edit) != 0 && showEditButton)
                    {
                        AddButtonToCell(cell, DataControlCommands.UpdateCommandName, UpdateText, causesValidation, validationGroup, rowIndex, UpdateImageUrl);
                        if (showCancelButton)
                        {
                            spaceControl = new LiteralControl("&nbsp;");
                            cell.Controls.Add(spaceControl);
                            AddButtonToCell(cell, DataControlCommands.CancelCommandName, CancelText, false, String.Empty, rowIndex, CancelImageUrl);
                        }
                    }
                    if ((rowState & DataControlRowState.Insert) != 0 && showInsertButton)
                    {
                        AddButtonToCell(cell, DataControlCommands.InsertCommandName, InsertText, causesValidation, validationGroup, rowIndex, InsertImageUrl);
                        if (showCancelButton)
                        {
                            spaceControl = new LiteralControl("&nbsp;");
                            cell.Controls.Add(spaceControl);
                            AddButtonToCell(cell, DataControlCommands.CancelCommandName, CancelText, false, String.Empty, rowIndex, CancelImageUrl);
                        }
                    }
                }
                else
                {
                    if (showEditButton)
                    {
                        AddButtonToCell(cell, DataControlCommands.EditCommandName, EditText, false, String.Empty, rowIndex, EditImageUrl);
                        isFirstButton = false;
                    }
                    if (showDeleteButton)
                    {
                        if (isFirstButton == false)
                        {
                            spaceControl = new LiteralControl("&nbsp;");
                            cell.Controls.Add(spaceControl);
                        }
                        AddButtonToCell(cell, DataControlCommands.DeleteCommandName, DeleteText, false, String.Empty, rowIndex, DeleteImageUrl);
                        isFirstButton = false;
                    }
                    if (showInsertButton)
                    {
                        if (isFirstButton == false)
                        {
                            spaceControl = new LiteralControl("&nbsp;");
                            cell.Controls.Add(spaceControl);
                        }
                        AddButtonToCell(cell, DataControlCommands.NewCommandName, NewText, false, String.Empty, rowIndex, NewImageUrl);
                        isFirstButton = false;
                    }
                    if (showSelectButton)
                    {
                        if (isFirstButton == false)
                        {
                            spaceControl = new LiteralControl("&nbsp;");
                            cell.Controls.Add(spaceControl);
                        }
                        AddButtonToCell(cell, DataControlCommands.SelectCommandName, SelectText, false, String.Empty, rowIndex, SelectImageUrl);
                        isFirstButton = false;
                    }
                }
            }
        }
Example #33
0
    public void Algo(DataTable dt)
    {
        DataRowCollection dr    = dt.Rows;
        DataTable         dtnew = CreateDataTable();

        double teamAverage         = 0;
        int    totalTeams          = Convert.ToInt32(txtNoOfTeams.Text);
        int    totalPlayersPerTeam = Convert.ToInt32(txtNoOfPlayersPerTeam.Text);

        int[][] retShuffledArr = shuffleArray(fillArray(dt, totalPlayersPerTeam, totalTeams), totalTeams, totalPlayersPerTeam);

        if ((totalPlayersPerTeam * totalTeams) <= dt.Rows.Count)
        {
            for (int i = 0; i < totalTeams; i++)
            {
                dtnew.Clear();
                teamAverage = 0;

                int it = 0;
                for (int j = 0; j < totalPlayersPerTeam; j++)
                {
                    int rowId = retShuffledArr[it][i];

                    double  k = Convert.ToDouble(dt.Rows[rowId]["average"]);
                    DataRow row;
                    row = dtnew.NewRow();
                    row["Player Name"]    = dt.Rows[rowId]["playerName"];
                    row["Contact Number"] = dt.Rows[rowId]["playerContactNumber"];
                    row["average"]        = k;
                    dtnew.Rows.Add(row);
                    teamAverage += k;

                    it = it + 1;
                }

                dtnew.AcceptChanges();

                // Lable for Grid Team name
                Label lblTeam = new Label();
                lblTeam.ID   = "lblTeam " + (i);
                lblTeam.Text = "<b>Team Name:</b> Team " + (i + 1);
                Page.Controls.Add(lblTeam);

                // Label for Average
                Label lblTeamAverage = new Label();
                lblTeamAverage.ID = "lblTeamAverage" + i;
                decimal rounded = decimal.Round((decimal)(teamAverage / totalPlayersPerTeam), 1);
                lblTeamAverage.Text = "<b>Team Average:</b> " + rounded.ToString();

                Page.Controls.Add(lblTeamAverage);
                LiteralControl breakLine = new LiteralControl();
                breakLine.Text = "<br /><br />";
                LiteralControl breakLineSingle = new LiteralControl();
                breakLineSingle.Text = "<br />";
                LiteralControl space = new LiteralControl();
                space.Text = "&nbsp;&nbsp;&nbsp;";

                //Adding the controls to div
                gvTeam.Controls.Add(breakLine);
                gvTeam.Controls.Add(lblTeam);
                gvTeam.Controls.Add(breakLineSingle);
                gvTeam.Controls.Add(lblTeamAverage);

                GridView gvTeamDivision = new GridView();
                gvTeamDivision.ID         = "gvTeam" + i;
                gvTeamDivision.DataSource = dtnew;
                gvTeamDivision.DataBind();
                Page.Controls.Add(gvTeamDivision);
                gvTeam.Controls.Add(gvTeamDivision);
            }
        }
        else
        {
            lblError.Text = "Total Players in al league are less then the expected players.";
        }
    }
Example #34
0
        public void AddControl(Screen Screen, Section Section, Control parent, Widget control)
        {
            try
            {
                bool              IsControlVisible  = true;
                bool              IsControlEditable = true;
                ControlType       controlType       = null;
                ControlType       labelControlType  = null;
                BaseFieldTemplate ctrl         = null;
                BaseFieldTemplate readOnlyCtrl = null;
                System.Web.UI.WebControls.BaseValidator val = null;


                HtmlGenericControl group = null;

                HtmlGenericControl labelContainer     = null;
                System.Web.UI.WebControls.Label label = null;

                HtmlGenericControl controlContainer = null;
                PlaceHolder        groupContainer   = null;

                Control help = null;

                IsControlVisible  = DetermineControlVisibility(control, IsControlVisible);
                IsControlEditable = DetermineIfControlIsEditable(control, IsControlVisible, IsControlEditable);

                //setup overall container
                groupContainer         = new PlaceHolder();
                groupContainer.ID      = String.Format("{0}_GroupContainer", control.Name);
                groupContainer.Visible = IsControlVisible;

                //setup control group if needed
                if (!String.IsNullOrEmpty(control.ControlGroupElement))
                {
                    group    = new HtmlGenericControl(control.ControlGroupElement);
                    group.ID = String.Format("{0}_FormGroup", control.Name);

                    if (!String.IsNullOrEmpty(control.ControlGroupCssClass))
                    {
                        group.Attributes.Add("class", control.ControlGroupCssClass);
                    }
                }

                //setup label container if needed
                if (!String.IsNullOrEmpty(control.LabelContainerElement))
                {
                    labelContainer    = new HtmlGenericControl(control.LabelContainerElement);
                    labelContainer.ID = String.Format("{0}_LabelContainer", control.Name);

                    if (!String.IsNullOrEmpty(control.LabelContainerCssClass))
                    {
                        labelContainer.Attributes.Add("class", control.LabelContainerCssClass);
                    }
                }

                //setup control container if needed
                if (!String.IsNullOrEmpty(control.ControlContainerElement))
                {
                    controlContainer    = new HtmlGenericControl(control.ControlContainerElement);
                    controlContainer.ID = String.Format("{0}_ControlContainer", control.Name);

                    if (!String.IsNullOrEmpty(control.ControlContainerCssClass))
                    {
                        controlContainer.Attributes.Add("class", control.ControlContainerCssClass);
                    }
                }

                //setup actual control
                controlType = ControlType.GetControlType(control);
                if (controlType == null)
                {
                    throw new ApplicationException(String.Format("Control of type {0} could not be found in configuration", control.Type));
                }

                if (!IsControlEditable)
                {
                    labelControlType = ControlType.GetControlType("Label");
                }

                if (controlType != null)
                {
                    //main edit control
                    ctrl    = LoadBaseFieldTemplateFromControlType(controlType);
                    ctrl.ID = control.Name;
                    ctrl.ResourceKeyPrefix = String.Format("Screen.Sections.{0}.Control", Section.Name);
                    BaseFieldTemplate renderControl = null;

                    //alternate edit control in read only mode
                    if (!IsControlEditable)
                    {
                        readOnlyCtrl    = LoadBaseFieldTemplateFromControlType(labelControlType);
                        readOnlyCtrl.ID = String.Format("{0}_ReadOnly_Label", control.Name);
                    }

                    if (IsControlEditable)
                    {
                        renderControl = ctrl;
                    }
                    else
                    {
                        renderControl = readOnlyCtrl;
                    }

                    //label
                    label    = new System.Web.UI.WebControls.Label();
                    label.ID = String.Format("{0}_Label", control.Name);
                    if (!String.IsNullOrEmpty(control.LabelCssClass))
                    {
                        string labelCss = String.Format("{0}", control.LabelCssClass);

                        if (control.IsRequired)
                        {
                            labelCss += " required required-label";
                        }

                        label.CssClass = labelCss;
                    }
                    if (!String.IsNullOrEmpty(control.Label))
                    {
                        string labelText = GetGlobalResourceString(String.Format("Control.{0}.Label", control.Name), control.Label);
                        labelText += ":";

                        label.Controls.Add(new LiteralControl(labelText));
                    }

                    //help text
                    if (!String.IsNullOrEmpty(control.HelpText))
                    {
                        string helpText = GetGlobalResourceString(String.Format("Control.{0}.HelpText", control.Name), control.HelpText);

                        if (String.IsNullOrEmpty(control.HelpTextElement))
                        {
                            help = new LiteralControl(control.HelpText);
                        }
                        else
                        {
                            HtmlGenericControl helpControl = new HtmlGenericControl(control.HelpTextElement);
                            helpControl.InnerHtml = control.HelpText;

                            if (!String.IsNullOrEmpty(control.HelpTextCssClass))
                            {
                                helpControl.Attributes.Add("class", control.HelpTextCssClass);
                            }

                            help = helpControl;
                        }
                    }


                    //validation controls
                    List <System.Web.UI.WebControls.BaseValidator> validators = new List <System.Web.UI.WebControls.BaseValidator>();
                    if (IsControlEditable)
                    {
                        //custom validators
                        foreach (CodeTorch.Core.BaseValidator validator in control.Validators)
                        {
                            System.Web.UI.WebControls.BaseValidator validatorControl = GetValidator(control, validator);
                            validators.Add(validatorControl);
                        }
                    }

                    //assign base control, section and screen references
                    ctrl.Widget = control;
                    if (!IsControlEditable)
                    {
                        readOnlyCtrl.Widget = CreateLabelControlFromWidget(control);
                        readOnlyCtrl.Value  = ctrl.Value;
                        readOnlyCtrl.SetDisplayText(ctrl.DisplayText);
                    }
                    ctrl.Section = Section;
                    ctrl.Screen  = Screen;

                    //now that all controls have been defined we now need to render table html based on rendering mode
                    if (group != null)
                    {
                        if (control.LabelWrapsControl)
                        {
                            AssignControl(group, labelContainer, label);
                            AssignControl(label, controlContainer, renderControl, help);
                        }
                        else
                        {
                            label.AssociatedControlID = renderControl.ClientID;

                            if (control.LabelRendersBeforeControl)
                            {
                                AssignControl(group, labelContainer, label);
                                AssignControl(group, controlContainer, renderControl, help);
                            }
                            else
                            {
                                AssignControl(group, controlContainer, renderControl, help);
                                AssignControl(group, labelContainer, label);
                            }
                        }
                    }
                    else
                    {
                        Control g = groupContainer;// (parent != null) ? (Control)parent : (Control)this.ContentPlaceHolder;

                        if (control.LabelWrapsControl)
                        {
                            AssignControl(g, labelContainer, label);
                            AssignControl(label, controlContainer, renderControl, help);
                        }
                        else
                        {
                            label.AssociatedControlID = renderControl.ClientID;

                            if (control.LabelRendersBeforeControl)
                            {
                                AssignControl(g, labelContainer, label);
                                AssignControl(g, controlContainer, renderControl, help);
                            }
                            else
                            {
                                AssignControl(g, controlContainer, renderControl, help);
                                AssignControl(g, labelContainer, label);
                            }
                        }
                    }


                    if (parent != null)
                    {
                        if (group != null)
                        {
                            groupContainer.Controls.Add(group);
                        }
                        parent.Controls.Add(groupContainer);
                    }
                    else
                    {
                        if (group != null)
                        {
                            groupContainer.Controls.Add(group);
                        }
                        this.ContentPlaceHolder.Controls.Add(groupContainer);
                    }


                    string requiredErrorMessage = String.Format("{0} is required.", control.Label);
                    string requiredErrorMessageResourceValue = GetGlobalResourceString(String.Format("Control.{0}.IsRequired.ErrorMessage", control.Name), requiredErrorMessage);

                    //get container for validation
                    Control valContainer = ((Control)controlContainer ??
                                            (
                                                (Control)group ??
                                                (
                                                    ((Control)parent ?? (Control)this.ContentPlaceHolder)
                                                )
                                            )
                                            );



                    if (!String.IsNullOrEmpty(control.Name))
                    {
                        if (ctrl.SupportsValidation())
                        {
                            val = ctrl.GetRequiredValidator(control, IsControlEditable, requiredErrorMessageResourceValue);
                            valContainer.Controls.Add(val);

                            if (IsControlEditable)
                            {
                                //custom validators
                                foreach (System.Web.UI.WebControls.BaseValidator validator in validators)
                                {
                                    valContainer.Controls.Add(validator);
                                }
                            }
                        }
                    }
                }
                else
                {
                    string ErrorMessageFormat = "<span style='color:red'>ERROR - Could not load control {0} - {1} - control type returned null object</span>";
                    string ErrorMessages      = String.Format(ErrorMessageFormat, control.Name, control.Type);


                    this.ContentPlaceHolder.Controls.Add(new LiteralControl(ErrorMessages));
                }
            }
            catch (Exception ex)
            {
                this.ContentPlaceHolder.Controls.Add(new LiteralControl(ex.Message));
            }
        }
Example #35
0
        protected void updateMessages_Click(object sender, EventArgs e)
        {
            if (Session["access_token"] == null)
            {
                return;
            }

            if (Timer.Text.Equals("Expire email time: 00:00:00") || Timer.Text.Equals(""))
            {
                Session["access_token"] = null;
                return;
            }

            var client = new RestClient("https://mail.zoho.eu/api/accounts/1305411000000002002/messages/view");

            client.Timeout = -1;
            var    request = new RestRequest(Method.GET);
            String header  = "Zoho-oauthtoken " + Session["access_token"].ToString();

            request.AddHeader("Authorization", header);
            IRestResponse response = client.Execute(request);
            dynamic       data     = JObject.Parse(response.Content);

            //string from = data.data[0].sender;
            //string subject = data.data[0].subject;
            //string date = data.data[0].receivedTime;
            int numMsg = data.data.Count;

            Label[] lFrom    = new Label[numMsg];
            Label[] lSubject = new Label[numMsg];
            Label[] lDate    = new Label[numMsg];
            Label[] lContent = new Label[numMsg];

            for (int i = 0; i < numMsg; i++)
            {
                string idMsg = data.data[i].messageId;

                HtmlGenericControl div = new HtmlGenericControl("div");
                div.Attributes.Add("class", "msg");

                lFrom[i]    = new Label();
                lSubject[i] = new Label();
                lDate[i]    = new Label();
                lContent[i] = new Label();

                client         = new RestClient("https://mail.zoho.eu/api/accounts/1305411000000002002/folders/1305411000000002014/messages/" + idMsg + "/content");
                client.Timeout = -1;
                request        = new RestRequest(Method.GET);
                header         = "Zoho-oauthtoken " + Session["access_token"].ToString();
                request.AddHeader("Authorization", header);
                response = client.Execute(request);

                dynamic dataMsg = JObject.Parse(response.Content);

                LiteralControl lineBreak1 = new LiteralControl("<br />");
                lFrom[i].Text = "From: " + data.data[i].sender;
                lFrom[i].Attributes.Add("style", "margin-left: 20px;");

                lSubject[i].Text      = data.data[i].subject;
                lSubject[i].Font.Bold = true;
                lSubject[i].Attributes.Add("style", "margin-left: 50px;");

                System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string          time       = data.data[i].receivedTime;
                dtDateTime    = dtDateTime.AddMilliseconds(long.Parse(time)).ToLocalTime();
                lDate[i].Text = dtDateTime.ToString();
                lDate[i].Attributes.Add("style", "float: right; margin-right: 20px;");

                LiteralControl lineBreak2 = new LiteralControl("<br /><br />");
                lContent[i].Text = dataMsg["data"]["content"];
                LiteralControl lineBreak3 = new LiteralControl("<br />");

                div.Controls.Add(lineBreak1);
                div.Controls.Add(lFrom[i]);
                div.Controls.Add(lSubject[i]);
                div.Controls.Add(lDate[i]);
                div.Controls.Add(lineBreak2);
                div.Controls.Add(lContent[i]);
                div.Controls.Add(lineBreak3);

                Messages.Controls.Add(div);
                Messages.Controls.Add(lineBreak1);
            }

            if (numMsg == 0)
            {
                HtmlGenericControl h2 = new HtmlGenericControl("h2");
                Label noMsg           = new Label();
                noMsg.Font.Bold   = true;
                noMsg.Font.Italic = true;
                noMsg.Text        = "You have no messages.";

                h2.Controls.Add(noMsg);

                Messages.Controls.Add(h2);
            }
        }
Example #36
0
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            base.Controls.Clear();

            _dfltShowButton = new Button();
            base.Controls.Add(_dfltShowButton);
            _dfltShowButton.ID = "default";
            _dfltShowButton.Attributes.Add("style", "display:none");

            _dialogPanel = new Panel();
            base.Controls.Add(_dialogPanel);
            _dialogPanel.ID       = "panel";
            _dialogPanel.CssClass = "rock-modal rock-modal-frame";
            _dialogPanel.Attributes.Add("style", "display:none");

            _headerPanel = new Panel();
            _dialogPanel.Controls.Add(_headerPanel);
            _headerPanel.ID       = "headerPanel";
            _headerPanel.CssClass = "modal-header";

            _contentPanel = new Panel();
            _dialogPanel.Controls.Add(_contentPanel);
            _contentPanel.ID       = "contentPanel";
            _contentPanel.CssClass = "modal-body";

            _footerPanel = new Panel();
            _dialogPanel.Controls.Add(_footerPanel);
            _footerPanel.ID       = "footerPanel";
            _footerPanel.CssClass = "modal-footer";

            _closeLink = new HtmlGenericControl("A");
            _headerPanel.Controls.Add(_closeLink);
            _closeLink.ID = "closeLink";
            _closeLink.Attributes.Add("HRef", "#");
            _closeLink.Attributes.Add("class", "close");
            _closeLink.InnerHtml = "&times;";

            _titleH3 = new HtmlGenericControl("h3");
            _titleH3.AddCssClass("modal-title");
            _headerPanel.Controls.Add(_titleH3);

            _title      = new LiteralControl();
            _title.Text = string.Empty;
            _titleH3.Controls.Add(_title);

            _cancelLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_cancelLink);
            _cancelLink.ID = "cancelLink";
            _cancelLink.Attributes.Add("class", "btn btn-link");
            _cancelLink.InnerText = "Cancel";

            _serverSaveLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_serverSaveLink);
            _serverSaveLink.ID = "serverSaveLink";
            _serverSaveLink.Attributes.Add("class", "btn btn-primary");
            _serverSaveLink.ServerClick += SaveLink_ServerClick;

            _saveLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_saveLink);
            _saveLink.ID = "saveLink";
            _saveLink.Attributes.Add("class", "btn btn-primary modaldialog-save-button");

            this.PopupControlID  = _dialogPanel.ID;
            this.CancelControlID = _cancelLink.ID;
        }
Example #37
0
        protected void UpdateFormForTemplate(int id, bool fResetTitle, string defaultText = null)
        {
            EndorsementType et = EndorsementType.GetEndorsementByID(id);

            if (et == null)
            {
                throw new MyFlightbookException(String.Format(CultureInfo.InvariantCulture, "EndorsementTemplate with ID={0} not found", id));
            }

            plcTemplateForm.Controls.Clear();
            plcValidations.Controls.Clear();

            // don't change the title unless we're changing from a prior template.
            if (fResetTitle)
            {
                txtTitle.Text = et.Title;
            }
            lblEndorsementFAR.Text = HttpUtility.HtmlEncode(et.FARReference);

            // Find each of the substitutions
            Regex           r       = new Regex("\\{[^}]*\\}");
            MatchCollection matches = r.Matches(et.BodyTemplate);

            int cursor = 0;

            foreach (Match m in matches)
            {
                // compute the base ID for a control that we create here, before anything gets added, since the result depends on how many controls are in the placeholder already
                string idNewControl = ctlIDPrefix + plcTemplateForm.Controls.Count.ToString(CultureInfo.InvariantCulture);

                if (m.Index > cursor) // need to catch up on some literal text
                {
                    LiteralControl lt = new LiteralControl();
                    plcTemplateForm.Controls.Add(lt);
                    lt.Text = et.BodyTemplate.Substring(cursor, m.Index - cursor);
                    lt.ID   = "ltCatchup" + idNewControl;
                }

                string szMatch = m.Captures[0].Value;

                switch (szMatch)
                {
                case "{Date}":
                {
                    Controls_mfbTypeInDate tid = (Controls_mfbTypeInDate)LoadControl("~/Controls/mfbTypeInDate.ascx");
                    plcTemplateForm.Controls.Add(tid);
                    tid.Date = DateTime.Now;
                    tid.ID   = idNewControl;
                    tid.TextControl.BorderColor = System.Drawing.Color.Black;
                    tid.TextControl.BorderStyle = BorderStyle.Solid;
                    tid.TextControl.BorderWidth = Unit.Pixel(1);
                }
                break;

                case "{FreeForm}":
                    NewTextBox(plcTemplateForm, idNewControl, defaultText ?? string.Empty, true, true, "Free-form text");
                    break;

                case "{Student}":
                    NewTextBox(plcTemplateForm, idNewControl, TargetUser == null ? Resources.SignOff.EditEndorsementStudentNamePrompt : TargetUser.UserFullName, false, true, Resources.SignOff.EditEndorsementStudentNamePrompt);
                    break;

                default:
                    // straight textbox, unless it is strings separated by slashes, in which case it's a drop-down
                {
                    string szMatchInner = szMatch.Substring(1, szMatch.Length - 2);          // get the inside bits - i.e., strip off the curly braces
                    if (szMatchInner.Contains("/"))
                    {
                        string[]     rgItems = szMatchInner.Split('/');
                        DropDownList dl      = new DropDownList();
                        plcTemplateForm.Controls.Add(dl);
                        foreach (string szItem in rgItems)
                        {
                            dl.Items.Add(new ListItem(szItem, szItem));
                        }
                        dl.ID          = idNewControl;
                        dl.BorderColor = System.Drawing.Color.Black;
                        dl.BorderStyle = BorderStyle.Solid;
                        dl.BorderWidth = Unit.Pixel(1);
                    }
                    else
                    {
                        NewTextBox(plcTemplateForm, idNewControl, String.Empty, false, true, szMatchInner);
                    }
                }
                break;
                }

                cursor = m.Captures[0].Index + m.Captures[0].Length;
            }

            if (cursor < et.BodyTemplate.Length)
            {
                LiteralControl lt = new LiteralControl();
                plcTemplateForm.Controls.Add(lt);
                lt.Text = et.BodyTemplate.Substring(cursor);
                lt.ID   = "ltEnding";
            }
        }
        /// <summary>
        /// Renders the comments.
        /// </summary>
        /// <returns>The HTML string.</returns>
        private static string RenderComments()
        {
            if (Comments.Count == 0)
            {
                return(string.Format("<p>{0}</p>", labels.none));
            }

            using (var ul = new HtmlGenericControl("ul"))
            {
                ul.Attributes.Add("class", "recentComments");
                ul.ID = "recentComments";

                foreach (var comment in Comments.Where(comment => comment.IsApproved))
                {
                    var li = new HtmlGenericControl("li");

                    // The post title
                    var title = new HtmlAnchor {
                        HRef = comment.Parent.RelativeLink, InnerText = comment.Parent.Title
                    };
                    title.Attributes.Add("class", "postTitle");
                    li.Controls.Add(title);

                    // The comment count on the post
                    var count =
                        new LiteralControl(string.Format(" ({0})<br />", ((Post)comment.Parent).ApprovedComments.Count));
                    li.Controls.Add(count);

                    // The author
                    if (comment.Website != null)
                    {
                        var author = new HtmlAnchor {
                            HRef = comment.Website.ToString(), InnerHtml = comment.Author
                        };
                        author.Attributes.Add("rel", "nofollow");
                        li.Controls.Add(author);

                        var wrote = new LiteralControl(string.Format(" {0}: ", labels.wrote));
                        li.Controls.Add(wrote);
                    }
                    else
                    {
                        var author = new LiteralControl(string.Format("{0} {1}: ", comment.Author, labels.wrote));
                        li.Controls.Add(author);
                    }

                    // The comment body
                    var commentBody = Regex.Replace(comment.Content, @"\[(.*?)\]", string.Empty);
                    var bodyLength  = Math.Min(commentBody.Length, 50);

                    commentBody = commentBody.Substring(0, bodyLength);
                    if (commentBody.Length > 0)
                    {
                        if (commentBody[commentBody.Length - 1] == '&')
                        {
                            commentBody = commentBody.Substring(0, commentBody.Length - 1);
                        }
                    }

                    commentBody += comment.Content.Length <= 50 ? " " : "� ";
                    var body = new LiteralControl(commentBody);
                    li.Controls.Add(body);

                    // The comment link
                    var link = new HtmlAnchor
                    {
                        HRef = string.Format("{0}#id_{1}", comment.Parent.RelativeLink, comment.Id), InnerHtml = string.Format("[{0}]", labels.more)
                    };
                    link.Attributes.Add("class", "moreLink");
                    li.Controls.Add(link);

                    ul.Controls.Add(li);
                }

                using (var sw = new StringWriter())
                {
                    ul.RenderControl(new HtmlTextWriter(sw));
                    return(sw.ToString());
                }
            }
        }
Example #39
0
        protected virtual void InitializeSiteMaster()
        {
            _isTouchUI = ApplicationServices.IsTouchClient;
            string html           = String.Empty;
            string siteMasterPath = "~/site.desktop.html";

            if (_isTouchUI)
            {
                siteMasterPath = "~/site.touch.html";
            }
            siteMasterPath = Server.MapPath(siteMasterPath);
            if (!(File.Exists(siteMasterPath)))
            {
                siteMasterPath = Server.MapPath("~/site.html");
            }
            if (File.Exists(siteMasterPath))
            {
                html = File.ReadAllText(siteMasterPath);
            }
            else
            {
                throw new Exception("File site.html has not been found.");
            }
            Match htmlMatch = Regex.Match(html, "<html(?\'HtmlAttr\'[\\S\\s]*?)>\\s*<head(?\'HeadAttr\'[\\S\\s]*?)>\\s*(?\'Head\'[\\S\\s]*?)\\s*<" +
                                          "/head>\\s*<body(?\'BodyAttr\'[\\S\\s]*?)>\\s*(?\'Body\'[\\S\\s]*?)\\s*</body>\\s*</html>\\s*");

            if (!(htmlMatch.Success))
            {
                throw new Exception("File site.html must contain \'head\' and \'body\' elements.");
            }
            // instructions
            Controls.Add(new LiteralControl(html.Substring(0, htmlMatch.Index)));
            // html
            Controls.Add(new LiteralControl(String.Format("<html{0} xml:lang={1} lang=\"{1}\">\r\n", htmlMatch.Groups["HtmlAttr"].Value, CultureInfo.CurrentUICulture.IetfLanguageTag)));
            // head
            Controls.Add(new HtmlHead());
            if (_isTouchUI)
            {
                Header.Controls.Add(new LiteralControl("<meta charset=\"utf-8\">\r\n"));
            }
            else
            {
                Header.Controls.Add(new LiteralControl("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n"));
            }
            string headHtml = Regex.Replace(htmlMatch.Groups["Head"].Value, "\\s*<title([\\s\\S+]*?title>)\\s*", String.Empty);

            Header.Controls.Add(new LiteralControl(headHtml));
            _headContent = new LiteralContainer();
            Header.Controls.Add(_headContent);
            // body
            _bodyTag        = new LiteralControl();
            _bodyAttributes = new AttributeDictionary(htmlMatch.Groups["BodyAttr"].Value);
            Controls.Add(_bodyTag);
            string themePath = Server.MapPath("~/App_Themes/MyCompany");

            if (Directory.Exists(themePath))
            {
                foreach (string stylesheetFileName in Directory.GetFiles(themePath, "*.css"))
                {
                    string fileName = Path.GetFileName(stylesheetFileName);
                    if (!(fileName.Equals("_Theme_Aquarium.css")))
                    {
                        HtmlLink link = new HtmlLink();
                        link.Href = ("~/App_Themes/MyCompany/" + fileName);
                        link.Attributes["type"] = "text/css";
                        link.Attributes["rel"]  = "stylesheet";
                        Header.Controls.Add(link);
                    }
                }
            }
            // form
            Controls.Add(new HtmlForm());
            Form.ID = "aspnetForm";
            // ScriptManager
            ScriptManager sm = new ScriptManager();

            sm.ID = "sm";
            sm.AjaxFrameworkMode = AjaxFrameworkMode.Disabled;
            if (AquariumExtenderBase.EnableCombinedScript)
            {
                sm.EnableScriptLocalization = false;
            }
            sm.ScriptMode = ScriptMode.Release;
            Form.Controls.Add(sm);
            // SiteMapDataSource
            SiteMapDataSource siteMapDataSource1 = new SiteMapDataSource();

            siteMapDataSource1.ID = "SiteMapDataSource1";
            siteMapDataSource1.ShowStartingNode = false;
            Form.Controls.Add(siteMapDataSource1);
            // parse and initialize placeholders
            string body             = htmlMatch.Groups["Body"].Value;
            Match  placeholderMatch = Regex.Match(body, "<div\\s+data-role\\s*=\\s*\"placeholder\"(?\'Attributes\'[\\s\\S]+?)>\\s*(?\'DefaultContent\'" +
                                                  "[\\s\\S]*?)\\s*</div>");
            int startPos = 0;

            while (placeholderMatch.Success)
            {
                AttributeDictionary attributes = new AttributeDictionary(placeholderMatch.Groups["Attributes"].Value);
                // create placeholder content
                Form.Controls.Add(new LiteralControl(body.Substring(startPos, (placeholderMatch.Index - startPos))));
                string placeholder    = attributes["data-placeholder"];
                string defaultContent = placeholderMatch.Groups["DefaultContent"].Value;
                if (!(CreatePlaceholder(Form.Controls, placeholder, defaultContent, attributes)))
                {
                    LiteralContainer placeholderControl = new LiteralContainer();
                    placeholderControl.Text = defaultContent;
                    Form.Controls.Add(placeholderControl);
                    if (placeholder == "page-header")
                    {
                        _pageHeaderContent = placeholderControl;
                    }
                    if (placeholder == "page-title")
                    {
                        _pageTitleContent = placeholderControl;
                    }
                    if (placeholder == "page-side-bar")
                    {
                        _pageSideBarContent = placeholderControl;
                    }
                    if (placeholder == "page-content")
                    {
                        _pageContent = placeholderControl;
                    }
                    if (placeholder == "page-footer")
                    {
                        _pageFooterContent = placeholderControl;
                    }
                }
                startPos         = (placeholderMatch.Index + placeholderMatch.Length);
                placeholderMatch = placeholderMatch.NextMatch();
            }
            if (startPos < body.Length)
            {
                Form.Controls.Add(new LiteralControl(body.Substring(startPos)));
            }
            // end body
            Controls.Add(new LiteralControl("\r\n</body>\r\n"));
            // end html
            Controls.Add(new LiteralControl("\r\n</html>\r\n"));
        }
Example #40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //string strPreviousPage = "";
        //if (Request.UrlReferrer != null)
        //{
        //    strPreviousPage = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
        //}
        //if (strPreviousPage == "")
        //{
        //    Session["IsLogin"] = "******";
        //    Response.Redirect("~/Default.aspx");
        //}
        if (Session["collegecode"] == null)
        {
            Response.Redirect("~/Default.aspx");
        }
        string group_code = Convert.ToString(Session["group_code"]);

        if (group_code.Contains(";"))
        {
            string[] group_semi = group_code.Split(';');
            group_code = group_semi[0].ToString();
        }

        if ((Session["group_code"].ToString().Trim() != "") && (Session["group_code"].ToString().Trim() != "0") && (Session["group_code"].ToString().Trim() != "-1"))
        {
            grouporusercode = " group_code=" + group_code + "";
        }
        else
        {
            grouporusercode = " user_code=" + Session["usercode"].ToString().Trim() + "";
        }
        string collegecode = Session["Collegecode"].ToString();

        string collegeName = da.GetFunction("select collname from collinfo where  college_code='" + collegecode + "'");

        if (da.GetFunction("select LinkValue from New_InsSettings where LinkName='UseCommonCollegeCode' and user_code ='" + Session["UserCode"].ToString() + "'") == "1")
        {
            string comCOde = da.GetFunction("select com_name from collinfo where  college_code='" + collegecode + "'").Trim();
            collegeName = (comCOde.Length > 1) ? comCOde : collegeName;
        }
        lblcolname.Text = collegeName;

        //lblcolname.Text = da.GetFunction("select collname from collinfo where  college_code='" + collegecode + "'");
        string color    = da.GetFunction("select Farvour_color from user_color where user_code='" + Session["UserCode"].ToString() + "' and college_code='" + collegecode + "'");
        string colornew = "";

        if (color.Trim() == "0")
        {
            colornew = "#06d995";
        }
        else
        {
            colornew = color;
            //prewcolor.Attributes.Add("style", "background-color:" + colornew + ";");
        }
        if (!IsPostBack)
        {
            MainDivIdValue.Attributes.Add("style", "background-color:" + colornew + ";border-bottom: 6px solid lightyellow; box-shadow: 0 0 11px -4px; height: 58px; left: 0; position: fixed; z-index: 2; top: 0; width: 100%;");
            if (Convert.ToString(Session["Staff_Code"]) != "")
            {
                img_stfphoto.ImageUrl = "~/Handler/staffphoto.ashx?staff_code=" + Session["Staff_Code"];
                imgstdphoto.ImageUrl  = "~/Handler/staffphoto.ashx?staff_code=" + Session["Staff_Code"];
                string stfdescode = "";
                sql        = "select desig_code from stafftrans where staff_code='" + Convert.ToString(Session["Staff_Code"]) + "' and latestrec=1";
                stfdescode = da.GetFunction(sql);


                if (stfdescode != "" && stfdescode != null)
                {
                    string stfdesigname = "";
                    sql          = "select dm.desig_name from desig_master dm where dm.desig_code='" + stfdescode.ToString() + "' and collegecode=" + Session["collegecode"].ToString();
                    stfdesigname = da.GetFunction(sql);



                    string staffname = "";
                    sql       = "select staff_name from staffmaster where staff_code='" + Session["staff_code"] + "'";
                    staffname = da.GetFunction(sql);

                    string deptname = "";
                    sql                 = "select dt.dept_acronym from Department dt,stafftrans st where dt.Dept_code=st.dept_code and staff_code='" + Session["staff_code"] + "' and latestrec=1";
                    deptname            = da.GetFunction(sql);
                    lbslstaffname.Text  = Convert.ToString(staffname);
                    lbldesignation.Text = Convert.ToString(stfdesigname);
                    lbldept.Text        = Convert.ToString(deptname);
                }
            }
            else
            {
                string staffname = "";
                sql                = "select full_name from usermaster where user_code='" + Session["UserCode"] + "'";
                staffname          = da.GetFunction(sql);
                lbslstaffname.Text = Convert.ToString(staffname);
            }
        }
        try
        {
            EntryCheck();
            DataSet   dsRights = new DataSet();
            DataTable dtOutput = new DataTable();
            DataView  dvnew    = new DataView();
            string    SelQ     = string.Empty;
            SelQ     = "  select distinct HeaderName from Security_Rights_Details where Rights_Code in(select rights_code from security_user_right where " + grouporusercode + " ) and ModuleName='Feedback'";
            SelQ     = SelQ + " select ModuleName ,HeaderName ,Rights_Code ,ReportId ,ReportName ,PageName ,HelpURL  from Security_Rights_Details where Rights_Code in (select rights_code from security_user_right where " + grouporusercode + " ) and ModuleName='Feedback' order by HeaderPriority, PagePriority asc";
            dsRights = da.select_method_wo_parameter(SelQ, "Text");
            if (dsRights.Tables.Count > 0 && dsRights.Tables[0].Rows.Count > 0 && dsRights.Tables[1].Rows.Count > 0)
            {
                dsRights.Tables[1].DefaultView.RowFilter = " HeaderName='Master'";
                dvnew = dsRights.Tables[1].DefaultView;
                if (dvnew.Count > 0)
                {
                    MasterList.Visible = true;
                    for (int tab1 = 0; tab1 < dvnew.Count; tab1++)
                    {
                        HtmlGenericControl li = new HtmlGenericControl("li");
                        tabs1.Controls.Add(li);
                        tabs1.Attributes.Add("style", "border: 1px solid #999999;background-color: #F0F0F0;box-shadow: 0px 0px 8px #999999; -moz-box-shadow: 0px 0px 10px #999999;-webkit-box-shadow: 0px 0px 10px #999999;border: 1px solid #D9D9D9;border-radius: 15px;");
                        HtmlGenericControl anchor = new HtmlGenericControl("a");
                        anchor.Attributes.Add("target", "_blank");
                        anchor.Attributes.Add("href", Convert.ToString(dvnew[tab1]["PageName"]));
                        anchor.InnerText = Convert.ToString(dvnew[tab1]["ReportName"]);
                        li.Controls.Add(anchor);
                    }
                }
                else
                {
                    MasterList.Visible = false;
                }
                dsRights.Tables[1].DefaultView.RowFilter = " HeaderName='Operation'";
                dvnew = dsRights.Tables[1].DefaultView;
                if (dvnew.Count > 0)
                {
                    OperationList.Visible = true;
                    for (int tab2 = 0; tab2 < dvnew.Count; tab2++)
                    {
                        HtmlGenericControl li = new HtmlGenericControl("li");
                        tabs2.Controls.Add(li);
                        tabs2.Attributes.Add("style", "border: 1px solid #999999;background-color: #F0F0F0;box-shadow: 0px 0px 8px #999999; -moz-box-shadow: 0px 0px 10px #999999;-webkit-box-shadow: 0px 0px 10px #999999;border: 1px solid #D9D9D9;border-radius: 15px;");
                        HtmlGenericControl anchor = new HtmlGenericControl("a");
                        anchor.Attributes.Add("target", "_blank");
                        anchor.Attributes.Add("href", Convert.ToString(dvnew[tab2]["PageName"]));
                        anchor.InnerText = Convert.ToString(dvnew[tab2]["ReportName"]);
                        li.Controls.Add(anchor);
                    }
                }
                else
                {
                    OperationList.Visible = false;
                }
                dsRights.Tables[1].DefaultView.RowFilter = " HeaderName='Report'";
                dvnew = dsRights.Tables[1].DefaultView;
                if (dvnew.Count > 0)
                {
                    ReportList.Visible = true;
                    for (int tab3 = 0; tab3 < dvnew.Count; tab3++)
                    {
                        HtmlGenericControl li = new HtmlGenericControl("li");
                        tabs3.Controls.Add(li);
                        tabs3.Attributes.Add("style", "border: 1px solid #999999;background-color: #F0F0F0;box-shadow: 0px 0px 8px #999999; -moz-box-shadow: 0px 0px 10px #999999;-webkit-box-shadow: 0px 0px 10px #999999;border: 1px solid #D9D9D9;border-radius: 15px;");
                        HtmlGenericControl anchor = new HtmlGenericControl("a");
                        anchor.Attributes.Add("target", "_blank");
                        anchor.Attributes.Add("href", Convert.ToString(dvnew[tab3]["PageName"]));
                        anchor.InnerText = Convert.ToString(dvnew[tab3]["ReportName"]);
                        li.Controls.Add(anchor);
                    }
                }
                else
                {
                    ReportList.Visible = false;
                }
                dsRights.Tables[1].DefaultView.RowFilter = " HeaderName='Charts'";
                dvnew = dsRights.Tables[1].DefaultView;
                if (dvnew.Count > 0)
                {
                    ChartList.Visible = true;
                    for (int tab4 = 0; tab4 < dvnew.Count; tab4++)
                    {
                        HtmlGenericControl li = new HtmlGenericControl("li");
                        tabs4.Controls.Add(li);
                        tabs4.Attributes.Add("style", "border: 1px solid #999999;background-color: #F0F0F0;box-shadow: 0px 0px 8px #999999; -moz-box-shadow: 0px 0px 10px #999999;-webkit-box-shadow: 0px 0px 10px #999999;border: 1px solid #D9D9D9;border-radius: 15px;");
                        HtmlGenericControl anchor = new HtmlGenericControl("a");
                        anchor.Attributes.Add("target", "_blank");
                        anchor.Attributes.Add("href", Convert.ToString(dvnew[tab4]["PageName"]));
                        anchor.InnerText = Convert.ToString(dvnew[tab4]["ReportName"]);
                        li.Controls.Add(anchor);
                    }
                }
                else
                {
                    ChartList.Visible = false;
                }
            }
        }
        catch { }
        LiteralControl ltr = new LiteralControl();

        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                   @"#showmenupages .has-sub ul li:hover a
                                                {
color:lightyellow;
                                                    background-color:" + colornew + @";

                                                }
#showmenupages .has-sub ul li a
        {
border-bottom: 1px dotted " + colornew + @";
}
ul li
{
  border-bottom: 1px dotted " + colornew + @";
            border-right: 1px dotted " + colornew + @";
}
ul li:hover
        {
color:lightyellow;
 background-color:" + colornew + @";
}
a:hover
        {
color:lightyellow;
}
                                                </style>
                                                ";
        this.Page.Header.Controls.Add(ltr);
    }
Example #41
0
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            //文本
            string str = @"<table align=""center"" class=""tableBorder"" cellspacing=""1"" cellpadding=""3"" width=""300"">";

            str += @"<tr><td class=""column"" align=""left"" colspan=""2"">" + CAPTION_STRING + "</td></tr>";
            str += @"<tr><td class=""f"" align=""center"" valign=""top"" colspan=""2"">";
            str += @"<table cellspacing=""1"" border=""0"" cellpadding=""2"">";
            str += @"<tr><td align=""right"" class=""txt3"">";
            str += USERNAME_STRING;
            str += "</td><td>";
            this.Controls.Add(new LiteralControl(str));

            //用戶名輸入框
            tbUserName           = new TextBox();
            tbUserName.Text      = "";
            tbUserName.Width     = Unit.Point(80);
            tbUserName.MaxLength = 64;
            tbUserName.Attributes.Add("size", "11");
            this.Controls.Add(tbUserName);

            //驗證
            vUserName         = new LiteralControl("<font color=red>*</font>");
            vUserName.Visible = false;
            this.Controls.Add(vUserName);

            //文本
            str  = @"</td></tr><tr><td align=""right"" class=""txt3"">";
            str += PASSWORD_STRING;
            str += "</td><td>";
            this.Controls.Add(new LiteralControl(str));

            //密碼輸入框
            tbPassword           = new TextBox();
            tbPassword.Text      = "";
            tbPassword.Width     = Unit.Point(80);
            tbPassword.MaxLength = 64;
            tbPassword.Attributes.Add("size", "11");
            tbPassword.TextMode = TextBoxMode.Password;
            this.Controls.Add(tbPassword);

            //驗證
            vPassword         = new LiteralControl("<font color=red>*</font>");
            vPassword.Visible = false;
            this.Controls.Add(vPassword);

            //文本
            str = @"</td></tr><tr><td align=""right"" colspan=""2"">";
            this.Controls.Add(new LiteralControl(str));

            //註冊新用戶鏈結
            if (ShowRegister)
            {
                lbRegister         = new LinkButton();
                lbRegister.Text    = REGISTER_STRING;
                lbRegister.ToolTip = REGISTER_STRING;
                lbRegister.Click  += new EventHandler(lbRegister_Click);
                this.Controls.Add(lbRegister);

                //文本
                str = "&nbsp;&nbsp;";
                this.Controls.Add(new LiteralControl(str));
            }

            //登陸按鈕
            btnLogin         = new Button();
            btnLogin.Text    = LOGIN_STRING;
            btnLogin.ToolTip = LOGIN_STRING;
            btnLogin.Click  += new EventHandler(btnLogin_Click);
            this.Controls.Add(btnLogin);

            //文本
            str = "&nbsp;&nbsp;";
            this.Controls.Add(new LiteralControl(str));

            //重置按鈕
            btnReset         = new Button();
            btnReset.Text    = RESET_STRING;
            btnReset.ToolTip = RESET_STRING;
            btnReset.Click  += new EventHandler(btnReset_Click);
            this.Controls.Add(btnReset);

            //文本
            str = "</td></tr></table></td></tr></table>";
            this.Controls.Add(new LiteralControl(str));
        }
Example #42
0
        //Form Initiating by creating dynamic controls from Excel sheet
        private void InitForm()
        {
            try
            {
                // Check for license and apply if exists
                string licenseFile = Server.MapPath("~/App_Data/Aspose.Total.lic");

                DataTable dataTable = null;
                if (Session["AsposeDynamicFormsdataTable"] == null)
                {
                    //Creating a file stream containing the Excel file to be opened
                    FileStream fstream = new FileStream(Server.MapPath("~/uploads/AsposeDynamicFormsDataFile.xlsx"),
                                                        FileMode.Open, FileAccess.Read);

                    //Instantiating a Workbook object
                    //Opening the Excel file through the file stream
                    Workbook workbook = new Workbook(fstream);

                    //Accessing a worksheet using its sheet name
                    Worksheet worksheet = workbook.Worksheets["Settings"];

                    //Exporting the contents of 7 rows and 2 columns starting from 1st cell to DataTable
                    dataTable = worksheet.Cells.ExportDataTableAsString(0, 0, worksheet.Cells.Rows.Count, 10, true);

                    //Closing the file stream to free all resources
                    fstream.Close();

                    dataTable.DefaultView.Sort = "[Sort ID] ASC";
                    dataTable = dataTable.DefaultView.ToTable();

                    Session["AsposeDynamicFormsdataTable"] = dataTable;
                }
                else
                {
                    dataTable = (DataTable)Session["AsposeDynamicFormsdataTable"];
                }

                if (dataTable != null)
                {
                    if (dataTable.Rows.Count > 0)
                    {
                        string fieldType = "Text";
                        int    rows      = 0;
                        foreach (DataRow row in dataTable.Rows)
                        {
                            if (!row[7].ToString().Trim().ToLower().Equals("false"))
                            {
                                rows     += 1;
                                fieldType = row[1].ToString();

                                switch (fieldType)
                                {
                                case "Title":
                                {
                                    lblTitle.Text = row[4].ToString().Trim();
                                }
                                break;

                                case "Success":
                                {
                                    success_msg.InnerText = row[4].ToString().Trim();
                                }
                                break;

                                case "Text":
                                {
                                    Label lbl = new Label();
                                    lbl.ID   = "lbl" + row[2].ToString();
                                    lbl.Text = row[3].ToString();
                                    lbl.Text = lbl.Text + " : ";
                                    lbl.Style.Add("font-weight", "bold");
                                    myPlaceHolder.Controls.Add(lbl);

                                    TextBox textBox = new TextBox();
                                    textBox.ID = row[2].ToString().Trim();
                                    textBox.Attributes.Add("placeholder", row[4].ToString().Trim());
                                    textBox.Style.Add("border", "1px solid rgba(34, 34, 34, 0.5)");
                                    //textBox.Style.Add("margin-left", "10px");

                                    if (myPlaceHolder.FindControl(textBox.ID) == null)
                                    {
                                        myPlaceHolder.Controls.Add(textBox);
                                    }
                                    LiteralControl literalBreak = new LiteralControl("<br /><br/>");
                                    myPlaceHolder.Controls.Add(literalBreak);
                                }
                                break;

                                case "MultiText":
                                {
                                    Label lbl = new Label();
                                    lbl.ID   = "lbl" + row[2].ToString().Trim();
                                    lbl.Text = row[3].ToString().Trim();
                                    lbl.Text = lbl.Text + " :  ";
                                    lbl.Style.Add("font-weight", "bold");
                                    myPlaceHolder.Controls.Add(lbl);

                                    TextBox textBox = new TextBox();
                                    textBox.ID = row[2].ToString().Trim();
                                    textBox.Attributes.Add("placeholder", row[4].ToString().Trim());
                                    textBox.TextMode = TextBoxMode.MultiLine;
                                    textBox.Style.Add("width", "18%");
                                    textBox.Style.Add("border", "1px solid rgba(34, 34, 34, 0.5)");
                                    //textBox.Style.Add("width", "162px");
                                    //textBox.Style.Add("height", "16px");
                                    //textBox.Style.Add("margin-left", "2px");


                                    if (myPlaceHolder.FindControl(textBox.ID) == null)
                                    {
                                        myPlaceHolder.Controls.Add(textBox);
                                    }
                                    LiteralControl literalBreak = new LiteralControl("<br /><br/>");
                                    myPlaceHolder.Controls.Add(literalBreak);
                                }
                                break;

                                case "Radio":
                                {
                                    Label lbl = new Label();
                                    lbl.ID   = "lbl" + row[2].ToString().Trim();
                                    lbl.Text = row[3].ToString().Trim();
                                    lbl.Text = lbl.Text + " :  ";
                                    lbl.Style.Add("font-weight", "bold");
                                    myPlaceHolder.Controls.Add(lbl);

                                    int i = 0;
                                    foreach (string strItem in row[2].ToString().Trim().Split(';'))
                                    {
                                        if (!strItem.Equals(""))
                                        {
                                            RadioButton radioButton = new RadioButton();
                                            radioButton.GroupName = "RadioGroup" + rows.ToString();
                                            //radioButton.Style.Add("margin-left", "2px");


                                            if (row[4].ToString().Trim().Split(';').Length >= i)
                                            {
                                                radioButton.Text = row[4].ToString().Trim().Split(';')[i];
                                                radioButton.ID   = row[2].ToString().Trim().Split(';')[i];
                                                if (i == 0)
                                                {
                                                    radioButton.Checked = true;
                                                }
                                            }
                                            if (myPlaceHolder.FindControl(radioButton.ID) == null)
                                            {
                                                myPlaceHolder.Controls.Add(radioButton);
                                            }
                                            i++;
                                        }
                                    }
                                    LiteralControl literalBreak = new LiteralControl("<br /><br />");
                                    myPlaceHolder.Controls.Add(literalBreak);
                                }
                                break;

                                case "Check":
                                {
                                    Label lbl = new Label();
                                    lbl.ID   = "lbl" + row[2].ToString().Trim();
                                    lbl.Text = row[3].ToString().Trim();
                                    lbl.Text = lbl.Text + " :  ";
                                    lbl.Style.Add("font-weight", "bold");
                                    myPlaceHolder.Controls.Add(lbl);

                                    int i = 0;
                                    foreach (string strItem in row[4].ToString().Trim().Split(';'))
                                    {
                                        if (!strItem.Equals(""))
                                        {
                                            CheckBox checkBox = new CheckBox();
                                            //checkBox.Style.Add("margin-left", "2px");

                                            if (row[4].ToString().Trim().Split(';').Length >= i)
                                            {
                                                checkBox.Text = row[4].ToString().Trim().Split(';')[i];
                                                checkBox.ID   = row[2].ToString().Trim().Split(';')[i];
                                            }
                                            if (myPlaceHolder.FindControl(checkBox.ID) == null)
                                            {
                                                myPlaceHolder.Controls.Add(checkBox);
                                            }
                                            i++;
                                        }
                                    }
                                    LiteralControl literalBreak = new LiteralControl("<br /><br />");
                                    myPlaceHolder.Controls.Add(literalBreak);
                                }
                                break;

                                case "DropDown":
                                {
                                    Label lbl = new Label();
                                    lbl.ID   = "lbl" + row[2].ToString().Trim();
                                    lbl.Text = row[3].ToString().Trim();
                                    lbl.Text = lbl.Text + " :  ";
                                    lbl.Style.Add("font-weight", "bold");
                                    myPlaceHolder.Controls.Add(lbl);

                                    DropDownList dropdownList = new DropDownList();
                                    dropdownList.ID = row[2].ToString().Trim();
                                    //dropdownList.Style.Add("border", "1px solid rgba(34, 34, 34, 0.5)");
                                    //dropdownList.Style.Add("margin-left", "2px");

                                    foreach (string strItem in row[4].ToString().Trim().Split(';'))
                                    {
                                        if (!strItem.Equals(""))
                                        {
                                            dropdownList.Items.Add(strItem);
                                        }
                                    }
                                    if (myPlaceHolder.FindControl(dropdownList.ID) == null)
                                    {
                                        myPlaceHolder.Controls.Add(dropdownList);
                                    }
                                    LiteralControl literalBreak = new LiteralControl("<br /><br />");
                                    myPlaceHolder.Controls.Add(literalBreak);
                                }
                                break;

                                default:

                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                success_msg.Visible = false;
                error_msg.Visible   = true;
                error_msg.InnerText = exc.Message;
            }
        }
Example #43
0
        private void LoadSettings()
        {
            Module module = new Module(ModuleGuid);

            config = new ModuleConfiguration(module);

            if (config.MarkupDefinition != null)
            {
                displaySettings = config.MarkupDefinition;
            }

            if (ModuleConfiguration != null)
            {
                Title       = ModuleConfiguration.ModuleTitle;
                Description = ModuleConfiguration.FeatureName;
            }
            StringBuilder moduleTitle = new StringBuilder();

            moduleTitle.Append(displaySettings.ModuleTitleMarkup);
            SuperFlexiHelpers.ReplaceStaticTokens(moduleTitle, config, IsEditable, displaySettings, ModuleId, PageId, out moduleTitle);
            litModuleTitle.Text = moduleTitle.ToString();

            if (config.InstanceCssClass.Length > 0 && !config.HideOuterWrapperPanel)
            {
                pnlOuterWrap.SetOrAppendCss(config.InstanceCssClass.Replace("$_ModuleID_$", ModuleId.ToString()));
            }

            if (SiteUtils.IsMobileDevice() && config.MobileInstanceCssClass.Length > 0 && !config.HideOuterWrapperPanel)
            {
                pnlOuterWrap.SetOrAppendCss(config.MobileInstanceCssClass.Replace("$_ModuleID_$", ModuleId.ToString()));
            }

            theWidget.Config = config;
            PageSettings currentPage = CacheHelper.GetCurrentPage();

            if (currentPage != null)
            {
                theWidget.PageId = currentPage.PageId;
            }
            theWidget.ModuleId      = ModuleId;
            theWidget.IsEditable    = IsEditable;
            theWidget.SiteRoot      = SiteRoot;
            theWidget.ImageSiteRoot = ImageSiteRoot;

            //theWidgetRazor.Config = config;
            //theWidgetRazor.PageId = PageId;
            //theWidgetRazor.ModuleId = ModuleId;
            //theWidgetRazor.IsEditable = IsEditable;
            //theWidgetRazor.SiteRoot = SiteRoot;
            //theWidgetRazor.ImageSiteRoot = ImageSiteRoot;

            theWidget.Visible = true;
            //theWidgetRazor.Visible = config.UseRazor;

            if (config.UseHeader && config.HeaderLocation != "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p>&nbsp;</p>"))
            {
                StringBuilder headerContent = new StringBuilder();
                headerContent.AppendFormat(displaySettings.HeaderContentFormat, config.HeaderContent);
                SuperFlexiHelpers.ReplaceStaticTokens(headerContent, config, IsEditable, displaySettings, ModuleId, PageId, out headerContent);
                LiteralControl litHeaderContent = new LiteralControl(headerContent.ToString());
                //if HeaderLocation is set to a hidden panel the header will be added to the Outside.
                switch (config.HeaderLocation)
                {
                default:
                    break;

                case "OuterBodyPanel":
                    if (config.HideOuterBodyPanel)
                    {
                        goto case "Outside";
                    }
                    pnlOuterBody.Controls.AddAt(0, litHeaderContent);
                    break;

                case "InnerWrapperPanel":
                    if (config.HideInnerWrapperPanel)
                    {
                        goto case "Outside";
                    }
                    pnlInnerWrap.Controls.AddAt(0, litHeaderContent);
                    break;

                case "OuterWrapperPanel":
                    if (config.HideOuterWrapperPanel)
                    {
                        goto case "Outside";
                    }
                    pnlOuterWrap.Controls.AddAt(0, litHeaderContent);
                    break;

                case "Outside":
                    litHead.Text = headerContent.ToString();
                    break;
                }
            }

            if (config.UseFooter && config.FooterLocation != "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p>&nbsp;</p>"))
            {
                StringBuilder footerContent = new StringBuilder();
                footerContent.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent);
                SuperFlexiHelpers.ReplaceStaticTokens(footerContent, config, IsEditable, displaySettings, ModuleId, PageId, out footerContent);
                LiteralControl litFooterContent = new LiteralControl(footerContent.ToString());
                //if FooterLocation is set to a hidden panel the footer will be added to the Outside.
                switch (config.FooterLocation)
                {
                default:
                    break;

                case "OuterBodyPanel":
                    if (config.HideOuterBodyPanel)
                    {
                        goto case "Outside";
                    }
                    pnlOuterBody.Controls.Add(litFooterContent);
                    break;

                case "InnerWrapperPanel":
                    if (config.HideInnerWrapperPanel)
                    {
                        goto case "Outside";
                    }
                    pnlInnerWrap.Controls.Add(litFooterContent);
                    break;

                case "OuterWrapperPanel":
                    if (config.HideOuterWrapperPanel)
                    {
                        goto case "Outside";
                    }
                    pnlOuterWrap.Controls.Add(litFooterContent);
                    break;

                case "Outside":
                    litFoot.Text = footerContent.ToString();
                    break;
                }
            }

            pnlOuterWrap.RenderContentsOnly = config.HideOuterWrapperPanel;
            pnlInnerWrap.RenderContentsOnly = config.HideInnerWrapperPanel;
            pnlOuterBody.RenderContentsOnly = config.HideOuterBodyPanel;
            pnlInnerBody.RenderContentsOnly = config.HideInnerBodyPanel;
        }
Example #44
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            account = new Account(appEnv.GetConnection());
            content = new Content(appEnv.GetConnection());
            notes   = new ContentNotes(appEnv.GetConnection());

            DataTable dt;
            int       accountNo = account.GetAccountID(User.Identity.Name);

            if (accountNo == 1)  // Admin sees all
            {
                dt = content.GetHeadlines();
            }
            else
            {
                dt = content.GetHeadlinesForAuth(accountNo);
            }

            LiteralControl lit;
            TableCell      cell;
            int            prv = -1;
            int            cur;

            foreach (DataRow dr in dt.Rows)
            {
                cur = Convert.ToInt32(dr["ContentID"]);

                if (cur != prv)
                {
                    prv = cur;

                    if (IsTypeRequested(dr["Status"].ToString()))
                    {
                        TableRow row = new TableRow();
                        tblView.Rows.Add(row);

                        lit  = new LiteralControl(dr["ContentID"].ToString());
                        cell = new TableCell();
                        cell.Controls.Add(lit);
                        cell.HorizontalAlign = HorizontalAlign.Center;
                        row.Cells.Add(cell);

                        lit  = new LiteralControl(dr["Version"].ToString());
                        cell = new TableCell();
                        cell.Controls.Add(lit);
                        cell.HorizontalAlign = HorizontalAlign.Center;
                        row.Cells.Add(cell);

                        lit  = new LiteralControl(dr["Headline"].ToString());
                        cell = new TableCell();
                        cell.Controls.Add(lit);
                        row.Cells.Add(cell);

                        lit = new LiteralControl(StatusCodes.ToString(
                                                     Convert.ToInt32(dr["Status"])));
                        cell                 = new TableCell();
                        cell.Font.Size       = new FontUnit(FontSize.XSmall);
                        cell.HorizontalAlign = HorizontalAlign.Center;
                        cell.Controls.Add(lit);
                        row.Cells.Add(cell);

                        BuildImageButton(row, "AutView.aspx?ContentID=" + dr["ContentID"].ToString(), -1);
                        BuildImageButton(row, "../Note/NoteList.aspx?ContentID=" + dr["ContentID"].ToString() + "&Origin=Author",
                                         notes.CountNotesForID(Convert.ToInt32(dr["ContentID"])));

                        if (StatusCodes.isCreating(dr["Status"].ToString()))
                        {
                            BuildImageButton(row, "AutUpdate.aspx?ContentID=" + dr["ContentID"].ToString(), -1);
                            BuildImageButton(row, "AutSubmit.aspx?ContentID=" + dr["ContentID"].ToString(), -1);
                            BuildImageButton(row, "AutRemove.aspx?ContentID=" + dr["ContentID"].ToString(), -1);
                        }
                        else
                        {
                            BuildImageButton(row, null, -1);
                            BuildImageButton(row, null, -1);
                            BuildImageButton(row, null, -1);
                        }
                    }
                }
            }
        }
Example #45
0
        private void editPreviewActivity_ExecuteCode(object sender, EventArgs e)
        {
            Stopwatch functionCallingStopwatch = null;
            long      millisecondsToken        = 0;

            CultureInfo oldCurrentCulture   = Thread.CurrentThread.CurrentCulture;
            CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                IXsltFunction xslt = this.GetBinding <IXsltFunction>("CurrentXslt");

                string xslTemplate = this.GetBinding <string>("XslTemplate");

                IFile persistemTemplateFile = IFileServices.TryGetFile <IXsltFile>(xslt.XslFilePath);
                if (persistemTemplateFile != null)
                {
                    string persistemTemplate = persistemTemplateFile.ReadAllText();

                    if (this.GetBinding <int>("XslTemplateLastSaveHash") != persistemTemplate.GetHashCode())
                    {
                        xslTemplate = persistemTemplate;
                        ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem {
                            Level = LogLevel.Fine, Message = "XSLT file on file system was used. It has been changed by another process.", Sender = this.GetType()
                        }, this.GetCurrentConsoleId());
                    }
                }

                List <NamedFunctionCall> namedFunctions = this.GetBinding <IEnumerable <NamedFunctionCall> >("FunctionCalls").ToList();

                // If preview is done multiple times in a row, with no postbacks an object reference to BaseFunctionRuntimeTreeNode may be held
                // If the function in the BaseFunctionRuntimeTreeNode have ben unloaded / reloaded, this preview will still run on the old instance
                // We force refresh by serializing / deserializing
                foreach (NamedFunctionCall namedFunction in namedFunctions)
                {
                    namedFunction.FunctionCall = (BaseFunctionRuntimeTreeNode)FunctionFacade.BuildTree(namedFunction.FunctionCall.Serialize());
                }


                List <ManagedParameterDefinition> parameterDefinitions = this.GetBinding <IEnumerable <ManagedParameterDefinition> >("Parameters").ToList();

                Guid        pageId        = this.GetBinding <Guid>("PageId");
                string      dataScopeName = this.GetBinding <string>("PageDataScopeName");
                string      cultureName   = this.GetBinding <string>("ActiveCultureName");
                CultureInfo cultureInfo   = null;
                if (cultureName != null)
                {
                    cultureInfo = CultureInfo.CreateSpecificCulture(cultureName);
                }

                IPage page;

                TransformationInputs transformationInput;
                using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                {
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    page = DataFacade.GetData <IPage>(f => f.Id == pageId).FirstOrDefault();
                    if (page != null)
                    {
                        PageRenderer.CurrentPage = page;
                    }

                    functionCallingStopwatch = Stopwatch.StartNew();
                    transformationInput      = RenderHelper.BuildInputDocument(namedFunctions, parameterDefinitions, true);
                    functionCallingStopwatch.Stop();

                    Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                    Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
                }


                string output = "";
                string error  = "";
                try
                {
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    var styleSheet = XElement.Parse(xslTemplate);

                    XsltBasedFunctionProvider.ResolveImportIncludePaths(styleSheet);

                    LocalizationParser.Parse(styleSheet);

                    XDocument transformationResult = new XDocument();
                    using (XmlWriter writer = new LimitedDepthXmlWriter(transformationResult.CreateWriter()))
                    {
                        XslCompiledTransform xslTransformer = new XslCompiledTransform();
                        xslTransformer.Load(styleSheet.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver());

                        XsltArgumentList transformArgs = new XsltArgumentList();
                        XslExtensionsManager.Register(transformArgs);

                        if (transformationInput.ExtensionDefinitions != null)
                        {
                            foreach (IXsltExtensionDefinition extensionDef in transformationInput.ExtensionDefinitions)
                            {
                                transformArgs.AddExtensionObject(extensionDef.ExtensionNamespace.ToString(),
                                                                 extensionDef.EntensionObjectAsObject);
                            }
                        }

                        Exception   exception   = null;
                        HttpContext httpContext = HttpContext.Current;

                        Thread thread = new Thread(delegate()
                        {
                            Thread.CurrentThread.CurrentCulture   = cultureInfo;
                            Thread.CurrentThread.CurrentUICulture = cultureInfo;

                            Stopwatch transformationStopwatch = Stopwatch.StartNew();

                            try
                            {
                                using (ThreadDataManager.Initialize())
                                    using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                                    {
                                        HttpContext.Current = httpContext;

                                        var reader = transformationInput.InputDocument.CreateReader();
                                        xslTransformer.Transform(reader, transformArgs, writer);
                                    }
                            }
                            catch (ThreadAbortException ex)
                            {
                                exception = ex;
                                Thread.ResetAbort();
                            }
                            catch (Exception ex)
                            {
                                exception = ex;
                            }

                            transformationStopwatch.Stop();

                            millisecondsToken = transformationStopwatch.ElapsedMilliseconds;
                        });

                        thread.Start();
                        bool res = thread.Join(1000);  // sadly, this needs to be low enough to prevent StackOverflowException from fireing.

                        if (res == false)
                        {
                            if (thread.ThreadState == System.Threading.ThreadState.Running)
                            {
                                thread.Abort();
                            }
                            throw new XslLoadException("Transformation took more than 1000 milliseconds to complete. This could be due to a never ending recursive call. Execution aborted to prevent fatal StackOverflowException.");
                        }

                        if (exception != null)
                        {
                            throw exception;
                        }
                    }

                    if (xslt.OutputXmlSubType == "XHTML")
                    {
                        XhtmlDocument xhtmlDocument = new XhtmlDocument(transformationResult);

                        output = xhtmlDocument.Root.ToString();
                    }
                    else
                    {
                        output = transformationResult.Root.ToString();
                    }
                }
                catch (Exception ex)
                {
                    output = "<error/>";
                    error  = string.Format("{0}\n{1}", ex.GetType().Name, ex.Message);

                    Exception inner = ex.InnerException;

                    string indent = "";

                    while (inner != null)
                    {
                        indent = indent + " - ";
                        error  = error + "\n" + indent + inner.Message;
                        inner  = inner.InnerException;
                    }
                }
                finally
                {
                    Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                    Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
                }

                Page currentPage = HttpContext.Current.Handler as Page;
                if (currentPage == null)
                {
                    throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page");
                }

                UserControl inOutControl = (UserControl)currentPage.LoadControl(UrlUtils.ResolveAdminUrl("controls/Misc/MarkupInOutView.ascx"));
                inOutControl.Attributes.Add("in", transformationInput.InputDocument.ToString());
                inOutControl.Attributes.Add("out", output);
                inOutControl.Attributes.Add("error", error);
                inOutControl.Attributes.Add("statusmessage", string.Format("Execution times: Total {0} ms. Functions: {1} ms. XSLT: {2} ms.",
                                                                           millisecondsToken + functionCallingStopwatch.ElapsedMilliseconds,
                                                                           functionCallingStopwatch.ElapsedMilliseconds,
                                                                           millisecondsToken));

                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                var webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(inOutControl);
            }
            catch (Exception ex)
            {
                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                Control errOutput        = new LiteralControl("<pre>" + ex.ToString() + "</pre>");
                var     webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(errOutput);
            }
        }
Example #46
0
//-------------------------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            IEnumerable <MetaColumn> columns = Table.GetScaffoldColumns(this.Mode, this.ContainerType);

            List <string> Groups = new List <string>();

            foreach (MetaColumn column in columns)
            {
                this.currentColumn = column;

                var groupattribute            = column.GetAttribute <ColumnGroupAttribute>();
                HtmlGenericControl tabContent = (HtmlGenericControl)GeneralControls;
                if (groupattribute != null)
                {
                    string groupId = groupattribute.GroupName.Replace(" ", "_");
                    if (!Groups.Contains(groupId))
                    {
                        Groups.Add(groupId);

                        var div = new HtmlGenericControl("div");
                        div.ID = groupId;
                        Tabs.Controls.Add(div);

                        LiteralControl tab = new LiteralControl();
                        tab.Text = "<li><a href=\"#" + div.ClientID + "\">" + groupattribute.GroupName + "</a></li>";
                        tabheader.Controls.Add(tab);
                    }
                    tabContent = (HtmlGenericControl)Tabs.FindControl(groupId);
                }


                HtmlGenericControl cellLine = new HtmlGenericControl("div");
                cellLine.Attributes["class"] = "formLine";
                tabContent.Controls.Add(cellLine);

                HtmlGenericControl cellLabel = new HtmlGenericControl("div");
                cellLabel.Attributes["class"] = "formLabel";
                cellLabel.InnerText           = column.DisplayName + ":";
                cellLine.Controls.Add(cellLabel);

                HtmlGenericControl cellData = new HtmlGenericControl("div");
                cellData.Attributes["class"] = "formData";
                var dynamicControl = new DynamicControl()
                {
                    Mode            = Mode,
                    DataField       = column.Name,
                    ValidationGroup = this.ValidationGroup
                };
                cellData.Controls.Add(dynamicControl);
                cellLine.Controls.Add(cellData);

                HtmlGenericControl br = new HtmlGenericControl("div");
                br.Style["clear"]  = "both";
                br.Style["height"] = "1px";
                cellLine.Controls.Add(br);
            }


            var clearDiv = new HtmlGenericControl("div");

            clearDiv.InnerHtml      = "&nbsp;";
            clearDiv.Style["clear"] = "both";
            GeneralControls.Controls.Add(clearDiv);

            //if (tabheader.Controls.Count == 1)
            //{
            //     tabheader.Controls.Clear();
            //}
            //else
            {
                string script = "<script type='text/javascript'>$(document).ready(function () { $(\"#tableControl\").tabs(); });</script>";
                ScriptManager.RegisterStartupScript(Page, GetType(), "TableControlInit", script, false);
            }
        }
Example #47
0
    private bool AddCustomControl(string tag, string tablename, string paramname,
                                  int HPosition, int VPosition, DataRow param, bool IsAlias, TableCell TCell)
    {
        if (tag == "")
        {
            return(false);
        }
        int    dotpos = tag.IndexOf(".");
        string tipo   = tag.Substring(0, dotpos);

        string[] token = tag.Substring(dotpos + 1).Split('|');

        switch (tipo.ToLower())
        {
        case "check":
            hwCheckBox ctrl = new hwCheckBox();
            ctrl.Tag   = tablename + "." + paramname + ":" + token[0] + ":" + token[1];
            ctrl.Text  = token[2];
            ctrl.Width = ControlWidth - 20;
            TCell.Controls.Add(ctrl);
            TCell.Style.Add("text-align", "left");
            TCell.Style.Add("vertical-align", "top");

            //ctrl.Style.Add("left", HPosition.ToString());
            //ctrl.Style.Add("top", VPosition + 8);
            //ctrl.Location = new Point(HPosition, VPosition + 8);
            if (OnePrintObbligatorio && paramname == "oneprint")
            {
                ctrl.Enabled = false;
            }
            break;

        case "radio":
            hwPanel        grp = InserisciGroupBox(param, TCell);
            LiteralControl br;
            int            i;
            Unit           Altezza = new Unit(0);
            for (i = 0; i < token.Length / 2; i++)
            {
                hwRadioButton rb = new hwRadioButton();
                rb.Tag  = tablename + "." + paramname + ":" + token[2 * i];
                rb.Text = token[2 * i + 1];
                //rb.Width = ControlWidth - 20;
                rb.Height = LabelHeight;
                //TCell.Controls.Add(rb);
                grp.Controls.Add(rb);
                br = new LiteralControl("<br/>");
                grp.Controls.Add(br);
                TCell.Controls.Add(grp);
                // come li piazziamo
                //rb.Location = new Point(12, Altezza);
                // Serve incrementarlo??
                Altezza = new Unit(Altezza.Value + rb.Height.Value);
            }
            grp.Height = new Unit(Altezza.Value + grp.Height.Value);     //Altezza + 10;
            //this.VPosition += (grp.Height - HelpHeight - 4);

            break;

        case "custom":
            string selectioncode = token[0];
            //ReportVista.customselectionDataTable T = reportVista1.customselection;
            //DataRow selRow = T.FindByselectioncode(selectioncode);
            DataTable T      = ExportVista.customselection;
            string    filter = QHC.CmpEq("selectioncode", selectioncode);
            DataRow[] selRow = T.Select(filter);

            if (selRow == null || selRow.Length == 0)
            {
                return(false);
            }
            string parenttable   = selRow[0]["tablename"].ToString();
            string editlisttype  = selRow[0]["editlisttype"].ToString();
            string selectiontype = selRow[0]["selectiontype"].ToString();
            string fieldname     = selRow[0]["fieldname"].ToString();
            filter = myDA.Compile(selRow[0]["filter"].ToString(), true);
            string filterapp = filter;
            AddCustomTableToDS(selRow[0], paramname, IsAlias);
            if (IsAlias)
            {
                parenttable += AliasCount;
            }

            GestioneClass GestAttributi = GestioneClass.GetGestioneClassForField(selectioncode, myDA, parenttable);

            if (GestAttributi != null)
            {
                selectiontype = "C";
                if (GestAttributi.AllowSelection() == false)
                {
                    myPrymaryTable.Columns[paramname].DefaultValue = GestAttributi.DefaultValue();
                    myPrymaryTable.Columns[paramname].AllowDBNull  = GestAttributi.AllowNull();
                    return(false);
                }
            }

            if (filter != "")
            {
                filterapp = "." + filterapp;
            }



            // C(hoose) o M(anage)?
            bool IsAutoManage  = (selectiontype.ToUpper() == "M");
            bool IsAutoChoose  = (selectiontype.ToUpper() == "C");
            bool IsComboManage = (selectiontype.ToUpper() == "U");

            // Si riporta la patch relativa al task 2525
            if (false)       //(paramname == "idupb" && Session["codiceresponsabile"] != null)
            {
                // Invece di inserire il groupbox, se sono un responsabile
                // Inserisco la classica dropdown e la filtro.

                hwDropDownList CB = new hwDropDownList();
                CB.Style.Add("width", "302px");

                string tablename2 = param["datasource"].ToString();
                string paramname2 = param["paramname"].ToString();
                if (IsAlias)
                {
                    tablename2 += AliasCount;
                }
                //CB.Location = new Point(btn.Location.X + btn.Width + 1, 14);
                //CB.Width = ControlWidth - btn.Width - 20;
                CB.ID = paramname;
                //CB.DropDownStyle = ComboBoxStyle.DropDownList;
                CB.Tag = myPrymaryTable.TableName + "." + paramname2;
                string cmbfilter;
                cmbfilter = QHC.AppAnd(QHC.DoPar(QHC.AppOr(QHC.IsNull("idman"), QHC.CmpEq("idman", Session["codiceresponsabile"]))), QHC.CmpEq("active", "S"));

                GetData.SetStaticFilter(DS.Tables[tablename2], cmbfilter);

                hwLabel LB = InserisciLabel(param, TCell);

                CB.DataSource     = DS.Tables[tablename2];
                CB.DataValueField = "idupb";
                CB.DataTextField  = "title";
                CB.AutoPostBack   = true;
                TCell.Controls.Add(CB);
                return(false);
            }


            //Inserisco un groupbox
            hwPanel gb = InserisciGroupBox(param, selRow[0]["selectionname"].ToString(), TCell);
            //gb.Style.Add("background-color", "#bababa;");
            //gb.Style.Add("border", "1px solid grey");
            //gb.Style.Add("width", "95%");

            //aggiungo un button
            hwButton btn = new hwButton();
            btn.ID   = "btn" + paramname;
            btn.Text = "Seleziona";
            //btn.Location = new Point(12, 14);
            btn.Style.Add("width", "85px");
            //btn.Height = TextHeight - 9;
            gb.Controls.Add(btn);
            LiteralControl nbsp = new LiteralControl("&nbsp;");
            gb.Controls.Add(nbsp);

            hwTextBox TBP = null;
            if (IsAutoChoose || IsAutoManage)
            {
                //e un textbox
                TBP    = new hwTextBox();
                TBP.ID = paramname;

                //TBP.Location = new Point(btn.Location.X + btn.Width + 1, 14);
                //TBP.Width = ControlWidth - btn.Width - 20;
                //TBP.Height = TextHeight;
                TBP.Tag = parenttable + "." + fieldname + "?x";
                TBP.Style.Add("width", "179px");
                gb.Controls.Add(TBP);
            }
            if (IsComboManage)
            {
                btn.Tag = "manage." + parenttable + "." + editlisttype + filterapp;

                hwDropDownList CBP = new hwDropDownList();

                string tablename2 = param["datasource"].ToString();
                string paramname2 = param["paramname"].ToString();
                if (IsAlias)
                {
                    tablename2 += AliasCount;
                }
                hwDropDownList CB = new hwDropDownList();
                CB.Style.Add("width", "179px");
                //CB.Location = new Point(btn.Location.X + btn.Width + 1, 14);
                //CB.Width = ControlWidth - btn.Width - 20;
                CB.ID = paramname;
                //CB.DropDownStyle = ComboBoxStyle.DropDownList;
                CB.Tag            = myPrymaryTable.TableName + "." + paramname2;
                CB.DataSource     = DS.Tables[tablename2];
                CB.DataValueField = param["valuemember"].ToString();
                CB.DataTextField  = param["displaymember"].ToString();
                CB.AutoPostBack   = true;
                if ((paramname.IndexOf("level") >= 0) && (param["hintkind"].ToString().ToUpper() == "NOHINT"))
                {
                    ComboToPreset.Add(CB);
                }
                gb.Controls.Add(CB);
                TCell.Controls.Add(gb);
            }

            if (GestAttributi != null)
            {
                TBP.Style.Add("text-align", "left");
                TBP.Style.Add("width", "179px");
                btn.Tag = GestAttributi.BtnTag();
                gb.Tag  = "AutoChoose." + TBP.ID + "." + editlisttype + "." + GestAttributi.GetFilterAutoChoose();
            }
            else
            {
                if (IsAutoManage)
                {
                    TBP.Style.Add("text-align", "right");
                    //TBP.TextAlign = HorizontalAlignment.Right;
                    btn.Tag = "manage." + parenttable + "." + editlisttype + filterapp;
                    gb.Tag  = "AutoManage." + parenttable + "." + editlisttype + filterapp;
                }
                if (IsAutoChoose)
                {
                    TBP.Style.Add("text-align", "left");
                    TBP.Style.Add("width", "179px");
                    //TBP.TextAlign = HorizontalAlignment.Left;
                    btn.Tag = "choose." + parenttable + "." + editlisttype + filterapp;
                    gb.Tag  = "AutoChoose." + TBP.ID + "." + editlisttype + filterapp;
                }
            }

            break;

        case "costant":
            //controlli il cui valore è costante (es. il filtro bilancio deve essere 'E')
            bool    visible = !(token[0].ToLower() == "hidden");
            hwLabel lb      = InserisciLabel(param, TCell);
            lb.Visible = visible;
            hwTextBox tb = InserisciTextBox(param, TCell);
            if (!visible)
            {
                tb.Style.Add("display", "none");
            }
            tb.ReadOnly = true;
            if (!visible)
            {
                return(false);
            }
            break;
        }
        return(true);
    }
Example #48
0
        protected override void OnPreInit(EventArgs e)
        {
            if (HttpContext.Current != null)
            {
                m_ThisCustomer = ((InterpriseSuiteEcommercePrincipal)Context.User).ThisCustomer;

                if (AppLogic.AppConfigBool("GoogleCheckout.ShowOnCartPage"))
                {
                    string s = CachingFactory.ApplicationCachingEngineInstance.GetItem <string>(DomainConstants.GCCallbackLoadCheck);
                    if (s != null)
                    {
                        string notused = CommonLogic.AspHTTP(AppLogic.GetStoreHTTPLocation(false) + "gccallback.aspx?loadcheck=1", 10);
                        CachingFactory.ApplicationCachingEngineInstance.AddItem(DomainConstants.GCCallbackLoadCheck, "true", 5);
                    }
                }

                if (!CurrentContext.IsInAdminRoot() &&
                    (AppLogic.AppConfigBool("SiteDisclaimerRequired") &&
                     CommonLogic.CookieCanBeDangerousContent("SiteDisclaimerAccepted", true).IsNullOrEmptyTrimmed()))
                {
                    string ThisPageURL = CommonLogic.GetThisPageName(true) + "?" + CommonLogic.ServerVariables("QUERY_STRING");
                    Response.Redirect("disclaimer.aspx?returnURL=" + Server.UrlEncode(ThisPageURL));
                }

                Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(ThisCustomer.LocaleSetting);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(ThisCustomer.LocaleSetting);
                LoadSkinTemplate();
                m_Parser = new Parser(m_EntityHelpers, m_SkinID, m_ThisCustomer);
                m_Parser.RenderHeader += this.OnRenderHeader;

                if (this.HasControls())
                {
                    foreach (Control c in this.Controls)
                    {
                        FindLocaleStrings(c);
                    }

                    Control ctl;
                    int     i         = 1;
                    int     limitLoop = 1000;
                    if (m_Template != null && m_Template.Content != null)
                    {
                        while (this.Controls.Count > 0 && i <= limitLoop)
                        {
                            bool FilterItOut = false;
                            ctl = this.Controls[0];
                            LiteralControl l = ctl as LiteralControl;
                            if (l != null)
                            {
                                string txtVal = l.Text;
                                if (txtVal.IndexOf("<html", StringComparison.InvariantCultureIgnoreCase) != -1 ||
                                    txtVal.IndexOf("</html", StringComparison.InvariantCultureIgnoreCase) != -1)
                                {
                                    FilterItOut = true; // remove outer html/body crap, as we're going to be moving the page controls INSIDE The skin
                                }
                            }
                            if (!FilterItOut)
                            {
                                // reparent the page control to be moved inside the skin template user control
                                m_Template.Content.Controls.Add(ctl);
                            }
                            else
                            {
                                this.Controls.RemoveAt(0);
                            }
                            i++;
                        }
                    }

                    // clear the controls (they were now all moved inside the template user control:
                    this.Controls.Clear();
                    // set the template user control to be owned by this page:
                    this.Controls.Add(m_Template);

                    //register the ScriptManager before loading controls or the ComponentArt menu won't work with AJAX pages
                    CheckIfRequireScriptManager();

                    // Now move the template child controls up to the page level so the ViewState will load
                    while (m_Template.Controls.Count > 0)
                    {
                        this.Controls.Add(m_Template.Controls[0]);
                    }
                }

                if (AppLogic.IsCBNMode() && m_ThisCustomer != null)
                {
                    var cart = new ShoppingCart(m_ThisCustomer.SkinID, m_ThisCustomer, CartTypeEnum.ShoppingCart, string.Empty, false);
                    if (!cart.IsEmpty())
                    {
                        //empty shopping cart
                        cart.ClearContents();
                    }
                }

                string bingAdsTrackingScript = AppLogic.GetBingAdsTrackingScript();

                if (!bingAdsTrackingScript.IsNullOrEmptyTrimmed())
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), DB.GetNewGUID(), bingAdsTrackingScript, false);
                }
            }

            base.OnPreInit(e);
        }
Example #49
0
    protected void WriteTablesContent()
    {
        foreach (object[] table in tables)
        {
            // Prepare the components
            DataTable         dt            = (DataTable)table[0];
            LiteralControl    ltlContent    = (LiteralControl)table[1];
            UIPager           pagerElem     = (UIPager)table[2];
            UniPagerConnector connectorElem = (UniPagerConnector)table[3];

            // Handle the different types of direct page selector
            int currentPageSize = pagerElem.CurrentPageSize;
            if (currentPageSize > 0)
            {
                if (connectorElem.PagerForceNumberOfResults / (float)currentPageSize > 20.0f)
                {
                    pagerElem.DirectPageControlID = "txtPage";
                }
                else
                {
                    pagerElem.DirectPageControlID = "drpPage";
                }
            }

            // Bind the pager first
            connectorElem.RaiseOnPageBinding(null, null);

            // Prepare the string builder
            StringBuilder sb = new StringBuilder();

            // Prepare the indexes for paging
            int pageSize = pagerElem.CurrentPageSize;

            int startIndex = (pagerElem.CurrentPage - 1) * pageSize + 1;
            int endIndex   = startIndex + pageSize;

            // Process all items
            int  index = 0;
            bool all   = (endIndex <= startIndex);

            if (dt.Columns.Count > 6)
            {
                // Write all rows
                foreach (DataRow dr in dt.Rows)
                {
                    index++;
                    if (all || (index >= startIndex) && (index < endIndex))
                    {
                        sb.Append("<table class=\"table table-hover\">");

                        // Add header
                        sb.AppendFormat("<thead><tr class=\"unigrid-head\"><th>{0}</th><th class=\"main-column-100\">{1}</th></tr></thead><tbody>", GetString("General.FieldName"), GetString("General.Value"));

                        // Add values
                        foreach (DataColumn dc in dt.Columns)
                        {
                            object value = dr[dc.ColumnName];

                            // Binary columns
                            string content;
                            if ((dc.DataType == typeof(byte[])) && (value != DBNull.Value))
                            {
                                byte[] data = (byte[])value;
                                content = "<" + GetString("General.BinaryData") + ", " + DataHelper.GetSizeString(data.Length) + ">";
                            }
                            else
                            {
                                content = ValidationHelper.GetString(value, String.Empty);
                            }

                            if (!String.IsNullOrEmpty(content))
                            {
                                sb.AppendFormat("<tr><td><strong>{0}</strong></td><td class=\"wrap-normal\">", dc.ColumnName);

                                // Possible DataTime columns
                                if ((dc.DataType == typeof(DateTime)) && (value != DBNull.Value))
                                {
                                    DateTime    dateTime    = Convert.ToDateTime(content);
                                    CultureInfo cultureInfo = CultureHelper.GetCultureInfo(MembershipContext.AuthenticatedUser.PreferredUICultureCode);
                                    content = dateTime.ToString(cultureInfo);
                                }

                                // Process content
                                ProcessContent(sb, dr, dc.ColumnName, ref content);

                                sb.Append("</td></tr>");
                            }
                        }

                        sb.Append("</tbody></table>\n");
                    }
                }
            }
            else
            {
                sb.Append("<table class=\"table table-hover\">");

                // Add header
                sb.Append("<thead><tr class=\"unigrid-head\">");
                int h = 1;
                foreach (DataColumn column in dt.Columns)
                {
                    sb.AppendFormat("<th{0}>{1}</th>", (h == dt.Columns.Count) ? " class=\"main-column-100\"" : String.Empty, column.ColumnName);
                    h++;
                }
                sb.Append("</tr></thead><tbody>");

                // Write all rows
                foreach (DataRow dr in dt.Rows)
                {
                    index++;
                    if (all || (index >= startIndex) && (index < endIndex))
                    {
                        sb.Append("<tr>");

                        // Add values
                        foreach (DataColumn dc in dt.Columns)
                        {
                            object value = dr[dc.ColumnName];
                            // Possible DataTime columns
                            if ((dc.DataType == typeof(DateTime)) && (value != DBNull.Value))
                            {
                                DateTime    dateTime    = Convert.ToDateTime(value);
                                CultureInfo cultureInfo = CultureHelper.GetCultureInfo(MembershipContext.AuthenticatedUser.PreferredUICultureCode);
                                value = dateTime.ToString(cultureInfo);
                            }

                            string content = ValidationHelper.GetString(value, String.Empty);
                            content = HTMLHelper.HTMLEncode(content);

                            sb.AppendFormat("<td{0}>{1}</td>", (content.Length >= 100) ? " class=\"wrap-normal\"" : String.Empty, content);
                        }
                        sb.Append("</tr>");
                    }
                }
                sb.Append("</tbody></table>\n");
            }

            ltlContent.Text = sb.ToString();
        }
    }
Example #50
0
        public static void AddRevisionControl(this LiteralControl lc)
        {
            String rv = String.Concat("?Rev=", HttpContext.Current.Session["Version"].ToString(), "\"");

            lc.Text = lc.Text.Replace(".js\"", ".js" + rv).Replace(".css\"", ".css" + rv);
        }
Example #51
0
 public HtmlLabel() : base("label")
 {
     control = new LiteralControl();
 }
Example #52
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // The following code gets the client context that represents the host web.
            var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

            // Because this is a provider-hosted app, SharePoint will pass in the host Url in the querystring.
            // Therefore, we'll retrieve it so that we can use it in GetClientContextWithContextToken method call
            var hostWeb = Page.Request["SPHostUrl"];

            // Then we'll build our context, exactly as implemented in the Visual Studio template for provider-hosted apps
            using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            {
                // Now we will use some pretty standard CSOM operations to enumerate the
                // document libraries in the host web...
                Microsoft.SharePoint.Client.Web            hostedWeb = clientContext.Web;
                Microsoft.SharePoint.Client.ListCollection libs      = hostedWeb.Lists;
                clientContext.Load(hostedWeb);
                clientContext.Load(libs);
                clientContext.ExecuteQuery();
                var foundFiles = false;
                foreach (Microsoft.SharePoint.Client.List lib in libs)
                {
                    if (lib.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                    {
                        // ... and for each document library we'll enumerate all the Office files that
                        // may exist in the root folder of each library.
                        Microsoft.SharePoint.Client.Folder         folder = lib.RootFolder;
                        Microsoft.SharePoint.Client.FileCollection files  = folder.Files;
                        clientContext.Load(folder);
                        clientContext.Load(files);
                        clientContext.ExecuteQuery();
                        foreach (Microsoft.SharePoint.Client.File file in files)
                        {
                            if ((file.ServerRelativeUrl.ToLower().EndsWith(".docx")) ||
                                (file.ServerRelativeUrl.ToLower().EndsWith(".xlsx")) ||
                                (file.ServerRelativeUrl.ToLower().EndsWith(".pptx"))
                                )
                            {
                                // We know that we have at least one file, so we'll set the foundFiles variable to true
                                foundFiles = true;
                                // Then, for each Office file, we'll build a tile in the UI and set its style to an
                                // appropriate style that we have defined in point8020metro.css.
                                Panel fileItem = new Panel();
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".docx"))
                                {
                                    fileItem.CssClass = "tile tileWord fl";
                                }
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".xlsx"))
                                {
                                    fileItem.CssClass = "tile tileExcel fl";
                                }
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".pptx"))
                                {
                                    fileItem.CssClass = "tile tilePowerPoint fl";
                                }
                                // Then we'll add text to the tile to represent the name of the file
                                fileItem.Controls.Add(new LiteralControl(file.Name));

                                // And now we'll add a custom-styled link for opening the file in 'View' mode
                                // in the Office Web Access Companion
                                HyperLink fileView = new HyperLink();
                                fileView.CssClass    = "tileBodyView";
                                fileView.Text        = "";
                                fileView.ToolTip     = "View in browser";
                                fileView.Target      = "_blank";
                                fileView.Width       = new Unit(125);
                                fileView.NavigateUrl = hostedWeb.Url + "/_layouts/15/WopiFrame.aspx?sourcedoc=" + file.ServerRelativeUrl + "&action=view&source=" + hostedWeb.Url + file.ServerRelativeUrl;

                                // And finally we'll add a custom-styled link for opening the file in 'Edit' mode
                                // in the Office Web Access Companion
                                HyperLink fileEdit = new HyperLink();
                                fileEdit.CssClass    = "tileBodyEdit";
                                fileEdit.Text        = "";
                                fileEdit.ToolTip     = "Edit in browser";
                                fileEdit.Target      = "_blank";
                                fileEdit.Width       = new Unit(125);
                                fileEdit.NavigateUrl = hostedWeb.Url + "/_layouts/15/WopiFrame.aspx?sourcedoc=" + file.ServerRelativeUrl + "&action=edit&source=" + hostedWeb.Url + file.ServerRelativeUrl;

                                fileItem.Controls.Add(new LiteralControl("<br/>"));
                                fileItem.Controls.Add(fileView);
                                fileItem.Controls.Add(new LiteralControl("<br/>"));
                                fileItem.Controls.Add(fileEdit);
                                FileList.Controls.Add(fileItem);
                            }
                        }
                    }
                }
                SiteTitle.Text = "Office Web Access: " + hostedWeb.Title;
                // If no videos have been found, build a red tile to inform the user
                if (!foundFiles)
                {
                    LiteralControl noItems = new LiteralControl("<div id='" + Guid.NewGuid()
                                                                + "' class='tile tileRed fl'>There are no Office files in the parent Web</div>");
                    FileList.Controls.Add(noItems);
                }
            }
        }
Example #53
0
        protected override void OnInit(EventArgs e)
        {
            if (HasEditPermission())
            {
                this.HtmlHolder.EnableViewState = false;
            }
            else
            {
                this.HtmlHolder2.EnableViewState = false;
            }


            // Add title
            // ModuleTitle = new DesktopModuleTitle();
            this.EditUrl = "~/DesktopModules/CommunityModules/HTMLDocument/HtmlEdit.aspx";

            // Controls.AddAt(0, ModuleTitle);
            var text = new HtmlTextDB();

            this.Content = this.Server.HtmlDecode(text.GetHtmlTextString(this.ModuleID, this.Version));
            if (PortalSecurity.HasEditPermissions(this.ModuleID) && string.IsNullOrEmpty(this.Content.ToString()))
            {
                this.Content = "Add content here ...<br/><br/><br/><br/>";
            }



            this.HtmlLiteral              = new LiteralControl(this.Content.ToString());
            this.HtmlLiteral.DataBinding += HtmlLiteralDataBinding;
            this.HtmlLiteral.DataBind();
            if (HasEditPermission())
            {
                this.HtmlHolder.Controls.Add(this.HtmlLiteral);
            }
            else
            {
                this.HtmlHolder2.Controls.Add(this.HtmlLiteral);
            }

            //if (PortalSecurity.HasEditPermissions(this.ModuleID)) {
            //    var editor = Settings["Editor"].ToString();
            //    var width = int.Parse(Settings["Width"].ToString()) + 100;
            //    var height = int.Parse(Settings["Height"].ToString());
            //    if (editor.Equals("FreeTextBox")) {
            //        height += 220;
            //    } else if (editor.Equals("FCKeditor")) {
            //        height += 120;
            //    } else if (editor.Equals("TinyMCE Editor")) {
            //        height += 140;
            //    } else if (editor.Equals("Code Mirror Plain Text")) {
            //        height += 140;
            //    } else if (editor.Equals("Syrinx CkEditor")) {
            //        height += 300;
            //    } else {
            //        height += 140;
            //    }
            //    string title = Resources.Appleseed.HTML_TITLE;
            //    var url = HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/HTMLDocument/HtmlEditModal.aspx?mID="+this.ModuleID);
            //    this.HtmlModuleText.Attributes.Add("OnDblClick", "setDialog(" + ModuleID.ToString() + "," + width.ToString() + "," + (height + 10).ToString() + ");editHtml(" + ModuleID.ToString() + "," + this.PageID + ",\"" + url + "\");");
            //    this.HtmlModuleText.Attributes.Add("class", "Html_Edit");
            //    this.HtmlModuleDialog.Attributes.Add("class", "HtmlModuleDialog" + ModuleID.ToString());
            //    this.HtmlMoudleIframe.Attributes.Add("class", "HtmlMoudleIframe" + ModuleID.ToString());
            //    this.HtmlMoudleIframe.Attributes.Add("width", "98%");
            //    this.HtmlMoudleIframe.Attributes.Add("height", "99%");
            //    this.HtmlModuleText.Attributes.Add("title", title);
            //    this.HtmlModuleDialog.Attributes.Add("title", General.GetString("HTML_EDITOR", "Html Editor"));
            //    if ((Request.Browser.Browser.Contains("IE") || Request.Browser.Browser.Contains("ie")) && Request.Browser.MajorVersion == 7) {

            //        this.HTMLEditContainer.Attributes.Add("style", "position: relative;overflow: auto;");
            //    }
            //}

            base.OnInit(e);
        }
Example #54
0
    public void Algo(DataTable dt, DataTable rowsDeleted)
    {
        DataRowCollection dr    = dt.Rows;
        DataTable         dtnew = CreateDataTable();

        double teamAverage         = 0;
        int    totalTeams          = Convert.ToInt32(txtNoOfTeams.Text);
        int    totalPlayersPerTeam = Convert.ToInt32(txtNoOfPlayersPerTeam.Text);

        int[] arrForPuttingExtraDataInRandomTables;

        /*
         * if the total teams and players are equal i.e 10 10 = 100 and total players = 104
         * or if total teams and players are not equal and total teams are > total players i.e
         * total teams =14 total players =7 total players= 98 , total league players 104 , remaning
         * 6. 6 < total teams so these 6 players can be accomodated in 1 player per team randomly.
         * arrForPuttingExtraDataInRandomTables array will not through error.
         *
         * Now, if the total teams = 5 , total players per team = 18 , total = 90 , remaning 14.
         * if we make an array like this. then it will only make an array of 5 whereas total players that need
         * to be accomadeted are 14. This will through error. so the else case is used and
         * the array is genereted based on the remaning players. and as the remaning players are 14
         * and teams are 5. so multiple random players are added in the array. This means that each
         * team will accomodate more than 1 player.
         * arrForPuttingExtraDataInRandomTables = new int[totalTeams];
         *
         */

        if (totalTeams >= totalPlayersPerTeam)
        {
            arrForPuttingExtraDataInRandomTables = new int[totalTeams];
            for (int l = 0; l < totalTeams; l++)
            {
                arrForPuttingExtraDataInRandomTables[l] = l;
            }
        }
        else
        {
            arrForPuttingExtraDataInRandomTables = new int[rowsDeleted.Rows.Count];
            int totalTeamsVar = 0;
            for (int h = 0; h < rowsDeleted.Rows.Count; h++)
            {
                arrForPuttingExtraDataInRandomTables[h] = totalTeamsVar;
                totalTeamsVar++;
                if (totalTeamsVar == (totalTeams))
                {
                    totalTeamsVar = 0;
                }
            }
        }
        //This array contains the shuffled extra rows
        int[] retShuffleArr = Shuffle(arrForPuttingExtraDataInRandomTables);



        int[][] retShuffledArr = shuffleArray(fillArray(dt, totalPlayersPerTeam, totalTeams), totalTeams, totalPlayersPerTeam);

        if ((totalPlayersPerTeam * totalTeams) <= dt.Rows.Count)
        {
            for (int i = 0; i < totalTeams; i++)
            {
                dtnew.Clear();
                teamAverage = 0;
                int extraPlayer = 0;

                int it = 0;
                for (int j = 0; j < totalPlayersPerTeam; j++)
                {
                    int rowId = retShuffledArr[it][i];

                    double  k = Convert.ToDouble(dt.Rows[rowId]["average"]);
                    DataRow row;
                    row = dtnew.NewRow();
                    row["Player Name"]    = dt.Rows[rowId]["playerName"];
                    row["Contact Number"] = dt.Rows[rowId]["playerContactNumber"];
                    row["average"]        = k;
                    dtnew.Rows.Add(row);
                    teamAverage += k;

                    it = it + 1;
                }

                for (int m = 0; m < rowsDeleted.Rows.Count; m++)
                {
                    //  string[] arr;
                    if (i == arrForPuttingExtraDataInRandomTables[m])
                    {
                        DataRow test = dtnew.NewRow();
                        test["Player Name"]    = rowsDeleted.Rows[m]["Player Name"];
                        test["Contact Number"] = rowsDeleted.Rows[m]["Contact Number"];
                        test["average"]        = Convert.ToDouble(rowsDeleted.Rows[m]["Average"]);
                        dtnew.Rows.Add(test);
                        //dtnew.ImportRow((DataRow)rowsDeleted[m]);
                        //dtnew.AcceptChanges();
                        teamAverage += Convert.ToDouble(rowsDeleted.Rows[m]["Average"]);
                        extraPlayer  = 1;
                    }
                }
                dtnew.AcceptChanges();

                // Lable for Grid Team name
                Label lblTeam = new Label();
                lblTeam.ID   = "lblTeam " + (i);
                lblTeam.Text = "<b>Team Name:</b> Team " + (i + 1);
                Page.Controls.Add(lblTeam);

                // Label for Average
                Label lblTeamAverage = new Label();
                lblTeamAverage.ID = "lblTeamAverage" + i;
                decimal rounded = decimal.Round((decimal)(teamAverage / (totalPlayersPerTeam + extraPlayer)), 1);
                lblTeamAverage.Text = "<b>Team Average:</b> " + rounded.ToString();

                Page.Controls.Add(lblTeamAverage);
                LiteralControl breakLine = new LiteralControl();
                breakLine.Text = "<br /><br />";
                LiteralControl breakLineSingle = new LiteralControl();
                breakLineSingle.Text = "<br />";
                LiteralControl space = new LiteralControl();
                space.Text = "&nbsp;&nbsp;&nbsp;";

                //Adding the controls to div
                gvTeam.Controls.Add(breakLine);
                gvTeam.Controls.Add(lblTeam);
                gvTeam.Controls.Add(breakLineSingle);
                gvTeam.Controls.Add(lblTeamAverage);

                GridView gvTeamDivision = new GridView();
                gvTeamDivision.ID         = "gvTeam" + i;
                gvTeamDivision.DataSource = dtnew;
                gvTeamDivision.DataBind();
                Page.Controls.Add(gvTeamDivision);
                gvTeam.Controls.Add(gvTeamDivision);
            }
        }
        else
        {
            lblError.Text = "Total Players in al league are less then the expected players.";
        }
    }
Example #55
0
    protected void GridViewResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            Control hlink = e.Row.Cells[0].Controls[0];
            // Create the sorting image based on the sort direction.
            string sort = "<img alt='{1}' src='{0}'/>";

            sort = string.Format(sort, "~/App_Themes/carz/images/bg.png", "Order");

//--------*** This sets up the column headings on the results page--------

            // Add the image to the appropriate header cell.
            e.Row.Cells[0].Controls[0].Controls.Add(new LiteralControl("Rank<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[1].Controls[0].Controls.Add(new LiteralControl("Year<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[2].Controls[0].Controls.Add(new LiteralControl("Make<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[3].Controls[0].Controls.Add(new LiteralControl("Model<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[4].Controls[0].Controls.Add(new LiteralControl("Horsepower<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[5].Controls[0].Controls.Add(new LiteralControl("MSRP<span style='margin-left: 5px;' >" + sort + "</span>"));
            e.Row.Cells[6].Controls[0].Controls.Add(new LiteralControl("0-60 Time<span style='margin-left: 5px;' >" + sort + "</span>"));
        }

        if (e.Row.RowType == DataControlRowType.Pager)
        {
            //DropDownList GridViewMainddl = new DropDownList();
            //adds variants of pager size
            //GridViewMainddl.Items.Add("5");
            //GridViewMainddl.Items.Add("10");
            //GridViewMainddl.Items.Add("20");
            //GridViewMainddl.Items.Add("50");
            //GridViewMainddl.Items.Add("100");
            //GridViewMainddl.Items.Add("200");
            //GridViewMainddl.Items.Add("500");
            //GridViewMainddl.Items.Add("All");
            //GridViewMainddl.AutoPostBack = true;
            //selects item due to the GridView current page size
            //ListItem li = GridViewMainddl.Items.FindByText(GridViewResult.PageSize.ToString());
            //if (li != null)
            // GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
            //GridViewMainddl.SelectedIndexChanged += new EventHandler(GridViewMainddl_SelectedIndexChanged);
            //adds dropdownlist in the additional cell to the pager table

            Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
            pagerTable.Style["float"]   = "right";
            pagerTable.Style["display"] = "inline";
            //TableCell cell = new TableCell();
            pagerTable.Style["margin-right"] = "15px";
            //cell.Controls.Add(new LiteralControl("Page Size:"));
            // cell.Controls.Add(GridViewMainddl);
            // pagerTable.Rows[0].Cells.Add(cell);
            //add current Page of total page count
            dtb = (DataTable)GridViewResult.DataSource;
            int sumcount = dtb != null ? dtb.Rows.Count : 0;
            //TableCell cellPageNumber = new TableCell();
            //cellPageNumber.Style["padding-left"] = "15px";
            //cellPageNumber.Controls.Add(new LiteralControl("Displaying results " + (GridViewResult.PageIndex * 20 + 1) + "-" + (GridViewResult.PageIndex * 20 + 20) + "(of " + sumcount + ")"));
            //pagerTable.Rows[0].Cells.Add(cellPageNumber);

            LiteralControl lt = new LiteralControl("<span style='float:left;font-weight: bold;width: auto;margin-left: 10px;'>Displaying results " + (GridViewResult.PageIndex * 20 + 1) + "-" + ((GridViewResult.PageIndex * 20 + 20) > sumcount ? sumcount.ToString() : (GridViewResult.PageIndex * 20 + 20).ToString()) + " (of " + sumcount.ToString() + ")</span>");

            e.Row.Cells[0].Controls.Add(lt);
        }
    }
Example #56
0
        /// <summary>
        ///     Render each day in the event (i.e. Cells)
        /// </summary>
        protected void EventCalendar_DayRender(object sender, DayRenderEventArgs e)
        {
            var objEvent    = default(EventInfo);
            var cellcontrol = new LiteralControl();

            _objEventInfoHelper = new EventInfoHelper(ModuleId, TabId, PortalId, Settings);

            // Get Events/Sub-Calendar Events
            var dayEvents    = new ArrayList();
            var allDayEvents = default(ArrayList);

            allDayEvents = _objEventInfoHelper.GetDateEvents(_selectedEvents, e.Day.Date);
            allDayEvents.Sort(new EventInfoHelper.EventDateSort());

            foreach (EventInfo tempLoopVar_objEvent in allDayEvents)
            {
                objEvent = tempLoopVar_objEvent;
                //if day not in current (selected) Event month OR full enrollments should be hidden, ignore
                if ((Settings.ShowEventsAlways || e.Day.Date.Month == SelectedDate.Month) &&
                    !HideFullEvent(objEvent))
                {
                    dayEvents.Add(objEvent);
                }
            }

            // If No Cell Event Display...
            if (Settings.Monthcellnoevents)
            {
                if (Settings.ShowEventsAlways == false && e.Day.IsOtherMonth)
                {
                    e.Cell.Text = "";
                    return;
                }

                if (dayEvents.Count > 0)
                {
                    e.Day.IsSelectable = true;

                    if (e.Day.Date == SelectedDate)
                    {
                        e.Cell.CssClass = "EventSelectedDay";
                    }
                    else
                    {
                        if (e.Day.IsWeekend)
                        {
                            e.Cell.CssClass = "EventWeekendDayEvents";
                        }
                        else
                        {
                            e.Cell.CssClass = "EventDayEvents";
                        }
                    }

                    if (Settings.Eventtooltipmonth)
                    {
                        var themeCss = GetThemeSettings().CssClass;

                        var tmpToolTipTitle = Settings.Templates.txtTooltipTemplateTitleNT;
                        if (tmpToolTipTitle.IndexOf("{0}") + 1 > 0)
                        {
                            tmpToolTipTitle = tmpToolTipTitle.Replace("{0}", "{0:d}");
                        }
                        var tooltipTitle =
                            Convert.ToString(HttpUtility.HtmlDecode(string.Format(tmpToolTipTitle, e.Day.Date))
                                             .Replace(Environment.NewLine, ""));
                        var cellToolTip = ""; //Holds control generated tooltip

                        foreach (EventInfo tempLoopVar_objEvent in dayEvents)
                        {
                            objEvent = tempLoopVar_objEvent;
                            //Add horizontal row to seperate the eventdescriptions
                            if (!string.IsNullOrEmpty(cellToolTip))
                            {
                                cellToolTip = cellToolTip + "<hr/>";
                            }

                            cellToolTip +=
                                CreateEventName(
                                    objEvent,
                                    Convert.ToString(Settings.Templates.txtTooltipTemplateBodyNT
                                                     .Replace(Constants.vbLf, "").Replace(Constants.vbCr, "")));
                        }
                        e.Cell.Attributes.Add(
                            "title",
                            "<table class=\"" + themeCss + " Eventtooltiptable\"><tr><td class=\"" + themeCss +
                            " Eventtooltipheader\">" + tooltipTitle + "</td></tr><tr><td class=\"" + themeCss +
                            " Eventtooltipbody\">" + cellToolTip + "</td></tr></table>");
                        e.Cell.ID = "ctlEvents_Mod_" + ModuleId + "_EventDate_" + e.Day.Date.ToString("yyyyMMMdd");
                    }

                    var dailyLink = new HyperLink();
                    dailyLink.Text = string.Format(Settings.Templates.txtMonthDayEventCount, dayEvents.Count);
                    var socialGroupId = GetUrlGroupId();
                    var socialUserId  = GetUrlUserId();
                    if (dayEvents.Count > 1)
                    {
                        if (Settings.Eventdaynewpage)
                        {
                            if (socialGroupId > 0)
                            {
                                dailyLink.NavigateUrl =
                                    _objEventInfoHelper.AddSkinContainerControls(
                                        Globals.NavigateURL(TabId, "Day", "Mid=" + ModuleId,
                                                            "selecteddate=" +
                                                            Strings.Format(e.Day.Date, "yyyyMMdd"),
                                                            "groupid=" + socialGroupId), "?");
                            }
                            else if (socialUserId > 0)
                            {
                                dailyLink.NavigateUrl =
                                    _objEventInfoHelper.AddSkinContainerControls(
                                        Globals.NavigateURL(TabId, "Day", "Mid=" + ModuleId,
                                                            "selecteddate=" +
                                                            Strings.Format(e.Day.Date, "yyyyMMdd"),
                                                            "userid=" + socialUserId), "?");
                            }
                            else
                            {
                                dailyLink.NavigateUrl =
                                    _objEventInfoHelper.AddSkinContainerControls(
                                        Globals.NavigateURL(TabId, "Day", "Mid=" + ModuleId,
                                                            "selecteddate=" +
                                                            Strings.Format(e.Day.Date, "yyyyMMdd")), "?");
                            }
                        }
                        else
                        {
                            if (socialGroupId > 0)
                            {
                                dailyLink.NavigateUrl =
                                    Globals.NavigateURL(TabId, "", "ModuleID=" + ModuleId, "mctl=EventDay",
                                                        "selecteddate=" + Strings.Format(e.Day.Date, "yyyyMMdd"),
                                                        "groupid=" + socialGroupId);
                            }
                            else if (socialUserId > 0)
                            {
                                dailyLink.NavigateUrl =
                                    Globals.NavigateURL(TabId, "", "ModuleID=" + ModuleId, "mctl=EventDay",
                                                        "selecteddate=" + Strings.Format(e.Day.Date, "yyyyMMdd"),
                                                        "userid=" + socialUserId);
                            }
                            else
                            {
                                dailyLink.NavigateUrl =
                                    Globals.NavigateURL(TabId, "", "ModuleID=" + ModuleId, "mctl=EventDay",
                                                        "selecteddate=" + Strings.Format(e.Day.Date, "yyyyMMdd"));
                            }
                        }
                    }
                    else
                    {
                        // Get detail page url
                        dailyLink = GetDetailPageUrl((EventInfo)dayEvents[0], dailyLink);
                    }
                    using (var stringWrite = new StringWriter())
                    {
                        using (var eventoutput = new HtmlTextWriter(stringWrite))
                        {
                            dailyLink.RenderControl(eventoutput);
                            cellcontrol.Text = "<div class='EventDayScroll'>" + stringWrite + "</div>";
                            e.Cell.Controls.Add(cellcontrol);
                        }
                    }
                }
                else
                {
                    e.Day.IsSelectable = false;
                }
                return;
            }

            //Make day unselectable
            if (!Settings.Monthdayselect)
            {
                e.Day.IsSelectable = false;
            }

            //loop through records and render if startDate = current day and is not null
            var celldata = ""; // Holds Control Generated HTML

            foreach (EventInfo tempLoopVar_objEvent in dayEvents)
            {
                objEvent = tempLoopVar_objEvent;
                var dailyLink  = new HyperLink();
                var iconString = "";

                // See if an Image is to be displayed for the Event
                if (Settings.Eventimage && Settings.EventImageMonth && objEvent.ImageURL != null &&
                    objEvent.ImageDisplay)
                {
                    dailyLink.Text = ImageInfo(objEvent.ImageURL, objEvent.ImageHeight, objEvent.ImageWidth);
                }

                if (Settings.Timeintitle)
                {
                    dailyLink.Text = dailyLink.Text + objEvent.EventTimeBegin.ToString("t") + " - ";
                }

                var eventtext = CreateEventName(objEvent, Settings.Templates.txtMonthEventText);
                dailyLink.Text = dailyLink.Text + eventtext.Trim();

                if (!IsPrivateNotModerator || UserId == objEvent.OwnerID)
                {
                    dailyLink.ForeColor = GetColor(objEvent.FontColor);
                    iconString          = CreateIconString(objEvent, Settings.IconMonthPrio,
                                                           Settings.IconMonthRec, Settings.IconMonthReminder,
                                                           Settings.IconMonthEnroll);

                    // Get detail page url
                    dailyLink = GetDetailPageUrl(objEvent, dailyLink);
                }
                else
                {
                    dailyLink.Style.Add("cursor", "text");
                    dailyLink.Style.Add("text-decoration", "none");
                    dailyLink.Attributes.Add("onclick", "javascript:return false;");
                }

                // See If Description Tooltip to be added
                if (Settings.Eventtooltipmonth)
                {
                    var isEvtEditor = IsEventEditor(objEvent, false);
                    dailyLink.Attributes.Add(
                        "title",
                        ToolTipCreate(objEvent, Settings.Templates.txtTooltipTemplateTitle,
                                      Settings.Templates.txtTooltipTemplateBody, isEvtEditor));
                }

                // Capture Control Info & save
                using (var stringWrite = new StringWriter())
                {
                    using (var eventoutput = new HtmlTextWriter(stringWrite))
                    {
                        dailyLink.ID = "ctlEvents_Mod_" + ModuleId + "_EventID_" + objEvent.EventID +
                                       "_EventDate_" + e.Day.Date.ToString("yyyyMMMdd");
                        dailyLink.RenderControl(eventoutput);
                        if (objEvent.Color != null && (!IsPrivateNotModerator || UserId == objEvent.OwnerID))
                        {
                            celldata = celldata + "<div style=\"background-color: " + objEvent.Color + ";\">" +
                                       iconString + stringWrite + "</div>";
                        }
                        else
                        {
                            celldata = celldata + "<div>" + iconString + stringWrite + "</div>";
                        }
                    }
                }
            }

            // Add Literal Control Data to Cell w/DIV tag (in order to support scrolling in cell)
            cellcontrol.Text = "<div class='EventDayScroll'>" + celldata + "</div>";
            e.Cell.Controls.Add(cellcontrol);
        }
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            Controls.Clear();

            // main container
            _dialogPanel = new Panel();
            Controls.Add(_dialogPanel);
            _dialogPanel.ID       = "modal_dialog_panel";
            _dialogPanel.CssClass = "modal container modal-content rock-modal rock-modal-frame";

            _hfModalVisible          = new HiddenFieldWithClass();
            _hfModalVisible.CssClass = "js-modal-visible";
            _dialogPanel.Controls.Add(_hfModalVisible);

            // modal-header
            _headerPanel = new Panel();
            _dialogPanel.Controls.Add(_headerPanel);
            _headerPanel.CssClass = "modal-header";

            _closeLink = new HtmlGenericControl("button");
            _headerPanel.Controls.Add(_closeLink);
            _closeLink.ID = "closeLink";
            _closeLink.Attributes.Add("class", "close js-modaldialog-close-link");
            _closeLink.Attributes.Add("aria-hidden", "true");
            _closeLink.Attributes.Add("type", "button");
            _closeLink.Attributes.Add("data-dismiss", "modal");
            _closeLink.InnerHtml = "&times;";

            _titleH3 = new HtmlGenericControl("h3");
            _titleH3.AddCssClass("modal-title");
            _headerPanel.Controls.Add(_titleH3);

            // _title control for public this.Title
            _title      = new LiteralControl();
            _title.Text = string.Empty;
            _titleH3.Controls.Add(_title);

            // _subtitle controls for public this.Subtitle
            _subtitleSmall = new HtmlGenericControl("small");
            _headerPanel.Controls.Add(_subtitleSmall);
            _subtitle      = new LiteralControl();
            _subtitle.Text = string.Empty;
            _subtitleSmall.Controls.Add(_subtitle);

            // modal-body and content
            _bodyPanel          = new Panel();
            _bodyPanel.CssClass = "modal-body";
            _dialogPanel.Controls.Add(_bodyPanel);

            // for this.Content
            _contentPanel = new Panel();
            _bodyPanel.Controls.Add(_contentPanel);
            _contentPanel.ID = "contentPanel";

            // modal-footer
            _footerPanel = new Panel();
            _dialogPanel.Controls.Add(_footerPanel);
            _footerPanel.CssClass = "modal-footer";

            _cancelLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_cancelLink);
            _cancelLink.ID = "cancelLink";
            _cancelLink.Attributes.Add("class", "btn btn-link js-modaldialog-cancel-link");
            _cancelLink.Attributes.Add("data-dismiss", "modal");
            _cancelLink.InnerText = "Cancel";

            _serverSaveLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_serverSaveLink);
            _serverSaveLink.ID = "serverSaveLink";
            _serverSaveLink.Attributes.Add("class", "btn btn-primary");
            _serverSaveLink.ServerClick += SaveLink_ServerClick;

            _saveLink = new HtmlAnchor();
            _footerPanel.Controls.Add(_saveLink);
            _saveLink.ID = "saveLink";
            _saveLink.Attributes.Add("class", "btn btn-primary js-modaldialog-save-link");
        }
Example #58
0
        /// <summary> Add controls directly to the form in the main control area placeholder </summary>
        /// <param name="MainPlaceHolder"> Main place holder to which all main controls are added </param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> The bulk of this page is added here, as controls </remarks>
        public override void Add_Controls(PlaceHolder MainPlaceHolder, Custom_Tracer Tracer)
        {
            Tracer.Add_Trace("NewPassword_MySobekViewer.Add_Controls", "");

            User_Object user = RequestSpecificValues.Current_User;

            // Is this for registration?
            bool registration = (HttpContext.Current.Session["user"] == null);

            if (registration)
            {
                user = new User_Object();
            }

            string current_password = String.Empty;
            string new_password     = String.Empty;
            string new_password2    = String.Empty;

            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                // Loop through and get the dataa
                string[] getKeys = HttpContext.Current.Request.Form.AllKeys;
                foreach (string thisKey in getKeys)
                {
                    switch (thisKey)
                    {
                    case "current_password_enter":
                        current_password = HttpContext.Current.Request.Form[thisKey];
                        break;

                    case "new_password_enter":
                        new_password = HttpContext.Current.Request.Form[thisKey];
                        break;

                    case "new_password_confirm":
                        new_password2 = HttpContext.Current.Request.Form[thisKey];
                        break;
                    }
                }

                if ((new_password.Trim().Length == 0) || (new_password2.Trim().Length == 0))
                {
                    validationErrors.Add("Select and confirm a new password");
                }
                if (new_password != new_password2)
                {
                    validationErrors.Add("New passwords do not match");
                }
                else if ((new_password.Length < 8) && (new_password.Length > 0))
                {
                    validationErrors.Add("Password must be at least eight digits");
                }
                if (validationErrors.Count == 0)
                {
                    if (new_password == current_password)
                    {
                        validationErrors.Add("The new password cannot match the old password");
                    }
                }

                if (validationErrors.Count == 0)
                {
                    bool success = SobekCM_Database.Change_Password(user.UserName, current_password, new_password, false, Tracer);
                    if (success)
                    {
                        user.Is_Temporary_Password = false;
                        // Forward back to their original URL (unless the original URL was this logon page)
                        string raw_url = (HttpContext.Current.Request.RawUrl);
                        if (raw_url.ToUpper().IndexOf("M=HML") > 0)
                        {
                            RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                            UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                            return;
                        }
                        else
                        {
                            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl, false);
                            HttpContext.Current.ApplicationInstance.CompleteRequest();
                            RequestSpecificValues.Current_Mode.Request_Completed = true;
                            return;
                        }
                    }
                    else
                    {
                        validationErrors.Add("Unable to change password.  Verify current password.");
                    }
                }
            }

            StringBuilder literalBuilder = new StringBuilder(1000);

            literalBuilder.AppendLine("<script src=\"" + Static_Resources_Gateway.Sobekcm_Metadata_Js + "\" type=\"text/javascript\"></script>");
            literalBuilder.AppendLine("<div class=\"SobekHomeText\" >");
            literalBuilder.AppendLine("<br />");
            literalBuilder.AppendLine("<blockquote>");
            literalBuilder.AppendLine(user.Is_Temporary_Password
                                          ? "You are required to change your password to continue."
                                          : "Please enter your existing password and your new password.");
            if (validationErrors.Count > 0)
            {
                literalBuilder.AppendLine("<br /><br /><strong><span style=\"color: Red\">The following errors were detected:");
                literalBuilder.AppendLine("<blockquote>");
                foreach (string thisError in validationErrors)
                {
                    literalBuilder.AppendLine(thisError + "<br />");
                }
                literalBuilder.AppendLine("</blockquote>");
                literalBuilder.AppendLine("</span></strong>");
            }
            literalBuilder.AppendLine("</blockquote>");
            literalBuilder.AppendLine("<table width=\"700px\"><tr><td width=\"180px\">&nbsp;</td>");
            literalBuilder.AppendLine("<td width=\"200px\"><label for=\"current_password_enter\">Existing Password:</label></td>");
            literalBuilder.AppendLine("<td width=\"180px\">");
            LiteralControl literal1 = new LiteralControl(literalBuilder.ToString());

            literalBuilder.Remove(0, literalBuilder.Length);
            MainPlaceHolder.Controls.Add(literal1);

            existingPasswordBox = new TextBox
            {
                CssClass = "preferences_small_input",
                ID       = "current_password_enter",
                TextMode = TextBoxMode.Password
            };
            existingPasswordBox.Attributes.Add("onfocus", "textbox_enter('current_password_enter', 'preferences_small_input_focused')");
            existingPasswordBox.Attributes.Add("onblur", "textbox_leave('current_password_enter', 'preferences_small_input')");
            MainPlaceHolder.Controls.Add(existingPasswordBox);

            LiteralControl literal2 = new LiteralControl("</td><td width=\"140px\">&nbsp;</td></tr>" + Environment.NewLine + "<tr><td>&nbsp;</td><td><label for=\"new_password_enter\">New Password:</label></td><td>");

            MainPlaceHolder.Controls.Add(literal2);

            passwordBox = new TextBox
            {
                CssClass = "preferences_small_input",
                ID       = "new_password_enter",
                TextMode = TextBoxMode.Password
            };
            passwordBox.Attributes.Add("onfocus", "textbox_enter('new_password_enter', 'preferences_small_input_focused')");
            passwordBox.Attributes.Add("onblur", "textbox_leave('new_password_enter', 'preferences_small_input')");
            MainPlaceHolder.Controls.Add(passwordBox);

            LiteralControl literal3 = new LiteralControl("</td><td>&nbsp;</td></tr>" + Environment.NewLine + "<tr><td>&nbsp;</td><td><label for=\"new_password_confirm\">Confirm New Password:</label></td><td>");

            MainPlaceHolder.Controls.Add(literal3);

            confirmPasswordBox = new TextBox
            {
                CssClass = "preferences_small_input",
                ID       = "new_password_confirm",
                TextMode = TextBoxMode.Password
            };
            confirmPasswordBox.Attributes.Add("onfocus", "textbox_enter('new_password_confirm', 'preferences_small_input_focused')");
            confirmPasswordBox.Attributes.Add("onblur", "textbox_leave('new_password_confirm', 'preferences_small_input')");
            MainPlaceHolder.Controls.Add(confirmPasswordBox);

            literalBuilder.AppendLine("   </td><td>&nbsp;</td></tr>");
            literalBuilder.AppendLine("  <tr align=\"right\" valign=\"bottom\" height=\"50px\" ><td colspan=\"3\">");
            RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Log_Out;
            literalBuilder.AppendLine("    <a href=\"" + UrlWriterHelper.Redirect_URL(RequestSpecificValues.Current_Mode) + "\"><img src=\"" + RequestSpecificValues.Current_Mode.Base_URL + "design/skins/" + RequestSpecificValues.Current_Mode.Base_Skin_Or_Skin + "/buttons/cancel_button.gif\" border=\"0\" alt=\"CANCEL\" /></a> &nbsp; ");
            RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.New_Password;

            LiteralControl literal4 = new LiteralControl(literalBuilder.ToString());

            MainPlaceHolder.Controls.Add(literal4);

            // Add the submit button
            ImageButton submitButton = new ImageButton
            {
                ImageUrl      = RequestSpecificValues.Current_Mode.Base_URL + "design/skins/" + RequestSpecificValues.Current_Mode.Base_Skin_Or_Skin + "/buttons/save_button.gif",
                AlternateText = "SAVE"
            };

            submitButton.Click += submitButton_Click;
            MainPlaceHolder.Controls.Add(submitButton);

            LiteralControl literal5 = new LiteralControl("</td></tr></table></blockquote></div>\n\n<!-- Focus on current password text box -->\n<script type=\"text/javascript\">focus_element('current_password_enter');</script>\n\n");

            MainPlaceHolder.Controls.Add(literal5);
        }
        /// <summary>
        /// Creates the table controls.
        /// </summary>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="dataViewId">The data view identifier.</param>
        private void BindHtmlGrid(int?batchId, int?dataViewId)
        {
            _financialTransactionDetailList = null;
            RockContext rockContext = new RockContext();

            nbSaveSuccess.Visible = false;
            btnSave.Visible       = false;

            List <DataControlField> tableColumns = new List <DataControlField>();

            tableColumns.Add(new RockLiteralField {
                ID = "lPerson", HeaderText = "Person"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lAmount", HeaderText = "Amount"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lAccount", HeaderText = "Account"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lTransactionType", HeaderText = "Transaction Type"
            });

            string entityColumnHeading = this.GetAttributeValue("EntityColumnHeading");

            if (string.IsNullOrEmpty(entityColumnHeading))
            {
                if (_transactionEntityType != null)
                {
                    entityColumnHeading = _entityTypeQualifiedName;
                }
            }

            tableColumns.Add(new RockLiteralField {
                ID = "lEntityColumn", HeaderText = entityColumnHeading
            });

            var additionalColumns = this.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>();

            if (additionalColumns != null)
            {
                foreach (var columnConfig in additionalColumns.ColumnsConfig)
                {
                    int insertPosition;
                    if (columnConfig.PositionOffsetType == CustomGridColumnsConfig.ColumnConfig.OffsetType.LastColumn)
                    {
                        insertPosition = tableColumns.Count - columnConfig.PositionOffset;
                    }
                    else
                    {
                        insertPosition = columnConfig.PositionOffset;
                    }

                    var column = columnConfig.GetGridColumn();
                    tableColumns.Insert(insertPosition, column);
                    insertPosition++;
                }
            }

            StringBuilder headers = new StringBuilder();

            foreach (var tableColumn in tableColumns)
            {
                if (tableColumn.HeaderStyle.CssClass.IsNotNullOrWhiteSpace())
                {
                    headers.AppendFormat("<th class='{0}'>{1}</th>", tableColumn.HeaderStyle.CssClass, tableColumn.HeaderText);
                }
                else
                {
                    headers.AppendFormat("<th>{0}</th>", tableColumn.HeaderText);
                }
            }

            lHeaderHtml.Text = headers.ToString();

            int?transactionId = this.PageParameter("TransactionId").AsIntegerOrNull();

            if (batchId.HasValue || dataViewId.HasValue || transactionId.HasValue)
            {
                var financialTransactionDetailQuery = new FinancialTransactionDetailService(rockContext).Queryable()
                                                      .Include(a => a.Transaction)
                                                      .Include(a => a.Transaction.AuthorizedPersonAlias.Person);
                if (batchId.HasValue)
                {
                    financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => a.Transaction.BatchId == batchId.Value);
                }

                if (dataViewId.HasValue && dataViewId > 0)
                {
                    var           dataView = new DataViewService(rockContext).Get(dataViewId.Value);
                    List <string> errorMessages;
                    var           transactionDetailIdsQry = dataView.GetQuery(null, rockContext, null, out errorMessages).Select(a => a.Id);
                    financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => transactionDetailIdsQry.Contains(a.Id));
                }

                if (transactionId.HasValue)
                {
                    financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => transactionId == a.TransactionId);
                }

                int maxResults = this.GetAttributeValue("MaxNumberofResults").AsIntegerOrNull() ?? 1000;
                _financialTransactionDetailList = financialTransactionDetailQuery.OrderByDescending(a => a.Transaction.TransactionDateTime).Take(maxResults).ToList();
                phTableRows.Controls.Clear();
                btnSave.Visible = _financialTransactionDetailList.Any();
                string appRoot   = this.ResolveRockUrl("~/");
                string themeRoot = this.ResolveRockUrl("~~/");

                foreach (var financialTransactionDetail in _financialTransactionDetailList)
                {
                    var tr = new HtmlGenericContainer("tr");
                    foreach (var tableColumn in tableColumns)
                    {
                        var literalControl = new LiteralControl();
                        if (tableColumn is RockLiteralField)
                        {
                            tr.Controls.Add(literalControl);
                            var literalTableColumn = tableColumn as RockLiteralField;
                            if (literalTableColumn.ID == "lPerson")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Transaction.AuthorizedPersonAlias);
                            }
                            else if (literalTableColumn.ID == "lAmount")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Amount.FormatAsCurrency());
                            }
                            else if (literalTableColumn.ID == "lAccount")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Account.ToString());
                            }
                            else if (literalTableColumn.ID == "lTransactionType")
                            {
                                literalControl.ID   = "lTransactionType_" + financialTransactionDetail.Id.ToString();
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Transaction.TransactionTypeValue);
                            }
                            else if (literalTableColumn.ID == "lEntityColumn")
                            {
                                var tdEntityControls = new HtmlGenericContainer("td")
                                {
                                    ID = "pnlEntityControls_" + financialTransactionDetail.Id.ToString()
                                };
                                tr.Controls.Add(tdEntityControls);

                                if (_transactionEntityType != null)
                                {
                                    if (_transactionEntityType.Id == EntityTypeCache.GetId <GroupMember>())
                                    {
                                        var ddlGroup = new RockDropDownList {
                                            ID = "ddlGroup_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        ddlGroup.Label                 = "Group";
                                        ddlGroup.AutoPostBack          = true;
                                        ddlGroup.SelectedIndexChanged += ddlGroup_SelectedIndexChanged;
                                        tdEntityControls.Controls.Add(ddlGroup);
                                        var ddlGroupMember = new RockDropDownList {
                                            ID = "ddlGroupMember_" + financialTransactionDetail.Id.ToString(), Visible = false, EnhanceForLongLists = true
                                        };
                                        ddlGroupMember.Label = "Group Member";
                                        tdEntityControls.Controls.Add(ddlGroupMember);
                                    }
                                    else if (_transactionEntityType.Id == EntityTypeCache.GetId <Group>())
                                    {
                                        var ddlGroup = new RockDropDownList {
                                            ID = "ddlGroup_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        ddlGroup.AutoPostBack = false;
                                        tdEntityControls.Controls.Add(ddlGroup);
                                    }
                                    else if (_transactionEntityType.Id == EntityTypeCache.GetId <DefinedValue>())
                                    {
                                        var ddlDefinedValue = new DefinedValuePicker {
                                            ID = "ddlDefinedValue_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        tdEntityControls.Controls.Add(ddlDefinedValue);
                                    }
                                    else if (_transactionEntityType.SingleValueFieldType != null)
                                    {
                                        var entityPicker = _transactionEntityType.SingleValueFieldType.Field.EditControl(new Dictionary <string, Rock.Field.ConfigurationValue>(), "entityPicker_" + financialTransactionDetail.Id.ToString());
                                        tdEntityControls.Controls.Add(entityPicker);
                                    }
                                }
                            }
                        }
                        else if (tableColumn is LavaField)
                        {
                            tr.Controls.Add(literalControl);
                            var lavaField = tableColumn as LavaField;

                            Dictionary <string, object> mergeValues = new Dictionary <string, object>();
                            mergeValues.Add("Row", financialTransactionDetail);

                            string lavaOutput = lavaField.LavaTemplate.ResolveMergeFields(mergeValues);

                            // Resolve any dynamic url references
                            lavaOutput = lavaOutput.Replace("~~/", themeRoot).Replace("~/", appRoot);

                            if (lavaField.ItemStyle.CssClass.IsNotNullOrWhiteSpace())
                            {
                                literalControl.Text = string.Format("<td class='{0}'>{1}</td>", lavaField.ItemStyle.CssClass, lavaOutput);
                            }
                            else
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", lavaOutput);
                            }
                        }
                    }

                    phTableRows.Controls.Add(tr);

                    pnlTransactions.Visible = true;
                }
            }
            else
            {
                pnlTransactions.Visible = false;
            }
        }
Example #60
0
        /// <summary>
        /// Instantiat in the control to container
        /// </summary>
        /// <param name="container"></param>
        public void InstantiateIn(Control container)
        {
            try
            {
                Table tbl = new System.Web.UI.WebControls.Table();
                container.Controls.Add(tbl);
                tbl.Width = Unit.Percentage(100);
                TableRow row = new TableRow();
                tbl.Rows.Add(row);
                TableCell cell = new TableCell();
                cell.Font.Size = new FontUnit(FontSize.Smaller);
                row.Cells.Add(cell);
                cell.HorizontalAlign = HorizontalAlign.Center;


                int currentPage = _gview.PageIndex + 1;
                int from        = 0;
                int to          = 0;
                if (currentPage > 1)
                {
                    ImageButton prevBtn = new ImageButton();
                    prevBtn.ImageUrl        = "~/_layouts/images/prev.gif";
                    prevBtn.CommandName     = "Page";
                    prevBtn.CommandArgument = "Prev";
                    cell.Controls.Add(prevBtn);
                }
                if (currentPage > 1)
                {
                    if (currentPage == _gview.PageCount)
                    {
                        from = (currentPage - 1) * _gview.PageSize + 1;
                        to   = _gview.Rows.Count + (currentPage - 1) * _gview.PageSize;
                    }
                    else
                    {
                        from = (currentPage - 1) * _gview.PageSize + 1;
                        to   = from + _gview.PageSize - 1;
                    }
                }
                else
                {
                    from = 1;
                    to   = _gview.PageSize;
                }
                LiteralControl lControl = new LiteralControl(String.Format(_format, from, to));
                cell.Controls.Add(lControl);

                if (currentPage < _gview.PageCount)
                {
                    ImageButton nextBtn = new ImageButton();
                    nextBtn.ImageUrl        = "~/_layouts/images/next.gif";
                    nextBtn.CommandName     = "Page";
                    nextBtn.CommandArgument = "Next";
                    cell.Controls.Add(nextBtn);
                }
            }
            catch (Exception ex)
            {
                //_log.Log(LogSeverity.Error, ex, "gview分页异常", string.Empty);
            }
        }