how to change to public - vb.net

Public Sub mainlogin_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles mainlogin.Authenticate
'Are the credentials valid?
If Membership.ValidateUser(mainlogin.UserName, mainlogin.Password) Then
'Has the password expired?
Dim usrInfo As MembershipUser = Membership.GetUser(mainlogin.UserName)
Dim daysSincePwdChange As Integer = Convert.ToInt32(DateTime.Now.Subtract(usrInfo.LastPasswordChangedDate).TotalDays)
If daysSincePwdChange > SecurityUtils.DefaultPasswordExpiryInDays Then
'Password expired, send user to change password
Response.Redirect("~/ChangePassword.aspx?UserName=" & Server.UrlEncode(mainlogin.UserName))
Else
e.Authenticated = True 'Credentials valid & password is current
End If
Else
e.Authenticated = False 'Invalid!
End If
end sub
but I got this error
Error 6 'System.Web.SecurityUtils' is not accessible in this context because it is 'Friend'.

You can't - as it says, System.Web.SecurityUtils is inaccessible. You can't make it public - it's not designed to be public. Change your approach so that you don't need it.
Of course, it could be that you really want to refer to a different type... were you reading this page by any chance? My guess is that here, SecurityUtils is a different custom class, not System.Web.SecurityUtils.
All it's doing is getting a default expiry for the site though - and that's probably something you want to implement in your own way anyway. It's likely to just be a constant, or possibly something from a settings file. It's not like there's going to be a lot of logic there.

Related

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.

Basic URI (Parsing?)

I have been helped by the good people of stackoverflow many times before, so here's my problem...
I haven't been coding for a GOOD while, and for class, we are going to be starting Visual Basic. Visual Basic is really not that hard, but I am not familiar with it, and can't think of a proper way to do this.
As an exercise, I'm coding a very simple web browser. Here's my issue...
Private Sub Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Send.Click
Dim input As String = TextBox1.Text
Me.WebBrowser1.Navigate(New Uri(input))
If the user types "www.youtube.com" in the address bar, they throw an exception (I presume because there is no http:// at the beginning) However, I can't simply add "http://" to the beginning of the string, because then there is the chance for a double up.
How can I check the string for "http://" and add it accordingly?
You can use regular expression to validate the URL/URI.
Dim pattern = "http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"
Dim Inputurl = "http://www.abc.com/aa"
If Regex.IsMatch(Inputurl, pattern) Then
'
Else
'
End If
Or use String.StartsWith() method,
If Inputurl.StartsWith("http://") Then
'
End If
You need to do something like this:
Dim value As String = Mid(input, 1, 7)
if value = "http://" then
'you don't need to modifie the url
else
'you add your http:// string normaly
EndIf
Hope this can help you
PS: sory I corrected some mistakes I maid

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.

VB.NET How To Tell If New Class Instance Was Ended Early?

I'm trying to detect if the Sub New() in my class has ended early due to missing fields. Below is a sample of my code:
Class Account
Public Sub New(ByVal Firstname As String, ByVal LastName As String, ByVal Username As String, ByVal Email As String, ByVal Password As String)
' Check For Blank Fields
If Firstname = "" Or LastName = "" Or Username = "" Or Email = "" Or Password = "" Then
MessageBox.Show("Please Enter All Information Requested")
Exit Sub
End If
' Set Public Variables Of Class
Firstname = Firstname
LastName = LastName
Username = Username
Email = Email
Password = Password
End Sub
Public Shared Sub OtherUse()
End Sub
End Class
' Create New Instance
Dim Process As New Account(txtFirstName.Text, txtLastName.Text, txtUsername.Text, txtEmail.Text, txtPassword.Text)
' HERE - How Can I Catch The Early Exit From The Instance Due To Potential Missing Fields?
' Use Instance For Other Use
Process.OtherUse()
How would I catch the Exit Sub from the class in the parent form to prevent the further processing of Process.OtherUse()?
You're approaching this problem the wrong way. Validate the input first, and then once the input is valid, create a new Account using New.
Another option would be to initialize data in New without checking if it's valid or not, then have an IsValid method in that class that you would call from another class to know whether or not the messagebox should be shown.
One way or another, the Account class shouldn't be responsible for a UI concern like showing a MessageBox on the screen. And the constructor should only be responsible for constructing the object, not validating the input, because you can't "abort" a constructor. You have a reference to a new object even though you call Exit Sub.
A fourth alternative, in addition to the three mentioned by Meta-Knight:
Have the constructor throw an exception when the parameters aren’t valid.
As an aside, your use of Or, while working, is a logical error: And and Or are bitwise arithmetic operations. You want a logical operation, OrElse (there’s also AndAlso). These may seem similar to Or and And and in this particular case, both happen to work. But they are actually quite different semantically, bitwise operations are just wrong here (it’s a pity that this code even compiles. The compiler shouldn’t allow this).

Installing Windows services gives an error

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.