I have the following C# code in my code behind for a regular Web Application:
protected void Page_Load(object sender, EventArgs e)
{
if (!validTime())
{
btnEdit.Enabled = false;
btnSubmit.Enabled = false; btnSubmit2.Enabled = false;
lblSuccess.Text = "It is not currently the time to edit picks for this week.";
lblSuccess.ForeColor = System.Drawing.Color.Red;
if (picksMade())
{
displayCurrentPicks();
}
}
else
{
if (picksMade())
{
btnEdit.Enabled = true;
btnSubmit.Enabled = false;
btnSubmit2.Enabled = false;
displayCurrentPicks();
lblSuccess.Text = "Viewing your current picks";
lblSuccess.ForeColor = System.Drawing.Color.Green;
if (Session["Success"] != null && Session["Success"].ToString() != String.Empty)
{
lblSuccess.Text = Session["Success"].ToString();
lblSuccess.ForeColor = System.Drawing.Color.Green;
Session.Remove("Success");
}
}
else
{
btnEdit.Enabled = false;
btnSubmit.Enabled = true; btnSubmit2.Enabled = true;
displayCreatePicks();
lblSuccess.Text = "Create your picks for this week";
lblSuccess.ForeColor = System.Drawing.Color.Green;
}
}
}
The problem is, this code works great when I test it using ASP.NET Development Server. When I publish it to my live server it has some different behavior.
I have a web method that inserts data into my database with this signature:
[WebMethod]
public static void savePicks(List<string> Points, List<string> Teams, List<string> TieBreaker)
Again, on the test server it runs and works great. The problem is, when the method returns it should refresh the page, and it does, but on the live server my code in the page_load event is not run? or is run differently? It never calls the displayCurrentPicks() method? Or if it does, it does not run correctly? except it runs perfectly on the test server.
I have no way to check this stepping through the code because when I do it works great, on the test server. The live server is hosted on Godaddy.
And I have tried everything. I have tried doing page refreshes after the correct methods and in my javascript to force the page_load event to be run again. Nothing works. I have been at this for a few days now. And I am sure all my code is publishing. I have done all the usual 'stupid checks'. The data is making it to the database, the picksMade() function returns true when there is data there. The data is there by the time the page refreshes.
Why does the live server not run the code I publish to it? Why does it run something different? Or Behave differently? I understand it is a different server, but shouldn't it run the code the same?
What exactly does the function validTime() do? If you are checking for specific time constraints it may be that your development server is set to your local time zone and that is why it is working but on your live server the timezone may be different. Just a guess though.
Related
I'm having a hard time with what appears to be a connection issue. I have scoured the web and sounds like this is not the way to go but if someone has any thoughts or ideas that would be great.
I have a hunch it's because these 4 pages are using the same .cs code file and all logic is happening OnLoad() so it is kicking the other off? These reports are for display only, no input required from user.
Please let me know if more information is needed, thank you!
Issue:
Page loads fine on its own but if multiple tabs are ran and one is still processing, it halts this and then displays missing data and formatting. Can sometimes be mimicked by pressing refresh (F5) twice quickly.
Environment:
IIS running on server
DB2Database (IBM)
Web Report:
4 asp.net pages that link to same Default.CS code file (ex. /dash/steel.aspx, /dash/steelnums.aspx)
On page load > read CSV files using StreamReader > run SQL query > format/display information into data grid view
Connection Example:
iDB2Connection BlueDB2Connection = new iDB2Connection(strConnectionString);
iDB2DataAdapter BlueDB2PartsDataAdapter = new iDB2DataAdapter();
iDB2Command SqlCmd = BlueDB2Connection.CreateCommand();
SqlCmd.CommandTimeout = 1000000000;
// select proper query based on page being loaded
if (curPage.Contains("amewood"))
{
SqlCmd.CommandText = sqlMainDataWood();
}
else if (curPage.Contains("amesteel"))
{
SqlCmd.CommandText = sqlMainDataSteel();
}
BlueDB2PartsDataAdapter.SelectCommand = SqlCmd;
try
{
BlueDB2PartsDataAdapter.Fill(dsParts);
}
catch (SqlException sqlEx)
{
DisplayError.Text = "Error:" + sqlEx.Message;
}
Reading CSV function:
using (StreamReader reader = new StreamReader(basePath + filePath + "daysStart.csv"))
{
var headerLine = reader.ReadLine();
var line = reader.ReadToEnd();
var values = line.Split(',');
DateTime dt;
DateTime today = DateTime.ParseExact(DateTime.Now.ToString("MMddyyyy"), "MMddyyyy", CultureInfo.InvariantCulture);
int i = 0;
if (values.Length != 0)
{
foreach (string item in values)
{
if (item != "")
{
dt = DateTime.ParseExact(item, "MMddyyyy", CultureInfo.InvariantCulture);
dateData.startDate = dt;
}
else
{
dateData.startDate = today;
}
i++;
}
}
else
{
dateData.startDate = today;
}
}
Troubleshooting:
Attempted multiple threading
Tried delays prior to code
Tested that the CSV's were not causing the issue
Not closing the DB connection (disposing it) would be the culprit. After running every command or query, you have to dispose of the connection (or at the end of the event handler function). As #Dai suggested if you're not limited to using DB2 and Web Forms you should use newer technologies such as ASP.net MVC and EntityFramework or other ORMs.
Update :
after reading your link:
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread-safe.
it is maybe from not sharing the same instance of DB2DataAdapter object. Share it with static modifier between pages and see if it helps.
Sorry for the delay, I don't get much time to work on this. The issue turned out to be related to a static variable that was being overwritten... face palm. I'm sure if I posted all of the code you would have noticed it immediately. Thank you for your time and effort.
I'm using AutoUpdater.NET for updating my applications. It's a great library. My program collects data for inventory system-data, sent it to database and than close the application.
this.Close();
The problem is, that the program also close, if an update is available. I want, that the application stay open, until the user update or cancel. I know that I have to check, if update is available or update-form is open, but I don't know how. Could someone please help? (Sorry, I'm beginner)
AutoUpdater.Start(updatePath);
AutoUpdater.ShowSkipButton = false;
AutoUpdater.ShowRemindLaterButton = false;
AutoUpdater.Mandatory = true;
//AutoUpdater.UpdateMode = Mode.Forced;
AutoUpdater.RunUpdateAsAdmin = false;
var currentDirectory = new DirectoryInfo(Environment.CurrentDirectory);
if (currentDirectory.Parent != null)
{
AutoUpdater.InstallationPath = currentDirectory.FullName;
}
The solution (in my case) was to replace Environment.CurrentDirectory with Application.StartupPath
I'm trying to submit a from using c# to a website and am trying to get the response from the server as a message box after the data is sent. the website does redirect to another page to show an output.
What happens so far is the data is not submitted until I click OK on the message box that is displaying the data before it is send not after.
WebBrowser browser = new WebBrowser();
string target = "http://www.awebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e) // fail was here.
{
WebBrowser b = (WebBrowser)sender;
string text = richTextBox1.Text.ToString();
if (text == null)
{
MessageBox.Show("the messgae was empty");
}
b.Document.GetElementById("idmsg").InnerText = richTextBox1.Text.ToUpper().ToString();
b.Document.GetElementById("idpassw").InnerText = ".....";
b.Document.GetElementById("idpagers").InnerText = id;
b.Document.GetElementById("Send").InvokeMember("click");
// allow server response time
System.Threading.Thread.Sleep(5000);
string output = b.Document.Body.OuterText.ToString();
MessageBox.Show(output);
}
I'v also tried adding another Document complete with the //allow server response time code but again did'nt send till OK was pressed.
what am I doing wrong?
You do it totally wrong. Never rely on the.Sleep(...). C# provides rich enough async environment, namely Task DoAsync(...) which is to be used somewhat like await DoAsync(). This guarantees that no code going below the DoAsync() would ever be executed unless the async operation either completed successfully, either failed with error. As such, by the time you'll get to the last MessageBox.Show(...), all the data would be there, displayed properly as expected.
I have a site where I'm trying to deliver files via WriteFile and they work fine in Chrome and Firefox, but in IE I have to hit "Retry" once or twice to actually make the file download.
Here is the code:
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var r = context.Response;
r.Clear();
r.ClearContent();
r.ContentType = "application/octet-stream";
string path = "";
try
{
if (HttpContext.Current.Request.QueryString["n"] != null)
{
var file = HttpContext.Current.Request.QueryString["n"].ToString();
var type = HttpContext.Current.Request.QueryString["t"].ToString();
r.AddHeader("Content-Disposition", "attachment; filename=" + file.Substring(file.IndexOf('_')+1));
string folder = "";
switch (type.ToLower())
{
case "public":
folder = ConfigurationManager.AppSettings["BCD_PublicDocsLoc"];
break;
case "private":
folder = ConfigurationManager.AppSettings["BCD_PrivateDocsLoc"];
break;
case "internal":
folder = ConfigurationManager.AppSettings["BCD_InternalDocsLoc"];
break;
}
path = folder + "/" + file;
r.WriteFile(path);
r.Flush();
r.Close();
r.End();
}
}
catch (Exception ex)
{
r.Flush();
r.Close();
r.End();
context.Response.Redirect("Error.aspx?err=301");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
If anyone has any advice as to why this is happening, it would be greatly appreciated. Thanks!
Try substituting the HttpResponse's Close() and End() calls with HttpApplication.CompleteRequest().
Read here why, there are examples too.
Also, this solution was suggested here(in the first answer) for a situation similar to yours.
As was hinted that a small explanation in this post would be convenient, due to the possibility of the links going dead in the future, here it goes:
In short: IE seems to have problems with the HttpResponse.Close and HttpResponse.End methods. Aside of that, anyways, Microsoft recommends in most cases the use of HttpApplication.CompleteRequest over the former two, because:
-HttpResponse.Close() terminates the connection abruptly, dropping buffered data and is not intended for normal HTTP use in which a response to the client is desired
-HttpResponse.End() exists for compatibility reasons with the older ASP technology. It calls the EndRequest event directly and no further code after the End call is executed which is inconvenient in many cases
-HttpApplication.CompleteRequest(): also executes the EndRequest event and it does allow the execution of the code that following the CompleteRequest call, which makes it more appropriate to handle most situations.
Just a hunch but it sounds like an I.E. caching issue to me...
if I.E is set to automatically check for newer pages 'every time i go to the website.' (in [tools\internet options\general\ browsing history\settings]) then you wont have a cache issue.
Like I say, only a hunch, but give it a whirl.
If you want to get around this [*1], add a guid to your Query string.[*2]
[*1] The cache setting is a user by user setting, you can never pre-empt the users settings, so work with them instead
[*2] The nocache value is always different, the browser will never have a cached version to go to.
I use something like this...
protected void Page_PreRender(object sender, EventArgs e)
{
if (HttpContext.Current.Request.QueryString["FirstRun"] == "1")
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.Url.Query);
nvc.Remove("FirstRun");
string url = Request.Url.AbsolutePath;
for (int i = 0; i < nvc.Count; i++)
url += string.Format("{0}{1}={2}", (i == 0 ? "?" : "&"), nvc.Keys[i], nvc[i]);
Response.Redirect(string.Format("{1}&NoCache={0}",System.Guid.NewGuid().ToString().Replace("-",""),url));
}
}
Any links/redirects to this page need ?FirstRun=1 (or &FirstRun=1) appended to the querystring. The page reload cycles itself once adding a &noCache value to the querystring.
Note:
Because you added FirstRun=1, it will always execute twice serverside, but appear like a single load to your user, and the browser.
If you don't add FirstRun=1, it will behave like a normal request as it never gets into the condition.
A quick project I've been asked to knock together doesn't need crazy security, so, I've implemented a simple login screen that checks the Username & PW against the db.
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
Session.Add("UserSeshAuthenticated", true);
Response.Redirect("Dashboard.aspx");
All the other pages share a MasterPage and in the Page_Load event:
if ((Session["UserSeshAuthenticated"] == null) || ((bool)Session["UserSeshAuthenticated"] == false))
{
fw.Write("UserSeshAuthenticated has been lost or something");
string path = HttpContext.Current.Request.Url.AbsolutePath;
Response.Redirect("Login.aspx?retpath=" + path);
}
else
{
lblLoggedInUsername.Text = Session["UserSeshAuthenticated"].ToString();
}
This all works very well on my development machine, but when I've published it to my server, by the time my MasterPage loads, it has lost the session variables.
Can anyone help ?... I'm supposed to have it live this afternoon & I didn't think I'd run into this problem !!!
Any help appreciated. Thanks a lot.
In your login code, you add "UserSeshAuthenticated" to the session, but not the User object. If the function u.AuthenticateUser() adds a copy of itself into the Session, that could be your problem. Try adding that in your result block instead. Like this:
User u = new User();
if (u.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
Session.Add("UserSeshAuthenticated", true);
Session.Add("oUser", u);
Response.Redirect("Dashboard.aspx");
}