Create a virtual directory in iis 6 programatically using vb.net as unprivileged user - vb.net

I'm trying to write an application that will allow a non-administrator user to create virtual directories in IIS6. I've tried numerous different ways of impersonating a administrative account but nothing seems to work to create the virtual directory.
Here's some of what I've tried:
dim sDirPath as string = "IIS://remotehost/W3svc/1/root"
Dim de As DirectoryEntry = New DirectoryEntry()
de.Path = sDirPath
de.AuthenticationType = AuthenticationTypes.Secure
de.Username = tbxUsername.Text
de.Password = tbxPassword.Text
''Fails here
virtualId = CType(de.Invoke("Create", "IIsWebVirtualDir", dirName), DirectoryEntry)
Using the AccountAlias class from here:
aa.BeginImpersonation()
Try
dim sDirPath as string = "IIS://remotehost/W3svc/1/root"
Dim de As DirectoryEntry = New DirectoryEntry()
de.Path = sDirPath
de.AuthenticationType = AuthenticationTypes.Secure
''Fails Here
virtualId = CType(de.Invoke("Create", "IIsWebVirtualDir", dirName), DirectoryEntry)
Finally
aa.EndImpersonation()
End Try
what is the correct way to impersonate another user in winforms application that will allow me to create the virtual directory WITHOUT the user that's running the application being an administrator on the web server? I know this can be done, IIS manager allows you to use "connect as" checkbox to do it.

It's been a long time since I hit this problem so I may be remembering a few things wrong. But IIRC ...
The root directory of IIS is protected by an ACL that requires administrative privs in order to create a new directory. A simple impersonation likely will not fix this issue because I believe under the hood you are combining both COM and either RPC or Local RPC. Impersonation across COM boundaries is tricky in native code and very tricky from managed code. It's very likley that you are running into an issue in this area with your impersonation trick.
It is possible though to lift the restriction on the web server and have normal users create root directories in IIS. I outlined the process to do so in the following blog post
http://blogs.msdn.com/jaredpar/archive/2005/02/04/367137.aspx

Related

Process.start () throwing error while trying to run as administrator

I have an application developed in vb.net which needs administrator privileges. I have set level = "requireAdministrator" in the application manifest. My client wants this application to be run by a local user due to some restrictions in their organization. So I created another ‘Launcher’ application which will actually save an administrator credentials in an encrypted format and will use the saved credentials to run the ‘Original’ application.
Everything works fine if I’m using the ‘Administrator’ account (Built-in account). But if I’m using the credentials of the manually created administrator account – the process.start () line is throwing an error “The requested operation requires elevation”
I really couldn’t identify the difference between the built-in administrator and manually created administrator account. I confirmed that both the users (built-in and manually created) are members of Administrators and HomeUsers. I tried all possibilities by creating different users with different user groups and even with different OS (windows 7 and Windows 10 – both 32 and 64 bit versions) – but, all are working in the same manner as explained above. Is there anything that I have to change in my code?
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.FileName = (AppToStart)
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = True
psi.UseShellExecute = False
psi.UserName = TbUser.Text
psi.Password = ConvertToSecureString(TbPass.Text)
psi.Domain = ""
Dim p As Process = Process.Start(psi)
Additional Info: Here I'm running this 'Launcher' application as a standard user (not administrator) and the application works well and it really elevates the privileges if
TbUser.Text = “Administrator” and
TbPass.Text = 123 (Administrator password).
But this is not elevating privileges if
TbUser.Text = “Adminuser” (which is also an administrator belongs to the same ‘Administrators’ group) and
TbPass.Text = 321 (password for Adminuser).
Unfortunately you can't do this and here is why...
Basically verb isn't recognized when psi.UseShellExecute = False, this would need to be psi.UseShellExecute = True. You are doing this while trying to use runas as an elevated permission.
In your situation, you would not use the verb = runas, make sure the application has already been started with the correct permissions.
Please see more here about elevating privileges, Hans Passant say's it best...

