How to clear System.Windows.Forms.WebBrowser session data? - c#

How can I clear current session data (cookies, cached data, auth sessions, etc) without restarting the application?
Update: I'm talking about WebBrowser control in Windows.Forms, not the ASP.Net session.

To clear session (such as HttpOnly cookies), you can use InternetSetOption() from wininet.dll.
private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
and use this method whenever need to clear session.
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
webBrowser1.Document.Window.Navigate(url);

I tried everything to clear the form data so the next user would not see the previous email address, etc. I ended up doing this to clear the cookies...
string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
foreach (string currentFile in theCookies)
{
try
{
System.IO.File.Delete(currentFile);
}
catch (Exception ex)
{
}
}

If you have javascript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on (I haven't yet found a way to clear session cookies other than this).
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
It's derived from this bookmarklet for clearing cookies.
In addition to this, you can delete the contents of the "C:\Documents and Settings\username\Cookies" folder (minus the index.dat, which is usually locked).
As for the cached data, it should be sufficient to just delete all of the files in "C:\Documents and Settings\username\Local Settings\Temporary Internet Files".
If you really need to be able to clear the cookies for all sites, you're probably better off using something like the axWebBrowser control in the long run.

Private Const INTERNET_OPTION_END_BROWSER_SESSION As Integer = 42
<DllImport("wininet.dll", SetLastError:=True)>
Public Shared Function InternetSetOption(hInternet As IntPtr, dwOption As Integer, lpBuffer As IntPtr, lpdwBufferLength As Integer) As Boolean
End Function
Private Sub WebBrowserFormName_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0)
End Sub
Just posting for someone looking for this answer in VB.
Happy coding!!!

webBrowser1.Document.Cookies = "" won't work. This call will not clear the cookie. webBrowser1.Document.Cookies = just works as document.cookie in javascript.
You should find the cookie you want to clear, sa 'Session', use
webBrowser1.Document.Cookies = "Session = ''";
It will just set the cookie to '', as you want.

Following solution worked for me -
webBrowser1.Document.ExecCommand("ClearAuthenticationCache", false, null);
This was suggested in following post for deleting cookies - https://stackoverflow.com/a/21512662/6291511
You can find more info regarding this here - https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.execcommand(v=vs.110).aspx
Hope it helps!!!

You have to realise that the way "session state" is tracked, from the point of view of a web server, is by giving the client browser a cookie with a session-id in it. When the browser posts back to the server, that cookie allows the server to associate the request with a stored session state.
So the solution is to clear the cookies of the webBrowser control. Eg webBrowser1.Document.Cookies = "", that should work I think.
ASP.NET also has what it calls "cookieless sessions", which work by adding the session id to the url. So if that's the mechanism used by the server, you could try to filter that out of the url. But you won't see that much, it's mostly the cookie based session state.

Windows 7 uses index.dat files to store cookies and history so that Bill and his freinds at CIA central can snoop on you and have done all they can to ensure you can not delete these files and that after taking copies because 'Special Folders' are used and the .Dat files remain locked whilst windows is running.
This is not a perfect solution but it works to some degree with the full file names being in a List.
int DeletedCount = 0;
int CouldNotDelete = 0;
KillExplorer();
foreach (string DatFile in DatFiles)
{//Do not put break point or step into the code else explorer will start and the file will become locked again
DirectoryInfo DInfo=new DirectoryInfo(DatFile.Replace("index.dat",""));
FileAttributes OldDirAttrib = DInfo.Attributes;
DInfo.Attributes = FileAttributes.Normal;//Set to normal else can not delete
FileInfo FInfo = new FileInfo(DatFile);
FileAttributes OldFileAttrib = FInfo.Attributes;
SetAttr(FInfo, FileAttributes.Normal);
TryDelete(FInfo);
SetAttr(FInfo, OldFileAttrib);//Sets back to Hidden,system,directory,notcontentindexed
if (File.Exists(DatFile))
CouldNotDelete++;
else
DeletedCount++;
}
if (DatFiles.Count>0)//Lets get explorer running again
System.Diagnostics.Process.Start(DatFiles[DatFiles.Count - 1].Replace("index.dat", ""));
else
System.Diagnostics.Process.Start("explorer");
System.Windows.Forms.MessageBox.Show("Deleted " + DeletedCount + " Index.dat files with " + CouldNotDelete + " Errors");
return "Deleted " + DeleteFileCount + " Files ";
}
private void KillExplorer()
{
foreach (Process P in Process.GetProcesses())
{//Kill both these process because these are the ones locking the files
if (P.ProcessName.ToLower() == "explorer")
P.Kill();
if (P.ProcessName.ToLower() == "iexplore")
P.Kill();
}
}
private bool TryDelete(FileInfo Info)
{
try
{
Info.Delete();
return true;
}
catch
{return false;}
}
private void SetAttr(FileInfo Info,FileAttributes Attr)
{
try
{
Info.Attributes = Attr;
}
catch { }
}

