How to change the web browser control properties? - c#

I am creating a web browser using c# winform. I am using webbrowser control for this. I am using this code. This is running good so far
// Declared Variables
private string[] SiteMemoryArray = new string[100];
private int count = 0;
// Page Load
private void Form1_Load(object sender, EventArgs e)
{
webBrowser.Navigate("http://www.google.com/"); // Goes To A Preset Site At Run Time
SiteMemoryArray[count] = urlTextBox.Text; // Saves URL To Memory
}
// Code For The ToolStrip
// URL TextBox
private void urlTextBox_Click(object sender, EventArgs e)
{
urlTextBox.SelectAll(); // Selects All The Text In The urlTexBox
}
// GO Button
private void goButton_Click(object sender, EventArgs e)
{
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
}
// Back Button
private void backButton_Click(object sender, EventArgs e)
{
if (count > 0) // Checks To Make Sure The Count Variable Is More Then 0
{
count = count - 1; // Subtracts 1 From Count Variable
urlTextBox.Text = SiteMemoryArray[count]; // Replace The Text In The urlTextBox With The Last URl
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
forwardButton.Enabled = true; // Enables The forwarButton
}
}
// Forward Button
private void forwardButton_Click(object sender, EventArgs e)
{
if (count < 100) // Checks To Make Sure The Count Variable Is Less Then 100
{
count = count + 1; // Adds 1 To Count Variable
urlTextBox.Text = SiteMemoryArray[count]; // Replace The Text In The urlTextBox With The Next URl
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
backButton.Enabled = true; // Enables The backButton
count = count + 1; // Adds 1 To Count Variable
if (SiteMemoryArray[count] == null) // Checks To See If The Next Variable In The SiteMemoryArray Is Null
{
forwardButton.Enabled = false; // Disables The forwarButton
}
count = count - 1; // Subtracts 1 From Count Variable
}
}
But after create this small application my friend who is php developer ask me to check browser name . For this he create a php script n give me url then i run this url on my this browser its show me the browser name Internet Explorer
Now I want my browser name whatever I give name Please tell me is it possible with this control. Is there any property by using i can change it ?

The web browser control is IE. If you want to create your own browser, it is a lot more work than this. You need to write code that is able to do following and more:
Understand and handle HTTP protocol.
Understand, parse and render HTML. Most browsers ignore certain HTML errors and still render pages accurately. Not sure if you want that kind of features.
Your application should be able apply CSS settings on the pages.
Your application should be able to apply JS, flash, video, audio and other items that may well be embedded on a page.
You would also need to provide features that are available standard browsers.
The question is: What is the purpose of this application? Are you trying to write your own browser?

Related

Label changes during page load

I'm trying to capture the value of my password to Label.
4 digit letter and 1 lower case letter
This is my method to add both digit and num
public void SaveTransactionID()
{
string password = lblStart.Text + lblStop.Text;
lblPassword.Text = password;
}
The generators:
private void GenRandomNumber()
{
Random generator = new Random();
String r = generator.Next(0, 10000).ToString("D4");
lblStart.Text = r;
}
//Generate Random Letter
static class RandomLetter
{
static Random _random = new Random();
public static char GetLetter()
{
// This method returns a random lowercase letter.
// ... Between 'a' and 'z' inclusize.
int num = _random.Next(0, 26); // Zero to 25
char let = (char)('a' + num);
return let;
}
}
My page load
protected void Page_Load(object sender, EventArgs e)
{
char lowerCase;
lowerCase = Convert.ToChar(RandomLetter.GetLetter());
lblStop.Text = lowerCase.ToString();
GenRandomNumber();
}
I know that my password will change every page load. That is why I tried to save it on my Label so I could capture the password in case the page loads again. But the things is my SaveTransactonId() also change during page load. How could I store the value of my password even with page load?
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
char lowerCase;
lowerCase = Convert.ToChar(RandomLetter.GetLetter());
lblStop.Text = lowerCase.ToString();
GenRandomNumber();
}
}
This will solve your problem.
EDIT:
Here's a short explanation of what conditions occur when IsPostBack = true or false. For a single computer for developing and debugging code, the "Client" is your browser and the "Server" is your computer. (In the linked article, the question is not "What is IsPostBack?" The correct question is "What is PostBack?" There is a better, more intricate diagram; I cannot find it, but this'll do.)
PostBack is the name given to the process of submitting an ASP.NET page to the server for processing. PostBack is done if (for example) certain credentials of the page are to be checked against some sources (such as verification of username and password for a database). This is something the client is not able to accomplish on its own and thus these details have to be 'posted back' to the server via user interaction.
A postback is round trip from the client (Browser) to the server and then back to the client. This enables your page to go through the asp engine on the server and any dynamic content to be updated.
For a more detailed answer to the PostBack question, see here.
Here is a description of the ASP.NET (web-) page life cycle overview, some of which involve PostBack.
write your code inside if(!Page.IsPostBack){// put your logic here.}
and You can save your value in Session["sessionKey"] = value;
and you can retrieve it by checking session is not null
if(Session["sessionKey"] !=null);
lblPassword.Text = Session["sessionKey"];
You can store the value in a Session variable; you can also control what runs in Page_Load on initial page load vs. subsequent page reloads (per session) via Page.IsPostBack property.

Universal Hub App sample does not return right number of items when trimmed

I’m trying to edit the Windows Store Universal Hub App sample in VS 2013. There is a SampleDataSource.cs that takes in data from a SampleData.json, and presents it when asked for. The method I’m interested in is SampleDataSource.GetGroupAsync. Assuming I have 10 items in a group (in the json file), I’d like to display only 6 on the landing page (HubPage), and all 10 on the SectionPage (the page you get when you click on the Hub Section header).
So I modified the code to do this.
HubPage.xaml.cs
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var sampleDataGroup = await SampleDataSource.GetGroupAsync("Group-4");
// Trim items to top 6 only
if (sampleDataGroup.Items.Count > 6)
{
for (int removeIndex = sampleDataGroup.Items.Count - 1; sampleDataGroup.Items.Count > 6; removeIndex--)
{
sampleDataGroup.Items.RemoveAt(removeIndex);
}
}
this.DefaultViewModel["Section3Items"] = sampleDataGroup;
}
However, when I navigate to SectionPage, I only see 6 items, instead of all 10. Why does this happen? I am calling SampleDataSource.GetGroupAsync again, the original collection or the json file was not modified by my trimming down to 6 items, so why am I receiving only 6 from SampleDataSource? I have confirmed that this is indeed “Group-4”
SectionPage.xaml.cs
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var group = await SampleDataSource.GetGroupAsync((string)e.NavigationParameter);
this.DefaultViewModel["Group"] = group;
this.DefaultViewModel["Items"] = group.Items;
}
Here is a direct link to the samples. I'm using the C# version:
http://code.msdn.microsoft.com/wpapps/Universal-Windows-app-cb3248c3

