Installing Windows services gives an error - vb.net

I created a simple windows service on my local PC and added the following code to it
Protected Overrides Sub OnStart(ByVal args() As String)
Const iTIME_INTERVAL As Integer = 60000 ' 60 seconds.
Dim oTimer As System.Threading.Timer
System.IO.File.AppendAllText("C:\AuthorLog.txt", _
"AuthorLogService has been started at " & Now.ToString())
Dim tDelegate As Threading.TimerCallback = AddressOf EventAction
oTimer = New System.Threading.Timer(tDelegate, Me, 0, iTIME_INTERVAL)
End Sub
Protected Overrides Sub OnStop()
End Sub
Public Sub EventAction(ByVal sender As Object)
System.IO.File.AppendAllText("C:\AuthorLog.txt", _
"AuthorLogService fires EventAction at " & Now.ToString())
End Sub
Next I added a Setup project to this solution and added a custom action (By double clicking application folder then clicking add output folder then selecting primary output from the dialog). The solution builds fine but I have 2 problems.
1) Everytime I install the service, it asks me for the username, password and confirm password; I was wondering if there was anyway to get rid of it atleast while running locally. I tried setting the account type to user, local service, local system etc but it keeps popping up.
2) Once I enter the credentials (random ones), I get an error "No mapping between account names and security ids was done".
Kindly help me out

1: You could make your service be selfinstalling as in this codeproject article and then just send in the username/password you want to use to the ServiceProcessInstaller.
2: Try entering the credentials in a different format. If you're currently using ".\user" try writing "computer\user" or vice versa.

Related

EWS Connection to Office365 fails - 401 Unauthorized

I need to make a VB .net tool to read email and save attachments. My company recently migrated from on-premise Exchange to Office 365. I have been reading EWS tutorials for 2 days now, and searching StackOverflow, but cannot get past the most basic step of authorized access to the O365 mailbox.
I took the original code from this article: htp://www.c-sharpcorner.com/UploadFile/jj12345678910/reading-email-and-attachment-from-microsoft-exchange-server/. I had some trouble converting it to VB using the Telerik converter but I think I have it right. Each time I try using the FindItemsResults method it halts with "(401) Unauthorized."
The instructions for asking a question state that I should include links to what I have already found and why it did not work, but my SO reputation only allows me 2 links. Here is what I have tried:
I have tried every possible usercode and domain combination I can think after reading this page: htps://stackoverflow.com/questions/10107872/ews-connections-issues-401-unauthorized
I am trying to read my own mailbox, so this one does not help: htps://stackoverflow.com/questions/43346498/401-unauthorized-access-when-using-ews-to-connect-to-mailbox
My connection looks identical to the connection on this page, but using it in my project did not get past the same Unauthorized error as before:htps://stackoverflow.com/questions/29009295/ews-managed-api-retrieving-e-mails-from-office365-exchange-server
Here is my code:
Public Class Form1
Public Exchange As ExchangeService
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstMsg.Clear()
lstMsg.View = View.Details
lstMsg.Columns.Add("Date", 150)
lstMsg.Columns.Add("From", 250)
lstMsg.Columns.Add("Subject", 400)
lstMsg.Columns.Add("Has Attachment", 50)
lstMsg.Columns.Add("Id", 100)
lstMsg.FullRowSelect = True
End Sub
Public Sub ConnectToExchangeServer()
Me.lblMsg.Text = "Connecting to Exchange Server"
lblMsg.Refresh()
Try
'Exchange = New ExchangeService(ExchangeVersion.Exchange2013)
Exchange = New ExchangeService()
Exchange.TraceEnabled = True
'Exchange.UseDefaultCredentials = True
Exchange.Credentials = New WebCredentials("DoeJohn", "mypasswd", "mycorp.com")
'Exchange.AutodiscoverUrl("DoeJohn#mycorp.mail.onmicrosoft.com", AddressOf MyRedirectionURLValidationCallback)
'Exchange.AutodiscoverUrl("John.Doe#mycorp.com", AddressOf MyRedirectionURLValidationCallback)
Exchange.Url = New System.Uri("https://outlook.office365.com/ews/exchange.asmx")
lblMsg.Text = "Connected to Exchange Server"
lblMsg.Refresh()
Catch ex As Exception
MsgBox("Fatal Error in Connect: " & ex.Message)
End
End Try
End Sub
Public Function MyRedirectionURLValidationCallback(RedirectionURL As String) As Boolean
Dim Result As Boolean = False
Dim RedirectionURI As Uri = New Uri(RedirectionURL)
If RedirectionURI.Scheme = "https" Then
Return True
End If
Return False
End Function
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
Call ConnectToExchangeServer()
Dim ts As TimeSpan = New TimeSpan(0, -1, 0, 0)
Dim MyDate As DateTime = DateTime.Now.Add(ts)
Dim MyFilter As SearchFilter.IsGreaterThanOrEqualTo = New SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, MyDate)
If Exchange IsNot Nothing Then
Dim FindResults As FindItemsResults(Of Item) =
Exchange.FindItems(WellKnownFolderName.Inbox, MyFilter, New ItemView(50))
Dim NewRow As ListViewItem
For Each MyItem As Item In FindResults
Dim Message As EmailMessage = EmailMessage.Bind(Exchange, MyItem.Id)
NewRow = New ListViewItem(Message.DateTimeReceived.ToString())
NewRow.SubItems.Add(Message.From.Name.ToString())
NewRow.SubItems.Add(Message.Subject)
NewRow.SubItems.Add(Message.HasAttachments.ToString())
NewRow.SubItems.Add(Message.Id.ToString())
lstMsg.Items.Add(NewRow)
Next
Else
End If
End Sub
I have confirmed that AutoDiscover is correctly finding the server, comparing to Test Email AutoConfiguration in Outlook.
AutoConfig
An interesting sidenote -- after my company moved to Office 365, I noticed that I have two new SMTP mail addresses. If I open Outlook properties on myself, I see this:
Props
This means someone can send mail to me now either at the old address john.doe#mycorp.com, and also now at doejohn#mycorp.mail.onmicrosoft.com. The new address is based on my domain usercode. I tested the microsoft one from a gmail account and it works.
To sum up, here are my questions:
1. Why am I getting the (401) Unauthorized errors when I try to read my Inbox?
2. Does Office 365 expect me to use my domain account or my mailbox name for user credentials?
3. In the domain part of the WebCredentials statement, do I use my company's mycorp.com or instead do I use Office 365's domain outlook.office365.com?
If you have read this far, many thanks!
I found the answer to the problem above, so I'll share here in case anyone needs it. The problem is down to security protocols added by my IT organization that were not documented because of recent phishing attacks on our company.
The first clue was that IT stated if I want to check company email on my personal 4G device like smartphone or ipad, I must also install Microsoft InTune for MFA connection to the O365 mail server. Since I am unaware of how to integrate InTune into my .Net app, I had to look for another answer.
I requested and was approved to move my functional mailbox from O365 to an on-premise Exchange server for this app. That solved the authentication problem.

