Raising UAC window loads my form twice - vb.net

I am using following code to raise UAC window. It works fine but my form that contains button to raise this window is shown twice. I mean if I put it in CopyFiile Button, when I click this button, it raises UAC windows, copies file, gives success message and then opens another instance of the same form that contains copyfile button. Please help.
Dim proc As New ProcessStartInfo
proc.UseShellExecute = True
proc.WorkingDirectory = Environment.CurrentDirectory
proc.FileName = Application.ExecutablePath
proc.Verb = "runas"
Try
Process.Start(proc)
Catch
' The user refused to allow privileges elevation.
MsgBox("Permission denied by user ! Can not proceed.", MsgBoxStyle.Critical)
vrIfDenied = 1
Return
End Try

Correct me if I'm wrong but i see your proc filename property is equals to it's self. You are running the same application and makes 2 instances of the current application

Add this to your code:
<DllImport("shell32.dll", EntryPoint:="IsUserAnAdmin")> _
Public Shared Function IsUserAnAdmin() As Boolean
End Function
Now when your app loads, check to see if it is running as elevated priviledges, and grey out the Copyfile button like this if it isn't:
If IsUserAnAdmin() = False Then
btnCopyFile.enabled=false
ElseIf IsUserAnAdmin() = True Then
btnCopyFile.enable=true
btnElevateMe.enabled=false
End If
Now you can add a 2nd button (btnElevateMe) which will use the code you originally posted to elevate the priviledges and bring up the UAC prompt. When running WITH priviledges, it will be greyed out.
Also, add to your code after "End Try" this:
Application.Exit()
And it will close the app after starting a second instance with elevated priviledges.

Related

Error thrown trying launch a webpage from a button

I created a button and a menu item in vb.net (.NET 6). I found several answers here on SO that say the process to launching a webpage from such an event can be launched with this code:
Dim webAddress As String = "http://www.example.com/"
Process.Start(webAddress)
However, trying launch the code, I'm given the error of "system cannot find the file specified".
Looking more into it, I know that .NET 6 is running a bit differently and changed the code to the following:
Using link As New Process()
link.StartInfo.UseShellExecute = True
link.Start(New ProcessStartInfo("https://example.com"))
End Using
But still to no avail, and I am given the same error. "System cannot find the file specified." I can run addresses via the regular Windows Run prompt... but the program still cannot launch.
Following Jimi's comment to my original question, I changed the Sub to the following:
Sub LaunchWebsite(strWebpageURL As String)
Using Process.Start(New ProcessStartInfo(strWebpageURL) With {.UseShellExecute = True})
End Using
End Sub
Using this, the webpage launched in my desktop's default browser with no problem.
You can use
Respone.Redirect("http://www.example.com/")
or use javascript in server side code
Dim url As String = "http://www.example.com"
Dim s As String = "window.open('" & url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');"
ClientScript.RegisterStartupScript(Me.GetType(), "script", s, True)
Above code open webpage in new popup window.
Regards
Aravind

Run Internet Explorer as a different user