Related

WPF app log out from Azure ACS [duplicate]

I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.
If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.
int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);
I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing?
If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
It's derived from this bookmarklet for clearing cookies.
I modified the solution from here:
http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html
Actually, you don't need an unsafe code. Here is the helper class that works for me:
public static class WinInetHelper
{
public static bool SupressCookiePersist()
{
// 3 = INTERNET_SUPPRESS_COOKIE_PERSIST
// 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
return SetOption(81, 3);
}
public static bool EndBrowserSession()
{
// 42 = INTERNET_OPTION_END_BROWSER_SESSION
return SetOption(42, null);
}
static bool SetOption(int settingCode, int? option)
{
IntPtr optionPtr = IntPtr.Zero;
int size = 0;
if (option.HasValue)
{
size = sizeof (int);
optionPtr = Marshal.AllocCoTaskMem(size);
Marshal.WriteInt32(optionPtr, option.Value);
}
bool success = InternetSetOption(0, settingCode, optionPtr, size);
if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
return success;
}
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(
int hInternet,
int dwOption,
IntPtr lpBuffer,
int dwBufferLength
);
}
You call SupressCookiePersist somewhere at the start of the process and
EndBrowserSession to clear cookies when browser is closed as described here:
Facebook multi account
I found a solution, for deleting all cookies.
the example found on the url, deletes the cookies on application (process) startup.
http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html
The solution is using InternetSetOption
Function to announce the WEBBROWSER to clear all its content.
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
MessageBox.Show("Something went wrong !>?");
}
Note, that clears the cookies for the specific PROCESS only as written on MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR:
A general purpose option that is used to suppress behaviors on a
process-wide basis.
A variant of other proposed answers, which doesn't require unsafe code or manual marshalling:
private static void SuppressCookiePersistence()
{
int flag = INTERNET_SUPPRESS_COOKIE_PERSIST;
if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, ref flag, sizeof(int)))
{
var ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
throw ex;
}
}
const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, ref int flag, int dwBufferLength);
web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. so by this answer you can try this:
System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
Try using this:
System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");
I'm using this code and it works without JavaScript. It's doing the same things as the JavaScript, but in VB.NET. Also, no navigation needed.
For Each cookie As String In Document.Cookie.Split(";"c)
Dim domain As String = "." + url.Host
While domain.Length > 0
Dim path As String = url.LocalPath
While path.Length > 0
Document.Cookie = cookie.Split("="c)(0).Trim & "= ;expires=Thu, 30-Oct-1980 16:00:00 GMT;path=" & path & ";domain=" & domain
path = path.Substring(0, path.Length - 1)
End While
Select Case domain.IndexOf(".")
Case 0
domain = domain.Substring(1)
Case -1
domain = ""
Case Else
domain = domain.Substring(domain.IndexOf("."))
End Select
End While
Next
The only real difference from the JavaScript is where, instead of just expiring cookie=value, I specifically search for the = and expire cookie=. This is important for expiring cookies that have no value.
Pitfalls:
You can only delete the cookies of the website to which you have navigated.
If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. Or not, it's a race between the redirect and your code.
Don't access Document until ReadyState = WebBrowserReadyState.Complete, otherwise Document will be Nothing and the dereference will throw an exception.
Probably lots of others, but this code works great for me.
Firefox with the View Cookies Add-On helped a lot in debugging specific web pages.
Does the webbrowser control show pages form mutliple sites that you, as a developer, are not in control of, or are you just using the web browser control to view custom HTML pages created within your application?
If it is the former, cookies are directly tied to the domain that sets them, and as such to delete these cookies you would need to monitor the users's cookie directory and delete any new cookies created, a track changes to existing cookies.
If it is the later, you can always send the webbrowser control to a custom page that deletes the cookies with either server-side scripting (if available in your application) or JavaScript.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code:
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
how says for Jordan Milne in this topic above.
In my application I need use webbrowser1.navigate("xxx");
here don't work if you use the C# properties.
i hope you find it useful this information.