VB.NET adding a user to distribution list. An operations error occurred

So this is what I've got -
Public Shared Function GetDirectoryEntry() As DirectoryEntry
Try
Dim entryRoot As New DirectoryEntry("LDAP://RootDSE")
Dim Domain As String = DirectCast(entryRoot.Properties("defaultNamingContext")(0), String)
Dim de As New DirectoryEntry()
de.Path = "LDAP://" & Domain
de.AuthenticationType = AuthenticationTypes.Secure
Return de
Catch
Return Nothing
End Try
End Function
Protected Sub rbAddUser_Click(sender As Object, e As EventArgs) Handles rbAddUser.Click
AddMemberToGroup("LDAP://DOMAIN.local/CN=" & !DISTRIBUTIONNAME! & ",CN=Users,DC=DOMAIN,DC=local", "/CN=" & !SELECTEDUSER! & ",CN=Users,DC=DOMAIN,DC=local")
End Sub
Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)
Dim ent As DirectoryEntry = GetDirectoryEntry()
ent.Properties("member").Add(newMember)
ent.CommitChanges()
End Sub
I hope this is easy enough for people to read, anyway the group and user are selected by the users in a table and when they click the add button I want the selected users to be adding to the selected distribution list.
when it gets to the CommitChanges() I get this error
An exception of type 'System.DirectoryServices.DirectoryServicesCOMException' occurred in System.DirectoryServices.dll but was not handled in user code Additional information: An operations error occurred.Error -2147016672
This is a common issue with the Process Model application pool configuration, from the official documentation:
By using the <processModel> element, you can configure many of the security, performance, health, and reliability features of application pools on IIS 7 and later.
This issue exists as CommitChanges() requires elevated privileges, and can be fixed by setting your web-application to run under NetworkManager; this can be done in two ways:
Directly in your code, place the problem code inside this Using statement:
Using HostingEnvironment.Impersonate()
'Problem code goes here.
End Using
Via IIS Manager:
Navigate to your website's application pool;
Navigate to Advanced Settings;
Scroll down to the Process Model group;
Change Identity to NetworkService
I solved the error by passing through my user credentials
Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)
Dim ent As New GetDirectoryEntry(bindString)
ent.Properties("member").Add(newMember)
ent.Username = "DOMAIN\USERNAME"
ent.Password = "PASSWORD"
ent.CommitChanges()
End Sub
However my code still doesn't work, I just get no errors.