How to get "previous" and "next" functionality?

I have a program that people can leave comments on a video. The comments come is as in queue status. The admin can go into the admin section and mark the comments as either approved or removed. They want to be able to automatically go to the next item marked in queue when they press either the previous or next buttons, as well as if they approve or remove a comment. I do not know jQuery or JavaScript well enough to know if it is possible to do it using those, or how to do it through the code behind (this is in C# .NET). Any help would be appreciated:
Status and value:
In queue = 0
Approved = 1
Removed = 2
Here is the code-behind. The status changes work, the only thing I cannot do is have it go to the next record marked in queue. The first two events are blank because I do not know how to fill them, but simply put, all the need to do too is go to the next record marked in queue.
If you need any more code, please let me know...
protected void previous_clicked(object sender, EventArgs e)
{
}
protected void next_clicked(object sender, EventArgs e)
{
}
protected void approve_clicked(object sender, EventArgs e)
{
currentMessage = new videomessage(Request["id"].ToString());
status.SelectedValue = "1";
currentMessage.status = "1";
currentMessage.Save();
}
protected void remove_clicked(object sender, EventArgs e)
{
currentMessage = new videomessage(Request["id"].ToString());
status.SelectedValue = "2";
currentMessage.status = "2";
currentMessage.Save();
}
Sounds more like an architectural challenge to me.
I recommend using a Queue. This is a collection type following a first-in, first-out (FIFO) approach. You put objects into the queue and get them back out in the same order. An object that was received out of this queue is automatically is removed from the queue, so you can be sure that you do not handle the same element twice.
Your described workflow then would work as these simple steps:
Whenever a message arrives, you put the object into your queue.
When the admin clicks on the next button, you request the first object out of the queue.
Your admin does his administrative tasks and approves the message.
Clicking on Next start with above item 1 again.
[EDIT]
Oops, I realized that my Queue approach would not allow for navigating back to previous items.
In this case I suggest using a simple List collection. This list can be accessed via the 0-based position in the list. This makes it easy to implement a forward/ backward navigation.
For my sample code, please bear in mind that there is a lot that I cannot know about your environment, so my code make a lot assumptions here.
You need to somwhere store a collection that contains your messages to be approved:
private IList<videomessage> _messagesToApprove = new List<videomessage>();
You will also need some variable that keeps track of the current position in your collection:
// Store the index of the current message
// Initial value depends on your environment. :-)
private int _currentIndex = 0;
To begin with, you will need a starting point where new messages are added to that collection, like subscribing to some event or so. Whenever a message arrives, add it to the collection by calling a method like:
// I made this method up because I do not know where your messages really come from.
// => ADJUST TO YOUR NEEDS.
private void onNewMessageArriving(string messageId)
{
videomessage arrivingMessage = new videomessage(messageId);
_messagesToApprove.Add(arrivingMessage);
}
The you can easily implement the navigation by incrementing/ decrementing the position index:
private void previous_Click(object sender, EventArgs e)
{
// Check that we do not go back further than the beginning of the list
if ((_currentIndex - 1) >= 0)
{
_currentIndex--;
this.currentMessage = this._messagesToApprove[_currentIndex];
}
else
{
// Do nothing if the position would be invalid
return;
}
}
private void next_Click(object sender, EventArgs e)
{
// Check if we have new messages to approve in our list.
if ((_currentIndex + 1) < _messagesToApprove.Count)
{
_currentIndex++;
currentMessage = _messagesToApprove[_currentIndex];
}
else
{
// Do nothing if the position would be invalid
return;
}
}
private void approve_Click(object sender, EventArgs e)
{
// Sorry, I don't know where exactly this comes from, needs to be adjusted to your environment
status.SelectedValue = "1";
this.currentMessage.status = "1";
this.currentMessage.Save();
// If you want to remove items that have been checked by the admin, delete it from the approval list.
// Otherwise remove this line :-)
this._messagesToApprove.RemoveAt(_currentIndex);
}
private void remove_Click(object sender, EventArgs e)
{
// Sorry, I don't know where exactly this comes from, needs to be adjusted to your environment
status.SelectedValue = "2";
this.currentMessage.status = "2";
this.currentMessage.Save();
// If you want to remove items that have been checked by the admin, delete it from the approval list.
// Otherwise remove this line :-)
this._messagesToApprove.RemoveAt(_currentIndex);
}
Save the id of current comment in session or viewstate get it back on next or previous button click and display the accordingly:
Session["id"] = 2;
int id = (int) Session["id"];

how to store post variable so i can call the variable anytime in ASP.NET

i am developing a web for my final project,and im new to ASP.NET and this forum.
thx to all who help me.
the question is...
example i have 2 pages.
page1.aspx.cs (this page for receive variable from mikrokontroler via network module)
example mikrokontroler send a variable "status" = 1
protected void Page_Load(object sender, EventArgs e)
{
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
}
page2.aspx
(in page 2 there is button and textbox)
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
}
You have a lot of options to store the variable value:
session state: Session["status"]= A
application state: Application["status"] = A
asp net cache: using Cache.Add()
database: here i would store also the timestamps, to trace the historic status of the controller.
local XML file.
It all depends on the scope of the stored data: session data is local to the current user/session and will expire after a predefined timeout(def: 20mins), application will be global to all your users/sessions and will expire when you will restart the application (by iis, iisreset, recompiling...), cache is global and will expire based on the parameters of invocation, the database and xml are global and will maintain state.
In your case i would use database or application store, because the microcontroller and user live in different sessions and the app cache is not a suitable messaging mechanism while Xml introduces some problems on his own (eg: filesystem permissions, data replication...).
write:
Application["status"] = A;
read:
int A = 0;
bool result = int.TryParse(Application["status"],out A);
BTW: to parse the integer you can skip the try/catch part doing this:
int A = 0;
bool result = int.TryParse(POST["status"],out A);
in this case if unable to parse A will be equal to 0;
You can use Session
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
Session["Avalie"] = A;
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
and then on page 2
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
if(!String.IsNullOrEmpty( Session["Avalie"] ))
int Aval = int.Parse(Session["Avalie"]);
}
Use crosspagepostback to pass values from one page to another (introduced in asp.net 2.0)
One option is to assign the value to a static variable in the first page.
Refer to Static Classes and Static Class Members (C# Programming Guide)
Another option is to use state variables as session state variables or application variables.
Refer to ASP.NET Session State Overview and ASP.NET Application State Overview

C# validate repeat last PostBack when hit Refresh (F5)

i have a webform that generates a file, but when i click the button that produces the postback to generate the file Once it finish if i press Refresh (F5) the page resubmit the postback and regenerates the file, there's any way to validate it and show a message to the user or simply DO NOTHING!
thanks :)
The simpler way will be to use Post Rediret Get pattern.
http://en.wikipedia.org/wiki/Post/Redirect/Get
Make sure to check out External Links on that Wikipedia article.
the browser should warn them if they hit refresh on a page that has been postbacked. how i handle it though is in the session track what i have done so i don't repeat certain actions. a simple flag should suffice.
Check for the existence of the file in question in your postback logic and only create the file if the file doesn't already exist:
if (false == System.IO.File.Exists(filename))
{
// create the file
}
else
{
// do whatever you do when the file already exists
}
i wrote a solution for this problem and here it is if anyone needs it.
protected void Page_Load(object sender, System.EventArgs e)
{
/*******/
//Validate if the user Refresh the webform.
//U will need::
//A global private variable called ""private bool isRefresh = false;""
//a global publica variable called ""public int refreshValue = 0;""
//a html control before </form> tag: ""<input type="hidden" name="ValidateRefresh" value="<%= refreshValue %>">""
int postRefreshValue = 0;
refreshValue = SII.Utils.convert.ToInt(Request.Form["ValidateRefresh"]); //u can use a int.parse()
if (refreshValue == 0)
Session["ValidateRefresh"] = 0;
postRefreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
if (refreshValue < postRefreshValue)
isRefresh = true;
Session["ValidateRefresh"] = postRefreshValue + 1;
refreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
/********/
if (!IsPostBack)
{
//your code
}
}
you just have to evaluate:
if (!isRefresh)
PostFile();
else
{
//Error msg you are refreshing
}

Categories