C# how to print asp:buttons - c#

I'm currently working on a small program that gets data from mongoDB and matches it with other data. My program is currently printing out the data, but it needs to add a <asp:button />with an unique ID to it so I can save the data for each product.
Here is my code:
public void showCoolers_Click(object sender, EventArgs e)
{
var items = "";
var connectionString = "mongodb://localhost:27017/";
var mongoClient = new MongoClient(connectionString);
MongoServer server = mongoClient.GetServer();
MongoDatabase database = server.GetDatabase("mydb");
MongoCollection<cpuCoolers> collection = database.GetCollection<cpuCoolers>("cpucoolers");
foreach (cpuCoolers parts in collection.FindAll())
{
String _id = parts._id.ToString();
items = items + "<tr><td>" + parts.Aanbieder + "</td><td> " + parts.Productnaam + "</td><td>" + parts.Socket + "</td><td> " + parts.Geluidsterkte + "</td><td> " + parts.Prijs +"</td><td><asp:Button ID='x' runat='server' Text='Motherboard' CssClass='btn btn-block btn-primary'/></td></tr>";
}
lblProducts.Text = "<table><thead><tr><th>Provider</th><th>Productname</th><th>Socket</th><th>Sound production</th><th>Price</th><th>Add to MyPc!</th></thead>" + items + "</table>";
}
I print my data via changing the content oflblProduct.Text in my aspx file. If I add a asp:button to this it doesn't show up, however a regular Html button does, why is that and is there a way to print out a asp:button's?

You can't render an asp.net button the way you are trying, you would need to use a regular html button as you found out.
The asp:button is something that asp.net interprets while it is building your page; by the time you _Click function is executed, its too late in the page lifecycle to render asp.net controls - so HTML buttons are your only option at that point in the page execution.
Here is an overview of the asp.net page life cycle that might help you understand it better:
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx

Related

How to overcome failures while doing UI Automation for Knockout Web sites

