Change text in HTML that I'm grabbing from a text file - c#

What I'm doing is grabbing the HTML code for my header from a text file.
But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...
So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.
How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?
Would like to do this with C# not JS please.
Edit: I have a work around for now, but I am still interested in better answers.
headerText = headerText.Replace("::Username::", Session["Username"] as string);
Here is my code for grabbing the HTML and pasting it in.
string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));
headerText = headerText.Replace("::Username::", Session["Username"] as string);
divHeader.InnerHtml = headerText;
divFooter.InnerHtml = footerText;
To be more clear, is there anyway to access something like
<asp:Panel ID="panelAccount" runat="server">
which is stored in another HTML file.

I have done similar work in C# earlier, I use HTMLAgilityPack for doing this kind of works. Later I start using Anglesharp since it has a very good CSS selector based support.
Try anglesharp and you can modify the HTML tag like you do in jQuery.

As much as I liked Adrians response, I found out a better way to do what I needed to do, I could do with a MasterPage. I definitely be using Adrians answer for a load of other things though so it still holds valid.
Then in the C# file associated with the master page you create a property like this.
public Panel PanelAccount
{
get { return panelAccount; }
set { panelAccount = value; }
}
Then from the regular WebForm, you can call "PanelAccount" to access that property.
Here is a tutorial for how to do that.
Thanks for everyones downvotes with no inputs, you guys are stars!

Related

Call aspx, html pages from another aspx page

I have one aspx page where I want to display contents of another aspx or html page based on the sessions. Code behind logic will fetch the file from particular location based on the session. I do not want to use frames, iframes because I have to make sure of cross browser compatibility. Is there any other way to achieve this?
User control may be a solution for this. I wanted to know more alternate approach.
Below is my code:
I don't have anything in aspx except the references to the external js file.
Code behind:
private void Page_Load(object sender, System.EventArgs e)
{
_getMainMenu();
}
protected string _getMainMenu()
{
string HomePageMenu = string.Empty;
string homeExist = Server.MapPath("../homepages/" + Session["ACCOUNT"].ToString() + "/HomePage.htm");
if (File.Exists(homeExist ))
{
HomePageMenu = "../homepages/" + Session["ACCOUNT"].ToString() + "/HomePage.htm";
}
else
{
HomePageMenu = "../homepages/NewMenu.html";
}
return HomePageMenu ;
}
Thanks.
Sounds like maybe something like jQuery load is something that may be helpful. This will asynchronously retrieve content and place it into a control of your choice, and not necessarily an iframe of course. This is called from the client, but you can have your server side logic/session state determine the content returned.
You should change the way you manage your content in generally.
In your case, your aspx-page is your content. And if you want to show contant b in contant a, you will have to show an aspx-page inside another aspx-page.
Change the point of view: your aspx-page should only be your content-holder. Extract your content to an ascx-usercontrol or store it in a database.
Then you are able to fetch the content whereever you need them.
Showing an aspx-page inside another is a very bad solution.
But if it's not possible to change the way your content is stored: I would prefere an iframe.

How can I find and scrape by Class using WatiN?

I am using WatiN and trying to scrape an image URL from a weblink, based on the fields class. Viewing the sites code the images info displays as this:
//images code
<div class="doc-banner-icon">
<img src="https://website.com/image.jpg">
</div>
//text code
<div id="doc-original-text">
Once upon a time, in a land far far away...
</div>
What I want to do is use a WatiN call to find that img link. I thought I could use something like the Find.ByClass() call to find specifically that area of the code, but I can't seem to figure out how to get the line of text contained within that class. When I use the Find.ById() on a different field and sent to string it pulls the text content of that area. Below is what I am trying.
using (myIE)
{
//loads the website
myIE.GoTo(txtbxWeblink.Text);
string infoText = myIE.Div(Find.ByClass("doc-banner-icon")).ToString();
//This will successfully return the text fields text.
string imageText = myIE.Div(Find.ById("doc-original-text")).ToString();
}
EDIT - It appears that I may need to use a different call on myIE, there is also myIE.Image, myIE.Link etc, I don't know much about this all still so not sure if Div is the right call here.
Try this...
string infoText = myIE.Div(Find.ByClass("doc-banner-icon")).Images.First().Src;
string imageText = myIE.Div(Find.ById("doc-original-text")).Text;

how to get text attribute from a asp:panel