I'm trying to launch Internet Explorer with a different user to access a website that requires single sign on.
Below is the code that I'm using. It doesn't produce any errors but IE doesn't launch at all, not even the process.
Try
System.Diagnostics.Process.Start(IExplorerPath, Username, ConvertToSecureString(Password), Domain)
Success = True
Catch ex As Exception
Success = False
Error_Message = ex.Message
End Try
I also tried the following variation with the same result (nothing):
Try
Dim psi As New ProcessStartInfo()
psi.Filename = IExplorerPath
psi.UserName = Username
psi.Domain = Domain
psi.Password = ConvertToSecureString(Password)
psi.UseShellExecute = False
Process.Start(psi)
Success = True
Catch ex As Exception
Success = False
Error_Message = ex.Message
End Try
This is the ConvertToSecureString function:
Function ConvertToSecureString(ByVal str As String)
Dim password As New SecureString
For Each c As Char In str.ToCharArray
password.AppendChar(c)
Next
Return password
End Function
Ok, I've been searching a lot a solution for this and if you have it you deserve a Nobel price. In the mean time, if it helps anyone this is the workaround that I had to use:
Use Process.Start to run a .bat file that contains the following code:
runas /user:User#Domain.com "C:\Program Files\Internet Explorer\iexplore.exe"
Then, when the command prompt appears I use the Send Keys to type in the password and press Enter.
This launches IE with different credentials. But again, there should be a better way.
This may / may not work. Try to launch your website that requires single sign on in "CHROME", hit F-12, go to Application Tab -> Cookies -> Click on your site link. on left hand side look for something that represent your session id, may be JSESSIONID or similar, copy that. Now open your Internet Explorer, hit F-12 and manually create that JSESSIONID by running this command in console window
document.cookie = "JSESSIONID=<your-session-id-from-chrome"
hit play button to execute script
Refresh your browser

Writing to Command Line Not Working

An application I need to use (USB capture utility) has a .cmd version that I can call from my Visual Basic code. I am able to launch the application and put it in "command line mode" like this:
Public Class MyClass
Dim StreamWriteUtility As System.IO.StreamWriter
Dim StreamReadUtility As System.IO.StringReader
Dim ProcessInfo As ProcessStartInfo
Dim Process As Process
Public Sub StartUSBCapture(ByVal DataStorageLocation As String)
Dim ProcessInfo As ProcessStartInfo
Dim Process As New Process
ProcessInfo = New ProcessStartInfo("C:\FW_Qualification_Suite\data-center-windows\data-center\bin\datacenter.cmd", "-c ")
ProcessInfo.CreateNoWindow = True
ProcessInfo.UseShellExecute = False 'Must be changed if redirect set to True
ProcessInfo.RedirectStandardInput = True
Process = Process.Start(ProcessInfo)
SWUtility = Process.StandardInput
While True
SWUtility.WriteLine("run") 'Looping for test to ensure this isn't a timing issue
End While
End Sub
End Class
This launches the application and opens a separate command line window that should accept further commands (i.e., capture, run, stop, etc). However, I am having trouble getting those subsequent commands to show up in the command line window. I've tried redirecting the standard input of the process, but still nothing shows up in the console window.
Can anyone tell how I'm supposed to actually get these commands from my Visual Basic program into this application?

How to stop a DataGridView removing columns on subsequent form loads? [duplicate]

I have a custom form which is open as Form.ShowDialog()
This form acts as a confirmation form. It asks a question whether you want to accept or decline the previously entered input in ComboBox & TextBox.
If you click OK, the input is saved into Excel File.
If you click Cancel, the input is not saved.
The problem I am having is that:
When you click cancel. The form.ShowDialog() is closed. (Which is fine.)
But when the form.ShowDialog() is open again. It retains the focus on the Cancel Button. So if you try to confirm the entry with "Enter" key, you cancel it instead.
My question is. Why does the Form.ShowDialog() retain the focus on the buttons after closing?
The Form.ShowDialog() has accept button "OK" [tabindex = 1], and cancel button "Cancel" [tabindex = 2] which are set to Enter key, and Esc key.
(To note again)The focus of the buttons remains after closing the form.
The portion of the code using the Dialog:
ElseIf ComboBoxBP.SelectedItem = ComboBoxBP.SelectedItem And TextBoxBP.Text = TextBoxBP.Text Then
form.Label1.Text = ComboBoxBP.SelectedItem
form.Label2.Text = TextBoxBP.Text
form.ShowDialog()
If form.DialogResult = Windows.Forms.DialogResult.Yes Then
SiE()
ElseIf form.DialogResult = Windows.Forms.DialogResult.No Then
LabelBPBot.Text = "Canceled."
End If
End If
When you use .ShowDialog() closing the form does not dispose of it as with a normal form. This is because once a Dialog "closes" it actually just hides so we can get info from it before it actually goes away.
The second issue is that forms are classes (it says so at the top of every one of them:)
Public Class Form1
...
So, instances of them should be created. VB allows Form1.Show or Form1.ShowDialog() to use a "default instance" and it is a shame that it does.
Combine these 2 tidbits and what you have is a case where the form you showed last time is still around in the same state as when you last used it, including the last focused control. You are only using a "fresh copy" of the form the first time, after that, you are just reusing the old instance. Remedy:
Using Dlg As New Form1 ' form1 is the class, dlg is the instance
... do stuff
Dim res As DialogResult = Dlg.ShowDialog()
If res = Windows.Forms.DialogResult.OK Then
'... do stuff
End If
End Using ' dispose of Dlg
Eventually, you will run into similar issues using the default instance of the other forms (LForm.Show). Just Say No to Default Form instances.