I'm working on knockout based site using selenium web driver + c# to automate. My test methods fail because of elements not found / not able to click as the site is slow / or the binding/ rendering of html is slow after the ajax calls are finished.
Below is sample code I used to know the ajax calls have finished and I can proceed to search elements.
public static void waitForAjax(IWebDriver driver, String action)
{
try
{
TimeSpan tp = TimeSpan.FromSeconds(1000);
driver.Manage().Timeouts().SetScriptTimeout(tp);
((IJavaScriptExecutor)driver).ExecuteAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '/" + action + "', true);" +
"xhr.onreadystatechange = function() {" +
" if (xhr.readyState == 4 && xhr.status == 200) {" +
" callback(xhr.responseText);" +
" }" +
"};" +
"xhr.send();");
}
catch { }
}
I am calling the above method before going to find the elements.
Test Method
try
{
IWebDriver _Driver;
IWebElement ele;
FirefoxDriverService _Service = FirefoxDriverService.CreateDefaultService(#"D:\CodePlex_C#\SeleniumTestWithHtml\SeleniumTestWithHtml\Drivers");
_Driver = new FirefoxDriver(_Service);
_Driver.Navigate().GoToUrl("HomepageURl");
System.Threading.Thread.Sleep(2000);
waitForAjax(_Driver,"Call1");
waitForAjax(_Driver,"Call2");
System.Threading.Thread.Sleep(2000);
ele = _Driver.FindElement(By.LinkText("DASHBOARD"));
ele.Click();
//System.Threading.Thread.Sleep(2000);
waitForAjax(_Driver,"Call1");
waitForAjax(_Driver,"Call2");
waitForAjax(_Driver,"Call3");
waitForAjax(_Driver,"Call4");
System.Threading.Thread.Sleep(2500);
ele = _Driver.FindElement(By.Id("QuickSearchCnt"));
ele.Click();
}
But my Code Fails. I suspect the code to find the calls have finished to execute is not working properly.
I need help in knowing is my approach right? And need help in fixing the issue.

Setting up google analytics for desktop application

I have a desktop application written in C#. I want to collect user statistics in google analytics. For instance I want to know when user pressed on specific button and what was value in text control when he did it.
I am sending events data as explained here. I tried to do this either with WebClient.UploadValues like in this question and also with WebClient.UploadString
I have set up new google analytics account. When I was asked what I want to track (website or mobile app) I have selected mobile app (there was no choice for desktop apps).
The problem is that I don't see any data in my Google Analytics account. I know it may take some time while new data will appear there but I have waited for 3 days. And also I don't see anything in real time view when I test my application ( I also have some websites with analytics connected and when I browse them I see new pageviews in realtime section).
What am I doing wrong?
Here is the code that I use:
private static string _googleURL = "http://www.google-analytics.com/collect";
private static string _gaid = "UA-12345678-9";
public static void TestMethod()
{
try
{
string data = "";
data += "v=" + HttpUtility.UrlEncode("1");
data += "&" + "tid" + "=" + HttpUtility.UrlEncode(_gaid);
data += "&" + "cid" + "=" + HttpUtility.UrlEncode(Guid.NewGuid().ToString());
data += "&" + "t" + "=" + HttpUtility.UrlEncode("event");
data += "&" + "ec" + "=" + HttpUtility.UrlEncode("testevent");
data += "&" + "ea" + "=" + HttpUtility.UrlEncode("testaction");
data += "&" + "el" + "=" + HttpUtility.UrlEncode("testlabel");
using (var client = new WebClient())
{
client.UploadString(_googleURL, "POST", data);
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}

asp.net Button type link should open on new window

using c# .net4.0
I am aware the asp.net button with in the gridview of type link does a post to the same page when clicked, i need make several manipualtion on server side before actually redirecting user to an external site hence i can't use Hyperlinkfield. What i need now is the external site htm page should open up in sperate window. I tried the following which works but source site's fonts get bigger???
heres what i tried
Response.Write("<script>");
Response.Write("window.open('http://www.google.co.uk','_blank')");
Response.Write("</script>");
Response.End();
may be i need a refresh source site??
Thanks
# Curt Here is the code for Hyperlink i tired
on page load added new button on gridview
HyperLinkField LinksBoundField = new HyperLinkField();
string[] dataNavigateUrlFields = {"link"};
LinksBoundField.DataTextField = "link";
LinksBoundField.DataNavigateUrlFields = dataNavigateUrlFields;
LinksBoundField.DataNavigateUrlFormatString = "http://" + Helper.IP + "/" + Helper.SiteName + "/" + Helper.ThirdPartyAccess + "?dispage={0}&token=" + Session["Token"];
LinksBoundField.HeaderText = "Link";
LinksBoundField.Target = "_blank";
GridViewLinkedService.Columns.Add(LinksBoundField);
GridViewLinkedService.RowDataBound += new GridViewRowEventHandler(grdView_RowDataBound);
to append external values (refe and appid) to navigate url
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
string strvalue = "";
string strvalue1 = "";
string strRef = "";
string strAppId = "";
foreach (GridViewRow row in GridViewLinkedService.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//reference and appid
strAppId = row.Cells[0].Text;
strRef = row.Cells[1].Text;
HyperLink grdviewLink = (HyperLink)row.Cells[5].Controls[0];
strvalue = grdviewLink.NavigateUrl;
strvalue1 = Regex.Replace(strvalue, "(.*dispage\\=).*/(services.*)", "$1$2");
grdviewLink.NavigateUrl = "~/My Service/FillerPage.aspx?nurl=" + strvalue1 + "&AppID=" + strAppId.ToString() + "&Ref=" + strRef.ToString();
}
}
}
public partial class FillerPage : System.Web.UI.Page
{
private string refno = null;
private string appid = null;
private string nurl = null;
private string strvalue1 = "";
private string newtoken = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.GetValues("AppID") != null)
{
appid = Request.QueryString.GetValues("AppID")[0].ToString();
}
if (Request.QueryString.GetValues("Ref") != null)
{
refno = Request.QueryString.GetValues("Ref")[0].ToString();
}
if (Request.QueryString.GetValues("nurl") != null)
{
nurl = Request.QueryString.GetValues("nurl")[0].ToString();
}
while receiving the long url it gets messed up(same query multiple times and all jumbled up)?????
is there a better way to pass parameters ???
you need to register script not response.write
so the code for you is :
ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language=JavaScript>window.open('http://www.google.co.uk','_blank')</script>");
Read more : ClientScriptManager.RegisterStartupScript.
In a situation where I need to run server side code, before then opening a new page, I sometimes create a Generic Handler File and link to this with a HyperLink, passing variables as Query Strings. Therefore something like:
/MyGenericFile.ashx?id=123
In this file, I would have some scripting that needs to be carried out, followed by a Response.Redirect().
As long as the HyperLink is set to target="_blank", the user won't even know they've been to a generic file, which is then redirected. It will appear as they've opened a new link.
Therefore the process would be:
User clicks link to .ashx file
Link opens in new window
Necessary scripting is ran
Response.Redirect() is ran
User is taken to web page (www.google.com in your example)
I believe this same process is used by advert management systems to help track clicks.
You can register a script to run on page load with ClientScriptManager.RegisterStartupScript.

Serving Word document on button click on C# asp.net page

When code is placed onClick event it does not show open save dialog box and no exception is thrown but works fine onLoad event,opens a open save dialog box to save a word file..
string strDocBody;
strDocBody = "<html " + "xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word'" + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head>" + "<title>Version and Release Management</title>";
strDocBody = strDocBody + "<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:Zoom>100</w:Zoom>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->";
strDocBody = strDocBody + "<style> #page" + "{size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt;" + " margin:0.75in 0.50in 0.75in 0.50in ; " + " mso-header-margin:.5in; " + " mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + " {page:Section1;}" + "p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "-->" + "</style>" + "</head>";
strDocBody = strDocBody + "<body lang=EN-US style='tab-interval:.5in'>" + "<div class=Section1>" + "<h1>This is my Heading</h1>" + "<h2>This is my Sub Heading</h2>" + "<p style='color:navy;'> This is blue text</p>" + "<p style='font-weight:bold; color:green;'><u> This is green bold underlined text </u></p>" + "<p style='color:red'><I>" + DateTime.Now + "</I></p>" + "<!--[if supportFields]>" + "<div style='mso-element:header' id=h1><p class=MsoHeader><span style='mso-tab-count:4'></span><span style='mso-field-code: PAGE '></span> </p></div>" + "<div style='mso-element:footer' id=f1> " + "<p class=MsoFooter style='border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'><o:p> </o:p></p> " + "Page <span style='mso-field-code: PAGE '><span style='mso-no-proof:yes'>1</span></span> of <span style='mso-field-code: NUMPAGES '></span>" + " <span style='mso-tab-count: 12'> <span style='mso-field-code: DATE '></span> " + " </p></div><![endif]-->" + "</div> </body> </html> ";
//Force this content to be downloaded as a Word document
Response.AddHeader("Content-Type", "application/msword");
Response.AddHeader("Content-disposition", "attachment; filename=TEST.doc");
Response.Charset = "";
Response.Write(strDocBody);
I suppose you are trying to feed the data in strDocBody as a Word file to the user. In order to do that, this data has to be the only thing that web server passes to the browser. That's why it works fine when you put it in your OnLoad event handler. It's not the case when you put it in button click handler.
If you want this behavior on button click, this button has to redirect user to another URL which will send the document data and nothing else.
Create a page specifically for serving document, let it be Document.aspx.
Now, I don't know if you need to perform any additional logic on button click. If not, you can just use LinkButton:
<asp:LinkButton runat="server" ID="docLink" Text="Document"
PostBackUrl="Document.aspx" />
Otherwise, just add redirect call in your onClick handler:
protected void btnButton1_Click(object sender, EventArgs e)
{
// ....
Response.Redirect("Document.aspx");
}
based on my experience, this indeed doesn't work for onClick since the headers has already been sent.
This could be because headers were already posted to the client browser. Try clearing with Response.Clear(), make sure you're not within an Ajax call. Another trick is to open a new page, using a client-side anchor with argument compiled dynamically.
EDIT: of course if you clear your Response, page will be blank after asking the user to download the file. Always keep in mind the stateless synchronous behavior of client-server http communication.

Ajax site performance problem (IE)

I am facing a performance issue related to running ajax in IE (i'm using Ie8), the problem is my website working very slow in ie but it works fine in chrome, and I mean by using SLOW => slow motion . I am using divs and tables and rendering html to div using javascript, besides that I'm using ajax to call 5 different pages (handlers)
function ReceiveServerData(rValue)
{
var x = GetHash();
var feeds = JSON.parse(rValue);
var sb = new StringBuilderEx();
var length = feeds.length;
for(var i=0; i<length-1; i++)
sb.append(News(feeds[i].Id, feeds[i].Title, feeds[i].Des, feeds[i].Icon, i));
if(i == 0)
{
$('#News').html("");
$('#head').html("<i><b><center>لا يوجد اي مقالات حاليا</center></b></i>");
return;
}
$('#News').html(sb.toString());
$('#Pages').html("");
if(feeds[i].count == 1)
{
$('#head').html("");
return;
}
for(var a = 1; a <= feeds[i].count; a++)
{
if('#'+a == x || a == x)
$('#Pages').append("<button id=b" + a + " class='bt2' type='button'><span class='yt-uix-button-content'>"+ a +" </span></button> ");
else
$('#Pages').append("<button id =" + a + " Onclick=javascript:ChangeHash(" + a + ") class='bt' type='button'>"+ a +"</button> ");
$('#head').html("<i><b><center>The page has been loaded.</center></b></i>");
}
scroll(0,0);
}
function News(id, title, des, icon, i)
{
var type = "";
if(i == 0)
type = "&p=big";
return "<table style=width:100%;>" +
"<tr><td rowspan=2 style=width:10%;><img width=70 hieght=70 src="+ icon +">" +
"</td><td align=right style=width:90%;background:url(./Images/BabrBackground.gif)>" +
" <font size=3> "+ title +"</font></td></tr><tr>"+
"<td valign=top align=right> <i><font color=#5C5858>"+ des +"</font></i></td></tr></table>";
}
IE's javascript engine tends to run slower than Chrome, and from the looks of it, your loop is probably making it work harder than its suppose to.
Not knowing anything about your project or what you are trying to accomplish, why do you not just render your html on the server and post that back to the client, instead of having all that javascript build the html for you?
I don't have direct answer to your question. But you can use dynaTrace to pinpoint exact line of code which is causing the issue. For more information - http://ejohn.org/blog/deep-tracing-of-internet-explorer/
I would look at optimising the html generation - have you checked out jTemplates?
I currently use jTemplates to create content from ajax returned JSON data which is inserted into divs on the page - I have no issues with performance despite generating a considerable amount of html content - largely I suspect because jTemplates is highly optimised.

Categories

Resources