CreateProcessAsUser user context

I've already been searching long time but couldn't find a working solution yet :-(
I have created a window service that launches a client on every user logged on to a machine using CreateProcessAsUser (http://www.pinvoke.net/default.aspx/advapi32/createprocessasuser.html), WTSEnumerateSessions and so on...
This works fine already. The client starts in the user's session, shows its taskbar icon, and communication with the service is working fine.
The problem I have is that I need to have that client store temporary files in the user's profile. I tried starting with a small log file so that I can keep track of any errors that my user's could eventually experience. Unfortunately I can not save to the user's temp folder because the client somehow seems to be running in LocalSystem's context although WindowsIdentity shows the correct user: System.IO.Path.GetTempPath() always returns 'C:\Windows\Temp' but my user's don't have administrative rights so they are not able to write there... furthermore, I planned to store settings in the current user's registry which is not working, too. I think this is related to the wrong temp path in some way.
I also tried CreateEnvironmentBlock (http://www.pinvoke.net/default.aspx/userenv/CreateEnvironmentBlock.html) but I could not make it work and somewhere I found an article saying that this won't work any more on Vista or higher so I stopped researching on that one.
For testing I have created a small test form just doing this:
MessageBox.Show("Temp: " + System.IO.Path.GetTempPath() + Environment.NewLine + "User: " + WindowsIdentity.GetCurrent().Name, "Before impersonation");
WindowsIdentity currentUserId = WindowsIdentity.GetCurrent();
WindowsImpersonationContext impersonatedUser = currentUserId.Impersonate();
MessageBox.Show("Temp: " + System.IO.Path.GetTempPath() + Environment.NewLine + "User: " + WindowsIdentity.GetCurrent().Name, "After impersonation");
This one always shows the same results before and after impersonation: "Temp: C:\Windows\Temp User:testdomain\testuser" :-(
If it helps here's my function to start a process (user token is delivered by WTSEnumerateSessions) - of course this only works under LocalSystem's context:
public static Process StartProcessAsUser(IntPtr UserToken, string App, string AppPath, string AppParameters)
{
Process ResultProcess = null;
IntPtr hDupedToken = IntPtr.Zero;
NativeProcessAPI.PROCESS_INFORMATION oProcessInformation = new NativeProcessAPI.PROCESS_INFORMATION();
try
{
NativeProcessAPI.SECURITY_ATTRIBUTES oSecurityAttributes = new NativeProcessAPI.SECURITY_ATTRIBUTES();
oSecurityAttributes.Length = Marshal.SizeOf(oSecurityAttributes);
bool result = NativeProcessAPI.DuplicateTokenEx(
UserToken,
NativeProcessAPI.GENERIC_ALL_ACCESS,
ref oSecurityAttributes,
(int)NativeProcessAPI.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)NativeProcessAPI.TOKEN_TYPE.TokenPrimary,
ref hDupedToken
);
if (!result)
{
return null;
}
NativeProcessAPI.STARTUPINFO oStartupInfo = new NativeProcessAPI.STARTUPINFO();
oStartupInfo.cb = Marshal.SizeOf(oStartupInfo);
oStartupInfo.lpDesktop = String.Empty;
result = NativeProcessAPI.CreateProcessAsUser(
hDupedToken,
null,
App + " " + AppParameters,
ref oSecurityAttributes, ref oSecurityAttributes,
false, 0, IntPtr.Zero,
AppPath, ref oStartupInfo, ref oProcessInformation
);
if (result)
{
try
{
int ProcessID = oProcessInformation.dwProcessID;
try
{
ResultProcess = System.Diagnostics.Process.GetProcessById(ProcessID);
}
catch
{
ResultProcess = null;
}
}
catch (Exception ex)
{
ResultProcess = null;
}
}
}
catch
{
ResultProcess = null;
}
finally
{
if (oProcessInformation.hProcess != IntPtr.Zero)
NativeProcessAPI.CloseHandle(oProcessInformation.hProcess);
if (oProcessInformation.hThread != IntPtr.Zero)
NativeProcessAPI.CloseHandle(oProcessInformation.hThread);
if (hDupedToken != IntPtr.Zero)
NativeProcessAPI.CloseHandle(hDupedToken);
}
return ResultProcess;
}
Any ideas how I could start my processes in the user's contexts and not in the context of LocalSystem?
Thanks a lot!
Leaving this here for anyone else wondering how to do this: CreateEnvironmentBlock is what you need to use.
DuplicateTokenEx(userToken, MAXIMUM_ALLOWED | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, IntPtr.Zero, SecurityIdentification, TokenPrimary, out dupUserToken);
CreateEnvironmentBlock(out envBlock, dupUserToken, false);
CreateProcessAsUserW(dupUserToken, null, cmdLine, IntPtr.Zero, IntPtr.Zero, false,
(uint)(CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT),
envBlock, processDir, ref startupInfo, out procInfo);
Ok I have found a workaround: I switched to using the USERS hive instead of the CURRENT_USER hive by using the SID provided by WindowsIdentity:
Microsoft.Win32.Registry.Users.OpenSubKey(System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString() + ..., true)
This works perfectly although it feels a bit uncomfortable to get environment variables from the user's "environment" and "volatile environment" registry paths instead of just using .Net's built-in functions...
But thanks a lot for your help ;-)
EDIT:
I will not mark this as an answer because it is a) my own solution and b) just a workaround