VB.NET/WMI - Real-Time Windows Service Monitoring?

So there's an application at my work that installs several Windows services to a server. As a side project, I've been asked to make a simple GUI that will list these services with a "light" (a picture box with a red or green dot) next to the name of each service. The idea is that in the event these services were to stop running, the "light" would change from green to red.
I have the GUI part built, and I can query a remote server's services, then compare it to an array of the ones I'm interested and set the "light" next to each service to green/red depending on the service state. The part I'm hung up on is how to monitor these services in real time? Currently, I just have the following code in the Form_Load event:
Dim myConnectionOptions As New System.Management.ConnectionOptions
With myConnectionOptions
.Impersonation = System.Management.ImpersonationLevel.Impersonate
.Authentication = System.Management.AuthenticationLevel.Packet
End With
Try
Dim myManagementScope As System.Management.ManagementScope
myManagementScope = New System.Management.ManagementScope("\\" & SERVERNAME & "\root\cimv2", myConnectionOptions)
myManagementScope.Connect()
Dim query As New Management.ObjectQuery("SELECT * FROM Win32_Service")
Dim searcher As New Management.ManagementObjectSearcher(myManagementScope, query)
Dim i As Integer = 0
For Each queryObj As Management.ManagementObject In searcher.Get()
For Each service As String In arrServices
If queryObj("DisplayName").Equals(service) Then
If queryObj("State").Equals("Stopped") Then
arrLights(i).Image = My.Resources.redlight
End If
i += 1
End If
Next
Next
Catch err As Management.ManagementException
MessageBox.Show("WMI query failed with the following error: " & err.Message)
Catch unauthorizedErr As System.UnauthorizedAccessException
MessageBox.Show("Authentication error: " & unauthorizedErr.Message)
End Try
Would a simple timer that executes this code repeatedly be the best approach, or is there a more elegant solution? I have a little experience in VB.NET and WMI, but none in any type of real-time monitoring activity like this.
First of all i would put it into a thread, that way even if your connection times out you dont freeze your UI, then i would use a custom wait timer not the built in one as cross threading can be a pain.
wait timer:
Public Sub Wait(ByVal wait_time As Integer)
Dim time As Date
time = Now.AddMilliseconds(wait_time)
Do While time > Now
Application.DoEvents()
Loop
End Sub
example of threading:
Private services_check As Thread
private sub form1_load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
services_check = new thread(AddressOf 'Current code in a public sub')
services_cheack.IsBackground = True
Services_check.start()
It may not be the most elegant solution but its how i would do it, as for your current code im sorry i dont know enough about remote connections to help you.

Accessing Files On Server By Specifying Credentials

