Get the owner of a file in VB.NET - vb.net

I have encountered a error in VB.NET when I want to get the owner of a file.
This is my code.
Imports System.Security.AccessControl
Imports System.Security.Principal
Imports System.IO
Dim fi As FileInfo = New FileInfo("X:\Temp\aa.txt")
Dim fs As FileSecurity = fi.GetAccessControl
Dim myuser As IdentityReference = fs.GetOwner(GetType(NTAccount))
Dim username = myuser.Value.ToString
and I got error:
System.Security.Principal.IdentityNotMappedException was caught
HResult=-2146233087
Message=Unable to translate some or all of the recognition references。
Source=mscorlib
StackTrace:
System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess)
in System.Security.Principal.SecurityIdentifier.Translate(Type targetType)
in System.Security.AccessControl.ObjectSecurity.GetOwner(Type targetType)
in Ts2.From1.Button1_Click(Object sender, EventArgs e) æ–¼ D:\Ts3\Ts1\Form1.vb: row 292
InnerException:

ypu can easily get the owner of a file or folder using this ...
Public Function GetFileOwner(ByVal fileName As String) As String
Try
Dim fi As New FileInfo(fileName)
Dim fs As System.Security.AccessControl.FileSecurity = fi.GetAccessControl
Dim owner As System.Security.Principal.NTAccount = CType(fs.GetOwner(GetType(System.Security.Principal.NTAccount)), System.Security.Principal.NTAccount)
Return owner.ToString
Catch ex As Exception
Return ""
End Try
End Function
Public Function GetDirOwner(ByVal fileName As String) As String
Try
Dim di As New DirectoryInfo(fileName)
Dim ds As System.Security.AccessControl.DirectorySecurity = di.GetAccessControl
Dim owner As System.Security.Principal.NTAccount = CType(ds.GetOwner(GetType(System.Security.Principal.NTAccount)), System.Security.Principal.NTAccount)
Return owner.ToString
Catch ex As Exception
Return ""
End Try
End Function

Related

Track upload progress in Azure Blob Storage