Delete all WebBrowser cookies and session data also set referer [duplicate]

I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.
If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.
int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);
I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing?
If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
It's derived from this bookmarklet for clearing cookies.
I modified the solution from here:
http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html
Actually, you don't need an unsafe code. Here is the helper class that works for me:
public static class WinInetHelper
{
public static bool SupressCookiePersist()
{
// 3 = INTERNET_SUPPRESS_COOKIE_PERSIST
// 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
return SetOption(81, 3);
}
public static bool EndBrowserSession()
{
// 42 = INTERNET_OPTION_END_BROWSER_SESSION
return SetOption(42, null);
}
static bool SetOption(int settingCode, int? option)
{
IntPtr optionPtr = IntPtr.Zero;
int size = 0;
if (option.HasValue)
{
size = sizeof (int);
optionPtr = Marshal.AllocCoTaskMem(size);
Marshal.WriteInt32(optionPtr, option.Value);
}
bool success = InternetSetOption(0, settingCode, optionPtr, size);
if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
return success;
}
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(
int hInternet,
int dwOption,
IntPtr lpBuffer,
int dwBufferLength
);
}
You call SupressCookiePersist somewhere at the start of the process and
EndBrowserSession to clear cookies when browser is closed as described here:
Facebook multi account
I found a solution, for deleting all cookies.
the example found on the url, deletes the cookies on application (process) startup.
http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html
The solution is using InternetSetOption
Function to announce the WEBBROWSER to clear all its content.
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
MessageBox.Show("Something went wrong !>?");
}
Note, that clears the cookies for the specific PROCESS only as written on MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR:
A general purpose option that is used to suppress behaviors on a
process-wide basis.
A variant of other proposed answers, which doesn't require unsafe code or manual marshalling:
private static void SuppressCookiePersistence()
{
int flag = INTERNET_SUPPRESS_COOKIE_PERSIST;
if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, ref flag, sizeof(int)))
{
var ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
throw ex;
}
}
const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, ref int flag, int dwBufferLength);
web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. so by this answer you can try this:
System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
Try using this:
System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");
I'm using this code and it works without JavaScript. It's doing the same things as the JavaScript, but in VB.NET. Also, no navigation needed.
For Each cookie As String In Document.Cookie.Split(";"c)
Dim domain As String = "." + url.Host
While domain.Length > 0
Dim path As String = url.LocalPath
While path.Length > 0
Document.Cookie = cookie.Split("="c)(0).Trim & "= ;expires=Thu, 30-Oct-1980 16:00:00 GMT;path=" & path & ";domain=" & domain
path = path.Substring(0, path.Length - 1)
End While
Select Case domain.IndexOf(".")
Case 0
domain = domain.Substring(1)
Case -1
domain = ""
Case Else
domain = domain.Substring(domain.IndexOf("."))
End Select
End While
Next
The only real difference from the JavaScript is where, instead of just expiring cookie=value, I specifically search for the = and expire cookie=. This is important for expiring cookies that have no value.
Pitfalls:
You can only delete the cookies of the website to which you have navigated.
If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. Or not, it's a race between the redirect and your code.
Don't access Document until ReadyState = WebBrowserReadyState.Complete, otherwise Document will be Nothing and the dereference will throw an exception.
Probably lots of others, but this code works great for me.
Firefox with the View Cookies Add-On helped a lot in debugging specific web pages.
Does the webbrowser control show pages form mutliple sites that you, as a developer, are not in control of, or are you just using the web browser control to view custom HTML pages created within your application?
If it is the former, cookies are directly tied to the domain that sets them, and as such to delete these cookies you would need to monitor the users's cookie directory and delete any new cookies created, a track changes to existing cookies.
If it is the later, you can always send the webbrowser control to a custom page that deletes the cookies with either server-side scripting (if available in your application) or JavaScript.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code:
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
how says for Jordan Milne in this topic above.
In my application I need use webbrowser1.navigate("xxx");
here don't work if you use the C# properties.
i hope you find it useful this information.

