Cancel webclient Async request - c#

Hopefully an easy question for you all but I'm really struggling.
I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.
Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)
private void searchCactus()
{
WebClient imgClient = new WebClient();
imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);
WebClient mwClient = new WebClient();
mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);
if (DeviceNetworkInformation.IsNetworkAvailable == false)
{
MessageBox.Show("No network found, please check network availability and try again");
}
else if (compoundSearchBox.Text.Contains("?"))
{
MessageBox.Show("\"?\" Not Permitted");
return;
}
else if (compoundSearchBox.Text != "")
{
progBar1.IsIndeterminate = true;
string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";
imgClient.OpenReadAsync(new Uri(#imageuri), imgClient);
mwClient.DownloadStringAsync(new Uri(#mwURI), mwClient);
// //lower keyboard
this.Focus();
}
else MessageBox.Show("Enter Search Query");
}
I tried implementing the following button but it does not work
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
imgClient.CancelAsync();
mwClient.CancelAsync();
}
as "the name 'mwClient' does not exist in the current context"
I would be very grateful if anybody could provide some guidance

Just put the two clients into fields in your class.

Related

Downloading email messages with IMAPX

I just started using the open-source library called IMAPX to interact with my IMAP mailbox. I am following this article on CodeProject. I can login properly and retrieve the email folders. But the problem is, the article seems to be incomplete which is leaving me in the middle of the road. Firstly the Retrieving Email Folder's part didn't work. I had to do a workaround.Now, I am trying to download the emails of a folder.The article, regarding this issue, has only a few line of code:
private void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = foldersList.SelectedItem as EmailFolder;
if(item != null)
{
// Load the folder for its messages.
loadFolder(item.Title);
}
}
private void loadFolder(string name)
{
ContentFrame.Content = new FolderMessagesPage(name);
}
The article doesn't explain anything about FolderMessagesPage . So, I made a test page named FolderMessagesPage. I literally have no idea what to put in that page. Can anybody please guide me?
Unfortunately now I'm having some problems in accessing the article on Code Project, but if you need to retrieve the emails, you can start with the following sample code which retrieves the emails from the Inbox folder. I think that might work for you as well.
private static readonly ImapClient _client = new ImapX.ImapClient(ServerImapName, ImapPort, ImapProtocol, false);
if (!_client.Connect())
{
throw new Exception("Error on conncting to the Email server.");
}
if (!_client.Login(User, Password))
{
throw new Exception("Impossible to login to the Email server.");
}
public static List<string> GetInboxEmails()
{
var lstInEmails = new List<string>();
// select the inbox folder
Folder inbox = _client.Folders.Inbox;
if (inbox.Exists > 0)
{
var arrMsg = inbox.Search("ALL", ImapX.Enums.MessageFetchMode.Full);
foreach (var msg in arrMsg)
{
var subject = msg.Subject;
var mailBody = msg.Body.HasHtml ? msg.Body.Html : msg.Body.Text;
lstInEmails.Add(string.Concat(subject, " - ", mailBody );
}
}
return lstInEmails;
}
Hope it helps.
Good bytes.

How to implement chat functionality in windows phone 7

I want to implement a simple online chat application in WP7.
I am using Matrix SDK to implement chat on my WP7
This is how I am trying to connect but I am not able to connect and send any messages.
Neither the events are getting fired..I am not getting any exception also..
what have I done wrong????
Please guide me
Thanks in advance
XmppClient xmppConn;
xmppConn = new XmppClient();
Jid jidUser = new Jid("username");
xmppConn.Username = jidUser.User;
xmppConn.Password = "password";
xmppConn.SetXmppDomain(jidUser.Server);
xmppConn.Uri = new System.Uri("http://server.com:7070/http-bind/",UriKind.RelativeOrAbsolute);
xmppConn.Status = "Testing on Windows Phone 7";
xmppConn.Show = Matrix.Xmpp.Show.Chat;
try
{
xmppConn.Open();
xmppConn.OnLogin += new EventHandler<Matrix.EventArgs>(xmppConn_OnLogin);
//xmppConn.OnPresence += new EventHandler<PresenceEventArgs>(xmppConn_OnPresence);
// xmpp.OnLogin += new EventHandler<Matrix.EventArgs>(xmpp_OnLogin);
}
catch
{
Console.WriteLine("Wrong login data!");
}
}
private void SendButton_Click(object sender, System.EventArgs e)
{
// loose focus to hide keyboard
this.Focus();
messages.Add(new ChatMessage()
{
Side = MessageSide.Me,
Text = TextInput.Text
});
var pm = new PresenceManager(xmppConn);
string sub_id = "xxxxxxxxx";
Jid jid = sub_id;
pm.Subscribe(jid);
xmppConn.Send(new Message(new Jid(jid), MessageType.chat, TextInput.Text));
xmppConn.OnMessage += new EventHandler<MessageEventArgs>(xmppConn_OnMessage);
TextInput.Text = "";
}
Take a look at SignalR for real time web based communications (including chat).
There is an official sample for Windows Phone 8 and also a 3rd party helper for WP7.
Before doing anything on xmpp you first need to set OnBind Event of xmmp class.
Reason: Most of the xmpp works asynchronously.When you call something like client.Open it returns immediately so you first need to wait for OnBind event.

How to control the youtube flash player with c#?

My goal is to make a open source YouTube player that can be controlled via global media keys.
The global key issue I got it covered but the communication between the YouTube player and my Windows Forms application just doesn't work for some reason.
So far this is what I have:
private AxShockwaveFlashObjects.AxShockwaveFlash player;
player.movie = "http://youtube.googleapis.com/v/9bZkp7q19f0"
...
private void playBtn_Click(object sender, EventArgs e)
{
player.CallFunction("<invoke name=\"playVideo\" returntype=\"xml\"></invoke>");
}
Unfortunately this returns:
"Error HRESULT E_FAIL has been returned from a call to a COM component."
What am I missing? Should I load a different URL?
The documentation states that YouTube player uses ExternalInterface class to control it from JavaScript or AS3 so it should work with c#.
UPDATED:
Method used to embed the player: http://www.youtube.com/watch?v=kg-z8JfOIKw
Also tried to use the JavaScript-API in the WebBrowser control but no luck (player just didn't respond to JavaScript commands, tried even to set WebBrowser.url to a working demo, all that I succeeded is to get the onYouTubePlayerReady() to fire using the simple embedded object version )
I think there might be some security issues that I'm overseeing, don't know.
UPDATE 2:
fond solution, see my answer below.
It sounds like your trying to use Adobe Flash as your interface; then pass certain variables back into C#.
An example would be this:
In Flash; create a button... Actionscript:
on (press) {
fscommand("Yo","dude");
}
Then Visual Studio you just need to add the COM object reference: Shockwave Flash Object
Then set the embed to true;
Then inside Visual Studio you should be able to go to Properties; find fscommand. The fscommand will allow you to physically connect the value from the Flash movie.
AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent
That collects; then just use e.command and e.arg for example to have the collected item do something.
Then add this to the EventHandler;
lbl_Result.Text="The "+e.args.ToString()+" "+e.command.ToString()+" was clicked";
And boom it's transmitting it's data from Flash into Visual Studio. No need for any crazy difficult sockets.
On a side note; if you have Flash inside Visual Studio the key is to ensure it's "embed is set to true." That will hold all the path references within the Flash Object; to avoid any miscalling to incorrect paths.
I'm not sure if that is the answer your seeking; or answers your question. But without more details on your goal / error. I can't assist you.
Hope this helps. The first portion should actually show you the best way to embed your Shockwave into Visual Studio.
Make sure you add the correct reference:
Inside your project open 'Solution Explorer'
Right-Click to 'Add Reference'
Go to 'COM Object'
Find Proper object;
COM Objects:
Shockwave ActiveX
Flash Accessibility
Flash Broker
Shockwave Flash
Hope that helps.
It sounds like you aren't embedding it correctly; so you can make the call to it. If I'm slightly mistaken; or is this what you meant:
If your having difficulty Ryk had a post awhile back; with a method to embed YouTube videos:
<% MyYoutubeUtils.ShowEmebddedVideo("<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/gtNlQodFMi8&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/gtNlQodFMi8&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>") %>
Or...
public static string ShowEmbeddedVideo(string youtubeObject)
{
var xdoc = XDocument.Parse(youtubeObject);
var returnObject = string.Format("<object type=\"{0}\" data=\{1}\"><param name=\"movie\" value=\"{1}\" />",
xdoc.Root.Element("embed").Attribute("type").Value,
xdoc.Root.Element("embed").Attribute("src").Value);
return returnObject;
}
Which you can find the thread here: https://stackoverflow.com/questions/2547101/purify-embedding-youtube-videos-method-in-c-sharp
I do apologize if my post appears fragmented; but I couldn't tell if it was the reference, the variable, the method, or embed that was causing you difficulties. Truly hope this helps; or give me more details and I'll tweak my response accordingly.
C# to ActionScript Communication:
import flash.external.ExternalInterface;
ExternalInterface.addCallback("loadAndPlayVideo", null, loadAndPlayVideo);
function loadAndPlayVideo(uri:String):void
{
videoPlayer.contentPath = uri;
}
Then in C#; add an instance of the ActiveX control and add the content into a Constructor.
private AxShockwaveFlash flashPlayer;
public FLVPlayer ()
{
// Add Error Handling; to condense I left out.
flashPlayer.LoadMovie(0, Application.StartupPath + "\\player.swf");
}
fileDialog = new OpenFileDialog();
fileDialog.Filter = "*.flv|*.flv";
fileDialog.Title = "Select a Flash Video File...";
fileDialog.Multiselect = false;
fileDialog.RestoreDirectory = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
flashPlayer.CallFunction("<invoke" + " name=\"loadAndPlayVideo\" returntype=\"xml"> <arguements><string>" + fileDialog.FileName + "</string></arguements></invoke>");
}
ActionScript Communication to C#:
import flash.external.ExternalInterface;
ExternalInterface.call("ResizePlayer", videoPlayer.metadata.width, videoPlayer.metadata.height);
flashPlayer.FlashCall += new _IShockwaveFlashEvents_FlashCallEventHandler(flashPlayer_FlashCall);
Then the XML should appear:
<invoke name="ResizePlayer" returntype="xml">
<arguements>
<number> 320 </number>
<number> 240 </number>
</arguments>
</invoke>
Then parse the XML in the event handler and invoke the C# function locally.
XmlDocument document = new XmlDocument();
document.LoadXML(e.request);
XmlNodeList list = document.GetElementsByTagName("arguements");
ResizePlayer(Convert.ToInt32(list[0].FirstChild.InnerText), Convert.ToInt32(list[0].ChildNodes[1].InnerText));
Now they are both passing data back and forth. That is a basic example; but by utilizing the ActionScript Communication you shouldn't have any issues utilizing the native API.
Hope that is more helpful. You can expand on that idea by a utility class for reuse. Obviously the above code has some limitations; but hopefully it points you in the right direction. Was that direction you were attempting to go? Or did I still miss the point?
Create a new Flash Movie; in ActionScript 3. Then on the initial first frame; apply the below:
Security.allowDomain("www.youtube.com");
var my_player:Object;
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"))
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}
function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
my_player.loadVideoById("_OBlgSz8sSM",0);
}
So what exactly is that script doing? It is utilizing the native API and using ActionScript Communication. So below I'll break down each line.
Security.allowDomain("www.youtube.com");
Without that line YouTube won't interact with the object.
var my_player:Object;
You can't just load a movie into the movie; so we will create a variable Object. You have to load a special .swf that will contain access to those codes. The below; does just that. So you can access the API.
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
We now reference the Google API per their documentation.
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
But in order to actually work with our object; we need to wait for it to be fully initialized. So the Event Listener will wait; so we know when we can pass commands to it.
The onLoaderInit function will be triggered upon initialization. Then it's first task will be my_loader to display the list so that the video appears.
The addChild(my_loader); is what will load one; the my_player = my_loader.content; will store a reference for easy access to the object.
Though it has been initialized; you have to wait even further... You use my_player.addEventListener("onReady", onPlayerReady); to wait and listen for those custom events. Which will allow a later function to handle.
Now the player is ready for basic configuration;
function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
}
The above function starts very basic manipulation. Then the last line my_player.loadVideoById("_OBlgSz8sSM",0); is referencing the particular video.
Then on your stage; you could create two buttons and apply:
play_btn.addEventListener(MouseEvent.CLICK, playVid);
function playVid(e:MouseEvent):void {
my_player.playVideo();
}
pause_btn.addEventListener(MouseEvent.CLICK, pauseVid);
function pauseVid(e:MouseEvent):void {
my_player.pauseVideo();
}
Which would give you a play and pause functionality. Some additional items you could use our:
loadVideoById()
cueVideoById()
playVideo()
pauseVideo()
stopVideo()
mute()
unMute()
Keep in mind those can't be used or called until it has been fully initialized. But using that; with the earlier method should allow you to layout the goal and actually pass variables between the two for manipulation.
Hopefully that helps.
I'd start by making sure that javascript can talk to your flash app.
make sure you have: allowScriptAccess="sameDomain" set in the embed (from http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#includeExamplesSummary).
you should validate that html->flash works; then C->html; and gradually work up to C->you-tube-component. you have a lot of potential points of failure between C and the you-tube-component right now and it's hard to address all of them at the same time.
After a lot of tries and head-hammering, I've found a solution:
Seems that the Error HRESULT E_FAIL... happens when the flash dosen't understand the requested flash call. Also for the youtube external api to work, the js api needs to be enabled:
player.movie = "http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1"
As I said in the question the whole program is open source, so you will find the full code at bitbucket. Any advice, suggestions or collaborators are highly appreciated.
The complete solution:
Here is the complete guide for embedding and interacting with the YouTube player or any other flash object.
After following the video tutorial
, set the flash player's FlashCall event to the function that will handle the flash->c# interaction (in my example it's YTplayer_FlashCall )
the generated `InitializeComponent()` should be:
...
this.YTplayer = new AxShockwaveFlashObjects.AxShockwaveFlash();
this.YTplayer.Name = "YTplayer";
this.YTplayer.Enabled = true;
this.YTplayer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("YTplayer.OcxState")));
this.YTplayer.FlashCall += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEventHandler(this.YTplayer_FlashCall);
...
the FlashCall event handler
private void YTplayer_FlashCall(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEvent e)
{
Console.Write("YTplayer_FlashCall: raw: "+e.request.ToString()+"\r\n");
// message is in xml format so we need to parse it
XmlDocument document = new XmlDocument();
document.LoadXml(e.request);
// get attributes to see which command flash is trying to call
XmlAttributeCollection attributes = document.FirstChild.Attributes;
String command = attributes.Item(0).InnerText;
// get parameters
XmlNodeList list = document.GetElementsByTagName("arguments");
List<string> listS = new List<string>();
foreach (XmlNode l in list){
listS.Add(l.InnerText);
}
Console.Write("YTplayer_FlashCall: \"" + command.ToString() + "(" + string.Join(",", listS) + ")\r\n");
// Interpret command
switch (command)
{
case "onYouTubePlayerReady": YTready(listS[0]); break;
case "YTStateChange": YTStateChange(listS[0]); break;
case "YTError": YTStateError(listS[0]); break;
default: Console.Write("YTplayer_FlashCall: (unknownCommand)\r\n"); break;
}
}
this will resolve the flash->c# communication
calling the flash external functions (c#->flash):
private string YTplayer_CallFlash(string ytFunction){
string flashXMLrequest = "";
string response="";
string flashFunction="";
List<string> flashFunctionArgs = new List<string>();
Regex func2xml = new Regex(#"([a-z][a-z0-9]*)(\(([^)]*)\))?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match fmatch = func2xml.Match(ytFunction);
if(fmatch.Captures.Count != 1){
Console.Write("bad function request string");
return "";
}
flashFunction=fmatch.Groups[1].Value.ToString();
flashXMLrequest = "<invoke name=\"" + flashFunction + "\" returntype=\"xml\">";
if (fmatch.Groups[3].Value.Length > 0)
{
flashFunctionArgs = pars*emphasized text*eDelimitedString(fmatch.Groups[3].Value);
if (flashFunctionArgs.Count > 0)
{
flashXMLrequest += "<arguments><string>";
flashXMLrequest += string.Join("</string><string>", flashFunctionArgs);
flashXMLrequest += "</string></arguments>";
}
}
flashXMLrequest += "</invoke>";
try
{
Console.Write("YTplayer_CallFlash: \"" + flashXMLrequest + "\"\r\n");
response = YTplayer.CallFunction(flashXMLrequest);
Console.Write("YTplayer_CallFlash_response: \"" + response + "\"\r\n");
}
catch
{
Console.Write("YTplayer_CallFlash: error \"" + flashXMLrequest + "\"\r\n");
}
return response;
}
private static List<string> parseDelimitedString (string arguments, char delim = ',')
{
bool inQuotes = false;
bool inNonQuotes = false;
int whiteSpaceCount = 0;
List<string> strings = new List<string>();
StringBuilder sb = new StringBuilder();
foreach (char c in arguments)
{
if (c == '\'' || c == '"')
{
if (!inQuotes)
inQuotes = true;
else
inQuotes = false;
whiteSpaceCount = 0;
}else if (c == delim)
{
if (!inQuotes)
{
if (whiteSpaceCount > 0 && inQuotes)
{
sb.Remove(sb.Length - whiteSpaceCount, whiteSpaceCount);
inNonQuotes = false;
}
strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());
sb.Remove(0, sb.Length);
}
else
{
sb.Append(c);
}
whiteSpaceCount = 0;
}
else if (char.IsWhiteSpace(c))
{
if (inNonQuotes || inQuotes)
{
sb.Append(c);
whiteSpaceCount++;
}
}
else
{
if (!inQuotes) inNonQuotes = true;
sb.Append(c);
whiteSpaceCount = 0;
}
}
strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());
return strings;
}
adding Youtube event handlers:
private void YTready(string playerID)
{
YTState = true;
//start eventHandlers
YTplayer_CallFlash("addEventListener(\"onStateChange\",\"YTStateChange\")");
YTplayer_CallFlash("addEventListener(\"onError\",\"YTError\")");
}
private void YTStateChange(string YTplayState)
{
switch (int.Parse(YTplayState))
{
case -1: playState = false; break; //not started yet
case 1: playState = true; break; //playing
case 2: playState = false; break; //paused
//case 3: ; break; //buffering
case 0: playState = false; if (!loopFile) mediaNext(); else YTplayer_CallFlash("seekTo(0)"); break; //ended
}
}
private void YTStateError(string error)
{
Console.Write("YTplayer_error: "+error+"\r\n");
}
usage ex:
YTplayer_CallFlash("playVideo()");
YTplayer_CallFlash("pauseVideo()");
YTplayer_CallFlash("loadVideoById(KuNQgln6TL0)");
string currentVideoId = YTplayer_CallFlash("getPlaylist()");
string currentDuration = YTplayer_CallFlash("getDuration()");
The functions YTplayer_CallFlash, YTplayer_FlashCall should work for any flash-C# communication with minor adjustments like the YTplayer_CallFlash's switch (command).
This stumped me for a number of hours.
Just add enable JS to your URL:
http://www.youtube.com/v/9bZkp7q19f0?version=3&enablejsapi=1
CallFunction works fine for me now! Also remove unrequired space in the call.

Problems using captured access token to retrieve user's facebook information

I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Categories