I am building a file upload function to Microsoft Azure Blob Storage using VB.Net. Is there a way to track the progress of data transfer without using the Data Transfer Library of Microsoft? Here's my code:
Public Function isUploaded(ByVal filename As String) As Boolean
Try
Dim connectionString As String = "Connection String Here"
Dim containerName As String = "uploads"
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(connectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(Path.GetFileName(filename).ToString)
Using FileStream = System.IO.File.OpenRead(filename)
blockBlob.UploadFromStream(FileStream)
Return True
End Using
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function
If you want to know how many bytes have been uploaded, you can use the method UploadFromStreamAsync in the sdk Microsoft.Azure.Storage.Blob. It will process the class StorageProgress which holds information about the progress data transfers for both request and response streams in a single operation.
For example
Sub Main()
Dim fileName As String = "D:\\help.txt"
Dim result = isUploaded(fileName).Result
Console.WriteLine(result)
Console.ReadLine()
End Sub
Public Async Function isUploaded(ByVal filename As String) As Task(Of Boolean)
Try
Dim connectionString As String = ""
Dim containerName As String = "test"
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(connectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(Path.GetFileName(filename).ToString)
// Define the function how to handle the infromation
Dim handelr As Action(Of StorageProgress) = Sub(progress) Console.WriteLine("Progress: {0} bytes transferred", progress.BytesTransferred)
Dim progressHandler As IProgress(Of StorageProgress) = New Progress(Of StorageProgress)(handelr)
Dim cancellationToken As CancellationToken = New CancellationToken()
Using FileStream = File.OpenRead(filename)
Await blockBlob.UploadFromStreamAsync(FileStream,
New AccessCondition(),
New BlobRequestOptions(),
New OperationContext(),
progressHandler,
cancellationToken)
Return True
End Using
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function

Create an object in VB.Net to use in VBA

Firstly, I'm quite new to this so be gentle!
I am trying to create a class/object in VB.net for use in vba. I have used Gary Whitcher's code from the bottom of this post:
Sample vb.net code to upload file to Amazon S3 storage
I have created a class in Visual Studio and managed to get it to output a TLB file which i can import to VBA in Excel.
I can then use the object in VBA to create a new folder in the S3 storage system however I am running into problems when using the 'AddFileToFolder' method.
I have had to edit Gary's code a little to get it to compile in VS, the edited version is below.
Imports Amazon.S3
Imports Amazon.S3.Model
Imports Amazon
Imports Amazon.S3.Util
Imports System.Collections.ObjectModel
Imports System.IO
Public Class aws_s3
Const AWS_ACCESS_KEY As String = "AccessKey" 'is set to MY actual key
Const AWS_SECRET_KEY As String = "SecretKey" 'is set to MY actual key
Private Property s3Client As IAmazonS3
Sub New()
Try
s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USEast1)
Catch ex As Exception
End Try
End Sub
Public Function CreateFolder(bucketName As String, folderName() As String) As String
Dim returnval As String = ""
Try
Try
Dim folderKey As String = ""
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
returnval = "Bucket does not exist"
Else
For i = 0 To folderName.Length - 1
folderKey += folderName(i) & "/"
Next
' folderKey = folderKey & "/" 'end the folder name with "/"
Dim request As PutObjectRequest = New PutObjectRequest()
request.BucketName = bucketName
request.StorageClass = S3StorageClass.Standard
request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
' request.CannedACL = S3CannedACL.BucketOwnerFullControl
request.Key = folderKey
request.ContentBody = String.Empty
s3Client.PutObject(request)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval
End Function
Public Function AddFileToFolder(FileName As String, bucketName As String, folderName As String) As String
Dim returnval As String = ""
Try
Try
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
Dim fname() As String = folderName.Split("/")
CreateFolder(bucketName, fname)
Else
Dim path As String = FileName
Dim file As FileInfo = New FileInfo(path)
Dim key As String = String.Format("{0}/{1}", folderName, file.Name)
Dim por As PutObjectRequest = New PutObjectRequest()
por.BucketName = bucketName
por.StorageClass = S3StorageClass.Standard
por.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
por.CannedACL = S3CannedACL.PublicRead
por.Key = key
por.InputStream = file.OpenRead()
s3Client.PutObject(por)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval & " dll"
End Function
End Class
Using VBA, I have created the above object and can successfully execute CreateFolder but when executing addfiletofolder i get the error "Class does not support automation or does not support expected interface"
the VBA code looks like this:
Dim aws As AWS_S3
Dim Result As String
Dim UploadFile As String
UploadFile = "C:\Zipped Builds\Hinchley Legion.zip"
Set aws = New AWS_S3
Dim fld(1) As String
fld(0) = "folder"
fld(1) = "subfolder"
Result = aws.CreateFolder("nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Result = aws.AddFileToFolder(UploadFile, "nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Exit Sub
errHandle:
MsgBox Result
End Sub
I'm guessing from the fact that CreateFolder works fine but AddFileToFolder doesn't, there is a problem in the class as created in VS, missing a dependancy or something?
Thanks Anu6is, that was indeed the problem. The author of the class had wrote the following for usage which had thrown me off:
ADD FILE TO FOLDER
Dim fld(1) As String
fld(0) = <foldername>
fld(1) = <subfoldername>
'List each sub folder as an element in array
Dim rtrn As String = aws.AddFileToFolder(<local file name>,<bucketname>, fld)
I need to get better at reading VB.Net i think! Many thanks for your quick reply, much appreciated.

Adding a dynamic member to an ExpandoObject

In the following method I am trying to add a dynamic member to an expando object but it throws an exception:
public member not found for expand object
Private Sub GetAckValues()
Try
Dim ack_duration As String = String.Empty
Dim ack_by_user_fkid As String = String.Empty
Dim ack_time As String = String.Empty
ack_duration = txtdefaultack.Text
ack_by_user_fkid = Convert.ToString(Session("user_code"))
Dim Ack_Detail As Object = New ExpandoObject()
Ack_Detail.ack_duration = ack_duration
Ack_Detail.ack_by_user_fkid = ack_by_user_fkid
receiptObject.StatusObject = Ack_Detail
Catch ex As Exception
logger.Error("Enter JobRequest form done by :" & LoggedinUserId, ex)
End Try
End Sub
Should this:
Ack_Detail.ack_duration = Ack_Detail.ack_duration
actually be this:
Ack_Detail.ack_duration = ack_duration

ManagementException was Caught: Invalid class

I have the following Function intended to identify the username of the user who started a specific process:
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim user(1) As String
Try
Dim query As New SelectQuery(processName)
Dim searcher As New System.Management.ManagementObjectSearcher(query)
For Each process As ManagementObject In searcher.Get()
process.InvokeMethod("GetOwner", CType(user, Object()))
Next
Catch ex As Exception
End Try
Return user(0)
End Function
However somewhere in the ForEach initiation i'm getting this "ManagementException was Caught: Invalid class" exception thrown into my catch block. I've been in through debug but still cant work out what is. Any help would be much appreciated.
You can try it accomplishing this way
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim query = "Select * from Win32_Process Where Name = """ + processName + """"
Dim searcher = New ManagementObjectSearcher(query)
Dim processList = searcher.Get()
For Each mObj As ManagementObject In processList
Dim argList As String() = {String.Empty, String.Empty}
Dim returnVal = Convert.ToInt32(mObj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
Return argList(1) + "\\" + argList(0)
End If
Next
Return ""
End Function
This snippet works with .NET Framework 3.5 and above. For more details you may refer using-managementobjectsearcher-in-systemmanagement-is-getting-compiling-errors

How to pass complex object in restful web service

I need to pass an object (a list of structures so defined):
Private attivitaDaTrasferire As New List(Of FileDaTrasferire)
Private Structure FileDaTrasferire
Dim activityID As Integer
Dim DataIns As Date
Dim idUtenteComp As Integer
Dim idVersione As Integer
Dim idFile As Integer
Dim fileNome As String
Dim fileDestinazione As String
Dim fileTipoProdotto As String
Dim fileTipo As String
Dim fileBinarySize As Integer
Dim fileBinaryDate As String
Dim fileBinary As Long
End Structure
from a form (vb.net) to a restful web service. How can I do?
Either use JSON or XML for passing it to the restful service.
JSON on .NET
XML-Serializer
I'm using XML-Serializer. I have two functions: one client side:
Private Function SerializeActivity(singolaAttivitaDaTrasferire As List(Of FileDaTrasferire)) As String
Dim writer As New StringWriter()
Dim serializer As New XmlSerializer(GetType(List(Of FileDaTrasferire)))
Try
serializer.Serialize(writer, singolaAttivitaDaTrasferire)
Catch ex As Exception
Console.WriteLine("Eccezione " + ex.Message)
End Try
Return writer.ToString()
End Function
and one for the web-service.I get the xml file from the web service as a string and try to deserialize it with this function:
Public Function SaveDataPost(sXMLFile As String) As Boolean Implements ILiveUpdateWS.SaveDataPost
Dim reader As New StringReader(sXMLFile)
Dim serializer As New XmlSerializer(GetType(List(Of FileDaAggiornare)))
Dim myFile As List(Of FileDaAggiornare)
'Dim myFile As FileDaAggiornare
Try
myFile = serializer.Deserialize(reader)
Catch ex As Exception
Console.WriteLine("Eccezione: " + ex.Message)
End Try
Return Nothing
End Function
but on the deserialize I obtain an InvalidOperationException. (Error in the xml document)