Why can I change the Registry only the first time?

I am attempting to write an application that automatically changes the proxy server based upon what network connection is active. In this application, the user can also manually click a server in the notifyIcon context menu and call the function to switch the server.
My problem is the following: The application changes the proxy server the first time the function is called, but will not work after that. I have put debug statements in to make sure the correct proxy server is being passed to that function (and it is indeed correct), but the registry entries never get changed after the first time. What am I doing wrong?
Here is my Proxy Class:
class Proxy
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
public void SetProxy(ProxyList proxy)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", proxy.server + ":" + proxy.port);
registry.Close();
// These lines implement the Interface in the beginning of program
// They cause the OS to refresh the settings, causing IP to realy update
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
}
And here is how I call the function from the context menu:
void Form1_Click(object sender, EventArgs e)
{
Proxy proxyServer = new Proxy();
ToolStripMenuItem item = (ToolStripMenuItem)sender;
proxyServer.SetProxy(XML.proxy[(int)item.Tag]);
proxyServer = null;
notifyIcon1.BalloonTipText = XML.proxy[(int)item.Tag].name + " is now your Active Proxy";
notifyIcon1.ShowBalloonTip(1);
}
From Microsoft's Knowledge Base: How to programmatically query and set proxy settings under Internet Explorer
Note INTERNET_OPTION_PER_CONNECTION_OPTION causes the settings to be changed on a system-wide basis when a NULL handle is used. To correctly reflect global proxy settings, you must call the InternetSetOption function with the INTERNET_OPTION_REFRESH option flag.
This is from MSDN
INTERNET_OPTION_PER_CONNECTION_OPTION
75
Sets or retrieves an INTERNET_PER_CONN_OPTION_LIST structure that specifies a list of options for a particular connection. This is used by InternetQueryOption and InternetSetOption. This option is only valid in Internet Explorer 5 and later.
Read about the INTERNET_PER_CONN_OPTION_LIST structure.
Note: the value for the INTERNET_PER_CONN_PROXY_SERVER flag is 2.
RegistryKey class is disposable. Maybe it is being cached or something, try disposing it in addition of closing it.
i think you'd better do a plug-in for your browser instead of changing the registry directly.