Our company has a share point document server where the UNC looks something like this: \\theserver.ourdomain.com\rootdirectory
Currently this drive is mapped to the Z:\ on my local computer. To access the Z:\ you have to specify (each time you login) credentials (in our case is it our username and password we logged on with) to access the folders and files in the rootdirectory.
I am in a situation where I need to copy files onto the share point server. I want to be able to copy files onto the server without using the mapped network drive (not have to specify Z:\ in the path). How can I supply credentials so that I can perform basic IO functions like GetDirectories(), GetFiles(), IO.File.Copy() etc...?
I have looked into the following things but was unsuccessful in making them work:
LogonUser API call by specifying plain text user name and password, then taking the token from that call and impersonating that user using a new instance of the WindowsIdentity class. Was able to get the token, but the impersonation didn't seem to work. Kept getting access denied errors.
CredUIPromptForCredentials/CredUIPromptForWindowsCredentials API calls, but I realize these are just for a fancy Windows UI where you can enter your credentials into and actually don't do anything.
<DllImport("advapi32.dll", SetLastError:=True)> _
Private Shared Function LogonUser(lpszUsername As String, lpszDomain As String, _
lpszPassword As String, dwLogonType As Integer, _
dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function CloseHandle(handle As IntPtr) As Boolean
End Function
'// logon types
Public Const LOGON32_LOGON_NETWORK As Integer = 3
Public Const LOGON32_LOGON_NEW_CREDENTIALS As Integer = 9
'// logon providers
Public Const LOGON32_PROVIDER_WINNT50 As Integer = 3
Public Const LOGON32_PROVIDER_WINNT40 As Integer = 2
Public Const LOGON32_PROVIDER_WINNT35 As Integer = 1
Public Const LOGON32_PROVIDER_DEFAULT As Integer = 0
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim token = IntPtr.Zero
Dim success = LogonUser("username", "domain", "password", _
LOGON32_LOGON_NEW_CREDENTIALS, _
LOGON32_PROVIDER_DEFAULT, token)
If Not success Then
Me.RaiseLastWin32Error()
End If
Using identity = New WindowsIdentity(token)
Using impersonated = identity.Impersonate()
Try
Dim info = New DirectoryInfo("\\theserver.ourdomain.com\rootdirectory\")
Dim files = info.GetDirectories()
Catch ex As Exception
Finally
impersonated.Undo()
End Try
If Not CloseHandle(token) Then
Me.RaiseLastWin32Error()
End If
End Using
End Using
End Sub
Private Sub RaiseLastWin32Error()
Dim hr = Marshal.GetLastWin32Error()
Dim ex = Marshal.GetExceptionForHR(hr)
If ex IsNot Nothing Then
Throw ex
End If
Throw New SystemException(String.Format("Call resulted in error code {0}", hr))
End Sub
This isn't a direct answer to your question as it is a wildly different approach. If it doesn't work for your situation sorry to bother, but have you considered using the SharePoint web services to load the files and retrieve information?
I suggest this approach for a few reasons:
The issue you are experiencing may be occurring because SharePoint implements WebDav which might not be 100% compatible with System.IO. I'm not an expert on the innards here, I don't know about the compatibility for sure, but it seems plausible.
The UNC location you have could easily be massaged into a URL that the web service requires.
You can set the credentials directly on the proxy and might have an easier time. (though we make these calls from another web server and so the app pool credentials in the example are good enough for us)
Here's some sanitized and simplified code just in case:
// location takes the form http://server.name.com/site/library/folder/document.ext
public string UploadDocument(string location, byte[] fileContents)
{
var result = String.empty;
var destination = new string[1];
destination[0] = location;
var fileName = Path.GetFileName(location);
var fieldInfo = new FieldInformation[0];
CopyResult[] copyResults;
_copyService.Url = "http://server.name.com/_vti_bin/Copy.asmx";
_copyService.Credentials = CredentialCache.DefaultCredentials;
_copyService.CopyIntoItems(fileName, destination, fieldInfo, fileContents, out copyResults);
var errorCode = copyResults[0].ErrorCode;
if (errorCode != CopyErrorCode.Success)
{
if (errorCode == CopyErrorCode.DestinationCheckedOut)
result = "File is currently checked out. Please try again later.";
else
result = "Error uploading content.";
}
return result;
}
_copyService is a dependency we inject where the run-time implementation is the proxy generated by Visual Studio tools from the Copy.asmx SharePoint web service.
You can also get folder contents and document metadata using the Lists.asmx web service. The biggest downsides to this approach are that querying the information requires some CAML knowledge and processing the results is not as easy. But the services are reasonably documented on MSDN and the operations are all working in our application.
Well, I was able to solve this with the help of the WNetAddConnection2 API. This API is used for mapping network drives as well, however you can call this method without specifying a drive letter so that it just adds the connection.
Say for example you had drive X: mapped to \\server\share
Lets also say that it requires username & password to access the files on the server. When you restart Windows 7, you will probably lose that connection (you will get a notification saying that Windows was unable to reconnect some of the network drives). If you have an application that requires access to that server's files and you attempt to access it without supplying your credentials you will get access denied exceptions. If you do a successful call to WNetAddConnection2, not only will it fix your unmapped network drive, you will also be able to access the files/directories via the System.IO namespace.
We use Sharepoint and this worked for me. Thanks to the other guys for replying also.

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.