Upload file to share point server from external application

My client has requested to upload files to his share point server from and external application. So I have designed a windows application and used Microsoft.sharepoint.dll supplied by client and used the following code for upload.
Public Function UploadFileToSharepoint(ByVal pstrSourceFilePath As String, ByVal pstrTargeSPURL As String) As Boolean
If Not File.Exists(pstrSourceFilePath) Then
Throw New ArgumentException(String.Format("{0} does not exist", pstrSourceFilePath), "srcUrl")
End If
Dim site As SPWeb = New SPSite(pstrTargeSPURL).OpenWeb()
Dim fStream As FileStream = File.OpenRead(pstrSourceFilePath)
Dim contents(CInt(fStream.Length)) As Byte
fStream.Read(contents, 0, CInt(fStream.Length))
fStream.Close()
EnsureParentFolder(site, pstrTargeSPURL)
site.Files.Add(pstrTargeSPURL, contents)
Return True
End Function
I am able to compile it but while running the application I am getting an error like "Could not load or found an assembly "Microsoft.Sharepoint.Library.dll".
My question: Is it possible to develop an application to create a folder structure and upload the file to share point server without having the share point installed on the machine but having only the share point dll's?
Suggest me a way to carry out this kind of development. In future my application will run on a machine where share point server is not installed.
Rupesh
Yes, you can do that using Client Object Model - just reference Microsoft.SharePoint.Client in your project. Here's how to do it in C#, VB.net shouldn't be much different.
ClientContext context = new ClientContext("http://mydomain");
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(#"C:\MyFile.docx");
newFile.Url = "MyFile.docx";
List docs = web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
You should look into using the SharePoint Client-Side Object model (CSOM). That will allow you to interact with SharePoint from a client.
More info here --> http://msdn.microsoft.com/en-us/library/office/ee535451(v=office.14).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

How can I change my connectionString in app.config file at runtime?

I created my vb.net project to .exe file.
During installation on another machine, one can change the location of installing package to any drive.
In my project, I have set my app.config to point the Database that is available in c:\project.
If I suppose, while installation, when I change the location of installation to **d:** or anywhere, I get invalid access db.
What I want is:
I want to reconfigure my app.config file automatically, by detecting its current db location.
Imports System.Configuration
Imports System.Configuration.ConfigurationManager
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.ConnectionStrings.ConnectionStrings("MyProject.Properties.Settings.MyProjectConString").ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\SampleDB;Persist Security Info=True;"
config.Save(ConfigurationSaveMode.Modified)
Where MyProject.Properties.Settings.MyProjectConString is the name of your project and connection string.
Although this is too late to answer as the question is very old but I think this might help someone else in the future.
So, there is a way to change the Connection String value in the runtime. Since connection string is a read-only item like all other items that are on Application Scope under My.Settings so we can't change it using My.Setting.ConnectionString = "Something". But here is the code by which you can solve the issue and change any My.Settings item that is on Application Scope in the runtime.
So the code is,
My.Settings.Item("ConnectionString") = "Something"
simple...
MsgBox(My.Settings.Item("remoteAddress").ToString)
My.Settings.Item("remoteAddress") = "abcserver.servebbs.net"
My.Settings.Save()
MsgBox(My.Settings.Item("remoteAddress").ToString)
You have three options:
1.) Create and use a folder in C:\Databse and set your connection string at design time.
2.)Add the database to the project's data source at design time, then use '|Data Directory|\mydb.mdb' as your connection string.
3.) And if you use sqlserver, you don't need to worry about the location of the database once you have attached the database to sqlserver. You only need to use the proper connection string eg 'Data Source=.; Database = mydb; Integrated Security = False; Username=myusername; Password = mypassword; User Instance = false'.
The above is an example of a sql server with SQL Authentication mode as login, if you use Windows Authentication, set Integrated Security = True and remove both username and password.

Is it necessary that Data Source of connection string must match the system name