How to delete Cookies from windows.form?

I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.
If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.
int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);
I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing?
If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
It's derived from this bookmarklet for clearing cookies.
I modified the solution from here:
http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html
Actually, you don't need an unsafe code. Here is the helper class that works for me:
public static class WinInetHelper
{
public static bool SupressCookiePersist()
{
// 3 = INTERNET_SUPPRESS_COOKIE_PERSIST
// 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
return SetOption(81, 3);
}
public static bool EndBrowserSession()
{
// 42 = INTERNET_OPTION_END_BROWSER_SESSION
return SetOption(42, null);
}
static bool SetOption(int settingCode, int? option)
{
IntPtr optionPtr = IntPtr.Zero;
int size = 0;
if (option.HasValue)
{
size = sizeof (int);
optionPtr = Marshal.AllocCoTaskMem(size);
Marshal.WriteInt32(optionPtr, option.Value);
}
bool success = InternetSetOption(0, settingCode, optionPtr, size);
if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
return success;
}
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(
int hInternet,
int dwOption,
IntPtr lpBuffer,
int dwBufferLength
);
}
You call SupressCookiePersist somewhere at the start of the process and
EndBrowserSession to clear cookies when browser is closed as described here:
Facebook multi account
I found a solution, for deleting all cookies.
the example found on the url, deletes the cookies on application (process) startup.
http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html
The solution is using InternetSetOption
Function to announce the WEBBROWSER to clear all its content.
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
MessageBox.Show("Something went wrong !>?");
}
Note, that clears the cookies for the specific PROCESS only as written on MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR:
A general purpose option that is used to suppress behaviors on a
process-wide basis.
A variant of other proposed answers, which doesn't require unsafe code or manual marshalling:
private static void SuppressCookiePersistence()
{
int flag = INTERNET_SUPPRESS_COOKIE_PERSIST;
if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, ref flag, sizeof(int)))
{
var ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
throw ex;
}
}
const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, ref int flag, int dwBufferLength);
web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. so by this answer you can try this:
System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
Try using this:
System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");
I'm using this code and it works without JavaScript. It's doing the same things as the JavaScript, but in VB.NET. Also, no navigation needed.
For Each cookie As String In Document.Cookie.Split(";"c)
Dim domain As String = "." + url.Host
While domain.Length > 0
Dim path As String = url.LocalPath
While path.Length > 0
Document.Cookie = cookie.Split("="c)(0).Trim & "= ;expires=Thu, 30-Oct-1980 16:00:00 GMT;path=" & path & ";domain=" & domain
path = path.Substring(0, path.Length - 1)
End While
Select Case domain.IndexOf(".")
Case 0
domain = domain.Substring(1)
Case -1
domain = ""
Case Else
domain = domain.Substring(domain.IndexOf("."))
End Select
End While
Next
The only real difference from the JavaScript is where, instead of just expiring cookie=value, I specifically search for the = and expire cookie=. This is important for expiring cookies that have no value.
Pitfalls:
You can only delete the cookies of the website to which you have navigated.
If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. Or not, it's a race between the redirect and your code.
Don't access Document until ReadyState = WebBrowserReadyState.Complete, otherwise Document will be Nothing and the dereference will throw an exception.
Probably lots of others, but this code works great for me.
Firefox with the View Cookies Add-On helped a lot in debugging specific web pages.
Does the webbrowser control show pages form mutliple sites that you, as a developer, are not in control of, or are you just using the web browser control to view custom HTML pages created within your application?
If it is the former, cookies are directly tied to the domain that sets them, and as such to delete these cookies you would need to monitor the users's cookie directory and delete any new cookies created, a track changes to existing cookies.
If it is the later, you can always send the webbrowser control to a custom page that deletes the cookies with either server-side scripting (if available in your application) or JavaScript.
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code:
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
how says for Jordan Milne in this topic above.
In my application I need use webbrowser1.navigate("xxx");
here don't work if you use the C# properties.
i hope you find it useful this information.

Categories

Resources