Probably a simple question, but I've been browsing now for 30 mins and STILL cant find a solution!
i have a panel and it has an attribute text="something". but the panel class does not seem to have a getAttribute method... Which personally, I think is STUPID!
Code follows:
foreach (Control c in clientGrid.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.Panel"))
{
/*Something*/ textInsidePanel = ((Panel)c)./*Somthing*/
}
}
Now i've tried AttributeCollection text = ((Panel)c).Attributes;
and
string text = ((Panel)c).Attributes.toString();
and other useless things...
This should be really simple! when i inspect element on chrome, I can see the panel, (well the div) and i can see the text attribute right there. and i can see its value! but i want my c# code to have the value to!!
Please Help!
Alex
if I get you question right - you can use next code
asp part
<asp:Panel runat="server" ID="pnl" Text="hello world"></asp:Panel>
c# part -
string s = pnl.Attributes["Text"];
Have you tried using an accessor?:
string val = YourPanel.Attributes["Text"];
// ^ that's your attribute name
That should get the attribute's value BUT I'm pretty sure what you are doing isn't possible as attribute values are not persisted between postbacks (at least not when set via a client script). To do that you should use hidden inputs or some other form element.
The Panel control itself doesn't have a text property. But if you access the inner text as a LiteralControl it will work:
var panelContent = ((Panel)c).Controls[0] as LiteralControl;
var text = panelContent.Text;

asp.net dynamically add usercontrols and position them

My issue is that I have a designer that will create a custom aspx page bu without any .net controls. I need a way of adding the controls dynamically. So far the only types of controls will be textboxes and a button, but there are 30 variations of what the textboxes can be (name, phone #, email, etc). Also the textboxes may or may not need to be required. Once the textboxes are added the form will be submitted to a db.
My first thought was to have the designer place something like [name] and then replace that with a user control that has a name textbox and a required field validator. In order to determine if the validator should be enabled I was thinking that the place holder could look like this, [name;val] or [name;noval]. I could either do replace the place holders in code dynamically or set up a tool that the user pastes their html into a textbox and clicks a button which then spits out the necessary code to create the aspx page.
I'm sure there must be a better way to do this but its a fairly unique problem so I haven't been able to find any alternatives. Does anyone have any ideas?
Thanks,
Kirk
IF your designer gives you html pages, just create a new website. copy and pages all the HTML pages with the Image folders and everything to your project. then for every HTML page create an aspx page, (with the same name) copy and pages the html's tags which are between to the aspx page's and for the body copy and paste HTML page's tags which are between into the of the aspx page.
Now you have your aspx page, exactly the same as html page.
Sounds like an attempt to over-engineer a solution to what should be a non-issue.
As #Alessandro mentioned in a comment above, why can't the designer provide you with pages that have the control markup? As it stands right now, the designer isn't providing you with "a custom aspx" so much as "a custom html page." If the designer is promising ASPX but delivering only HTML, that's a misinterpretation somewhere in the business requirements.
However, even if the designer is rightfully providing only HTML, there shouldn't be a problem with that. At worst, you can set each element you need on the server to runat="server" to access them on the server-side. Or, probably better, would be to simply replace them with the ASPX control markup for the relevant controls.
Write a simple parser that will recognize the [...] tags and replace them with corresponding controls. Its pretty easy to do and i've often done this... the tag i use is usually $$(..); though, but that doesn't matter as long as your parser knows your tags.
Such a parser will consist of a simple state-machine that can be in two states; text-mode or tag-mode. Loop through the whole page-text, char for char. As long as you're in text-mode you keep appending each char into a temporary buffer. As soon as you get into tag-mode you create a LiteralControl with the content of the temporary buffer and add it to the bottom of your Control-tree, and emtpy the buffer.
Now, you still keep adding each char into the buffer, but when you hit text-mode again, you analyze the content of the buffer and create the correct control - could be a simple switch case statement. Add the control to the bottom of your control tree and keep looping through the rest of the chars unto you read the end and keep switching back and forth between text-mode and tag-mode adding LiteralControls and concrete controls.
Simple example of such a parser... written in notepad in 4 minutes, but you should get the idea.
foreach (var c in text)
{
buffer.Append(c);
if (c== '[' && mode == Text)
{
mode = Tag;
Controls.Add(new LiteralControl(buffer));
buffer.Clear();
}
if (c == ']' && mode == Tag)
{
mode = Text;
switch (buffer)
{
case "[name]": Controls.Add(new NameControl());
... the rest of possible tags
}
buffer.Clear();
}

How to copy all data from a HTML doc and save it to a string using C#

I need to create a data index of HTML pages provided to a service by essentially grabbing all text on them and putting them in a string to go into a storage system.
If this were GUI based, I would simply Ctrl+A on the HTML page, copy it, then go to Notepad and Ctrl+V. Simples. If I can do it via good old point n' click, then surely there must be a way to do it programmatically, but I'm struggling to find anything useful.
The HTML docs in question are being loaded for rendering currently using the System.Windows.Controls.WebBrowser class, so I wonder if its somehow possible to grab the data from there?
I'm going to keep hunting, but any pointers would be very appreciated.
Note: We don't want the HTML source code, and would also really rather not have to parse all the source code to get the text unless we absolutely have to.
If I understand your problem correctly, you will have to do a bit of work to get the data.
WebBrowser browser=new WebBrowser(); // This is what you have
HtmlDocument doc = browser.Document; // This gives you the browser contents
String content =
(((mshtml.HTMLDocumentClass)(doc.DomDocument)).documentElement).innerText;
That last line is the browser's view of the rendered content.
This looks like it might be quite helpful.

Categories

Resources