Have Windows Authentication use default login page instead of popup dialog in Sharepoint 2010

Is there a way to have simple windows authentication for a public facing site (anonymous viewing is enabled so as to view the login page) but insatead of it popping up the windows auth dialog, to use a login page (aspx). I saw something similar when i switched to mixed mode authentication. SharePoint has a dropdown with "windows authentication" or "forms authentication". What i need is something similar, but just the "windows authentication" option.
I've seen similar questions on SO, but they all involve creating a custom login page. The ideal solution would involve no new pages and no coding.
Is this possible?
This could be done by launching the sharepoint page's address in internet explorer, and using some pinvoke api to send keys or settext to the login box.
I fanagled this setup for a vb.net forms application. It works on my XP. I haven't tried it in Windows 7 yet, but I'm sure it needs some adjustment for it to work there.
This uses a library called WindowScraper, from here: http://www.programmersheaven.com/download/56171/download.aspx
This library has a bunch of winapi and pinvoke built in. If your assembly won't allow it (because you are using VS 2010, perhaps), saying it doesn't have a strong name, then use SharpDevelop and rebuild the solution after adding your own certificate.
Then put the dll in your application directory and add a reference.
Then add the imports:
Imports WindowScrape
Imports WindowScrape.Constants
Imports WindowScrape.Types
Finally, the code (put all this in a module or class):
Private Property PortalAddress As String = "http://myportal#somewhere.com"
Private Property logintitle As String = "Connect to myportal#somewhere.com"
Public Sub openPortal()
If My.Computer.Info.OSFullName = "Microsoft Windows XP Professional" then
LoginToPortalXP()
Else
msgbox("Someday, we will be able to log you in automatically" & vbCr & "But it isn't ready yet.")
End If
End Sub
Private Function IsWindowReady(Optional ByVal timeout As integer = 10000)
Dim isready As Boolean = false
Dim timer As Integer = 1000
Do Until Not loginBox is nothing or timer = timeout
Thread.Sleep(1000)
loginbox = HwndObject.GetWindowByTitle(logintitle)
timer = timer + 1000
loop
If Not loginbox is nothing then isready = true
Return isready
End Function
Sub LoginToPortalXP()
Try
Dim TheBrowser As Object = CreateObject("InternetExplorer.Application")
TheBrowser.Visible = True
TheBrowser.Navigate(PortalAddress)
If Not IsWindowReady then debug.print("failed") : Exit sub
Dim sys As HwndObject = loginbox.GetChildren(1) 'SysCredential
sys.GetChildren(1).Text = "myUserName" 'username box
Thread.Sleep(500)
sys.GetChildren(4).Text = "myPassword" 'password box
Thread.Sleep(500)
loginbox.GetChildren(2).Click() 'push the okay button
Catch ex As Exception
msgbox("ERROR AutoLogging into Portal: " & vbcr & & ex.Message)
Finally
End Try
End Sub
I added the timer just in case it takes longer. You can change the timeout, of course.