This is my first post to this precious website. I am a new learner of vb.net. I am working on a simple purchase project, where i got some errors. But the first thing is which baffled me is:
This is my connection string at module level, on the developed machine.
Public strCn As String = "Data Source = (local); Initial Catalog = PSys; Integrated Security = false; User ID = sa; Password = 123;"
Is it mandatory that Data Source must be the original name of the System Name. I mean If i use (local) or using ( . ), so will it work or not? Because when i copy my project to any other system for further development so every time i need to change the Data source, otherwise i get the error that: "Network-related or instance-specific error occurred......."
Kindly guide me that what i need to do.
When you are developing an application which uses a database server such as MsSQL it is not wise to install the server along with your application in every pc which is installed to. For example what are you going to do if a customer has a local network with 10 computers? Are you going to install SQL server in all 10 of them? And if so what if they need to share data?
So your best approach (based on common practice by other applications) will be to allow the user to install the SQL server where he wants and let him configure your application and point it to the server's location. If you follow that path then the configuration of your application can be in the setup application or in the application itself.
Now about the development phase, I had a similar situation in which I needed to develop the same application in two different computers. What I did was to install the SQL server in both of them with a named instance "sqlexpress" then in the application I used the
Data.SqlClient.SqlConnectionStringBuilder
class to build the connection string. I did something like this:
Public Function getDevConnectionString() As String
Dim csb As New Data.SqlClient.SqlConnectionStringBuilder(My.Settings.dbConnectionString) '<-My original cs in app settings
csb.DataSource = My.Computer.Name & "\sqlexpress"
Return csb.ConnectionString
End Function
Whenever I need a connection string I simply call getDevConnectionString() which returns the connection string based on the computer name plus the sql server instance name. For example:
Dim cs As String
#If DEBUG Then
cs = getDevConnectionString()
#Else
cs = getReleaseConnectionString()
#End If
where getReleaseConnectionString() is the function that returns your connection string configured by the customer.
Hope this point you the right direction...

VBscript - How do I change anonymous authentication settings for a specific site?

I'm writing a VBscript that I would like to alter the anyonymous authentication configuration for a specific site on my web server. However, I'm unsure of how this is done in the commit path. Currently, I am able to change the setting on a global scale, but I only want to target one particular site folder. My best guess was to simply include the site path at the end of MACHINE/WEBROOT/APPHOST.
'CHANGE ANONYMOUS AUTHENTICATION GLOBALLY (working code):
Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
Set anonymousAuthenticationSection = adminManager.GetAdminSection("system.webServer/security/authentication/anonymousAuthentication", "MACHINE/WEBROOT/APPHOST")
anonymousAuthenticationSection.Properties.Item("enabled").Value = True
anonymousAuthenticationSection.Properties.Item("userName").Value = "myUser"
anonymousAuthenticationSection.Properties.Item("password").Value = "myPass"
adminManager.CommitChanges()
'MY BEST GUESS AT TARGETING A SPECIFIC SITE (returns error 80070005):
Set anonymousAuthenticationSection = adminManager.GetAdminSection("system.webServer/security/authentication/anonymousAuthentication", "MACHINE/WEBROOT/APPHOST/Sites/InsideFTL/Corp/redirects/netXposure")
The code that you have above should work, are you running it from an elevated command prompt?
You could also try to make sure that it is committing to ApplicationHost.config to make sure it is not a locking issue by setting CommitPath, and make sure that the identity under you are running the script has write access to it.
'CHANGE ANONYMOUS AUTHENTICATION For Default Web Site:
Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"
Set anonymousAuthenticationSection = adminManager.GetAdminSection("system.webServer/security/authentication/anonymousAuthentication", "MACHINE/WEBROOT/APPHOST/Default Web Site")
anonymousAuthenticationSection.Properties.Item("enabled").Value = True
anonymousAuthenticationSection.Properties.Item("userName").Value = "myUser"
anonymousAuthenticationSection.Properties.Item("password").Value = "myPass"
adminManager.CommitChanges()