I have tried a diverse amount of methods this is my latest method which I have tried to not fire the error but to no avail I still get the FileIOPermission error
The Full error is
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
The code I am using is the below
Dim permissions As New Security.PermissionSet(Security.Permissions.PermissionState.None)
permissions.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Execution))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Assertion))
permissions.Assert()
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)
Dim asm As Reflection.Assembly = Reflection.Assembly.Load("ReportingServiceUtils, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cca1b177d76f2036")
Dim asm_name As Reflection.AssemblyName = asm.GetName()
ReportViewer1.LocalReport.AddFullTrustModuleInSandboxAppDomain(New Security.Policy.StrongName(New Security.Permissions.StrongNamePublicKeyBlob(asm_name.GetPublicKeyToken()), asm_name.Name, asm_name.Version))
The Code being used in the dll is the below
Public Sub Add(ByVal group As String, ByVal groupCurrentPageNumber As String)
Try
If _GroupWithRunningMaxPageNumber.ContainsKey(group) Then
_GroupWithRunningMaxPageNumber(group) = groupCurrentPageNumber
Else
If _GroupWithRunningMaxPageNumber.Count = 0 Then
Dim fileName = "C:\Working Folder\ms-dot-net-report-viewer-group-pagenation\ReportingServiceUtils\test.xml"
sw = New System.IO.StreamWriter(fileName, False)
sw.WriteLine("<root>")
sw.WriteLine("</root>")
sw.Close()
sw.Dispose()
End If
_GroupWithRunningMaxPageNumber.Add(group, groupCurrentPageNumber)
sw.WriteLine("<Group current='" & group & "' lastPage='" & CStr(groupCurrentPageNumber) & "'/>", 1, 1)
sw.Close()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Does anyone see anything wrong with the below code
I have found the solution and it was quite funny when I did.
The below 1 liner solves the problem of not being able to have file access from report.
Dim auth As New System.Security.Permissions.FileIOPermission( System.Security.Permissions.PermissionState.Unrestricted)
Using PermissionSet
var sec = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(sec);
You can convert from C# to VB.net easyly
Related
I'v seen a lot of answers here on stackoverflow, but none of them help me with exactly what i need and almost all of them in C# when i need VB, so i hope someone will help me with my problem, which is this :
I have compiled a exe file in vb.net using CodeDOM, and i added two dll file to its resources and that worked just fine and you can even notice that the size of the exe has increase after adding the resources, but when i run the exe file like that My.Resources.Touchless, it gives me an error saying that
"Resources" is not a member of "My".
And what i need is to read these dll files from the compiled exe file and then extract them using File.WriteAllBytes()..., if i didn't try to extract the files from the resources and instead of that i copied them manually to the executable path, the application will work perfectly, so the problem is just with trying to call the dll files from the resources.
Here is some code :
Public Shared Function Compile(ByVal Output As String, ByVal Source As String, ByVal Icon As String, ByVal resources As String) As Boolean
Dim Parameters As New CompilerParameters()
Dim cResults As CompilerResults = Nothing
Dim Compiler As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
Parameters.GenerateExecutable = True
Parameters.TreatWarningsAsErrors = False
Parameters.OutputAssembly = Output
Parameters.MainClass = "MyNamespace.MainWindow"
Parameters.EmbeddedResources.Add(Path.GetTempPath & "TouchlessLib.dll")
Parameters.EmbeddedResources.Add(Path.GetTempPath & "WebCamLib.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", Path.GetTempPath & "TouchlessLib.dll"})
Parameters.CompilerOptions = "/platform:x86 /target:winexe"
If Not String.IsNullOrEmpty(Icon) Then
File.Copy(Icon, "icon.ico")
Parameters.CompilerOptions += " /win32icon:" & "icon.ico"
End If
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source)
If cResults.Errors.Count > 0 Then
For Each compile_error As CompilerError In cResults.Errors
Dim [error] As CompilerError = compile_error
Console.Beep()
MsgBox("Error: " & [error].ErrorText & vbCr & vbLf & [error].Line)
Next
Return False
End If
If Not (String.IsNullOrEmpty(Icon)) Then
File.Delete("icon.ico")
End If
Return True
End Function
When i call them from the compiled exe file like this :
File.WriteAllBytes(Application.StartupPath & "\TouchlessLib.dll", My.Resources.TouchlessLib)
File.WriteAllBytes(Application.StartupPath & "\WebCamLib.dll", My.Resources.WebCamLib)
... i get the following error message :
"Resources" is not a member of "My".
Try adding this class:
Imports System.Dynamic
Imports System.Reflection
Public Class DynamicResources
Inherits DynamicObject
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim name As String = IO.Path.GetFileNameWithoutExtension(s)
Dim Manager As New Resources.ResourceManager(name, asm)
Try
Dim resource = Manager.GetObject(binder.Name)
If Not resource Is Nothing Then
result = resource
Return True
End If
Catch ex As Exception
End Try
Next
Return False
End Function
End Class
You can use it like this:
Dim root as string=Application.StartupPath
File.WriteAllBytes(Path.Combine(root, "TouchlessLib.dll"), DynamicResources.TouchlessLib)
File.WriteAllBytes(Path.Combine(root, "WebCamLib.dll"), DynamicResources.WebCamLib)
The My namespace and any associated functionality is created via auto-generated code. Since your code is now the code generator and not the IDE, you will not have those niceties unless your code provides it.
To extract an embedded resource, you need to include code similar to the following in the source code you are compiling with CodeDOM.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim fi As New FileInfo(s)
Using strm As Stream = asm.GetManifestResourceStream(s)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
Next
Make sure that you also include:
Imports System.Reflection
Imports System.IO
This code retrieves the executing Assembly obtains an array of embedded resource names. It then calls GetManifestResourceStream method to get the named resource as a stream. This stream is copied to a file stream.
Modify the example to suite your needs.
Note that I have not included any error checking/handling in this example. Anything dealing with IO should have some error handling.
Edit:
Based on the comment below, it appears that only a copy/paste type answer will do for the OP.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName As String
Dim fi As FileInfo
resourceName = "TouchlessLib.dll"
fi = New FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, resourceName))
Using strm As Stream = asm.GetManifestResourceStream(resourceName)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
I'm trying to upload a file to dropbox. The file gets uploaded and code works when i'm running locally. But file never gets uploaded when published on the server. I'm having the following error .
Could not load type 'System.Security.Authentication.SslProtocols' from assembly 'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*********'.
I'm trying the below code sample to upload it
public sub uploadtodropbox()
Using httpclient As New HttpClient
httpclient.Timeout = TimeSpan.FromMinutes(20)
Dim _DropboxClient = New DropboxClient(ApiKeyDropBox, config)
Dim resultstring As String = UploadToDB(_DropboxClient, dropboxdir, docName, fileBytes)
_DropboxClient.Dispose()
If Not resultstring = "RanToCompletion" Then
ErrorMsg &= "The following error occured: " & resultstring
End If
End Using
End Sub
and this is the funtion that is uploading to Dropbox
Private Function UploadToDB(_DropboxClient As DropboxClient, Directory As String, Filename As String, Content As [Byte]()) As String
Try
Dim result As String = "Unknown"
Dim trycnt As String = 0
Dim tryLimit As String = 20
Dim respnse As Task(Of FileMetadata)
Using _mStream = New MemoryStream(Content)
respnse = _DropboxClient.Files.UploadAsync(Convert.ToString(Directory & Convert.ToString("/")) & Filename, WriteMode.Overwrite.Instance, body:=_mStream)
While Not respnse.IsCompleted And trycnt < tryLimit
Threading.Thread.Sleep(1000)
trycnt += 1
result = respnse.Status.ToString()
End While
UploadToDB = result
End Using
End try
END function.
I have tried without using the httpclient then i am getting this error :
The type initializer for 'Dropbox.Api.DropboxRequestHandlerOptions' threw an exception.
Thank you
I go the answer . I have system.Net.primitives assembly that is creating a problem uploading the file to Dropbox. All i need to do is delete the reference and also the System.Net.Http has versions have been set wrong in the web.config file. Once i set that in the configuration everything works fine.
For the certificate I have set the on post back to validate and allow the certificates generated in the event handler.
I am using the following code to connect to Google Calendar 3.
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "101935195xxxxxx-jm6o24ifgbixxxxxxxxxxxx#developer.gserviceaccount.com".Trim()
scopes.Add("https://www.googleapis.com/auth/calendar")
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = myClientID, _ ' It is saved in the web config
.ClientSecret = ClientSecret _ ' It is saved in the web config
}
Dim flow As GoogleAuthorizationCodeFlow
Try
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes
})
Catch ex As Exception
lblerr.Text = ex.ToString
End Try
It throws:
System.TypeInitializationException: The type initializer for 'Google.Apis.Http.ConfigurableMessageHandler' threw an exception.
System.IO.FileLoadException: Could not load file or assembly 'System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
What am I doing wrong with this coding? Why am I not getting authenticated?
I have seen a similar error when using external libraries (e.g. DLL's) which are downloaded from the internet. Your post doesn't mention this, but I'll post here just in case this applies to you.
Make sure any external libraries used by your project are not blocked by Windows. You can do this by right-clicking the library file (e.g. the DLL) and going to Properties. At the bottom, if this applies, there will be a button to "Unblock". Click it and then try to run your project again.
Additional info and automation options can be found here: http://www.howtogeek.com/70012/what-causes-the-file-downloaded-from-the-internet-warning-and-how-can-i-easily-remove-it/
I've been using CoSign within Microsoft Word successfully, but now I'm trying to automate the report generation using Microsoft Visual Basic Studio 10 Express. Trying to download the developer's software bundle fails due to the previous client installation, but I do already see the Arx Signature API 6.20 installed on my desktop, and I can add a reference to the Interop.SAPILib.dll without a problem, through the COM tab; Intellisense recognizes all the appropriate functions, so everything seemed to be installed. However, when I build and debug the program, I am given the error 80040154 Class not registered, specifically on the first "Dim myFileHandle as New SAPILibrary.FileHandle" call. Previous calls work without error; they include creating MySAPI as a New SAPICrypt, MyHandle as a new SESHandle object, MyFieldHandle as new SAPILib.SigFieldSettings, and calls to MySAPI.init, MySAPI.HandleAquire, MySAPI.Logon. My code is below.
Other forum posts for this error cite the need for assuring x86 builds if using a 32-bit dll. I have confirmed that it is my solution's compile platform; I am using a 64-bit Toshiba running Windows 7.
Can it be a dll issue, since the other SAPILibrary class reference worked well?
Does the Arx Cosign installation not automatically register the dll, despite my being able to reference it in Visual Stuio Express? I tried to manually register the dll file, but I'm then given the error that the module was loaded but that the entry point DllRegisterServer was not found, and to check to see if this is a valid dll.
Obviously I'm new to COM dlls. Am I on the right track, or is this an unhandled error of another kind?
Private Sub SignWithSAPI()
Dim username As String = "XXX#yahoo.com"
Dim password As String = "passwordhere"
'add a signature field locator string - NEED TO HIDE THIS AS IT DOESN'T GET ERASED BY SAPI
Dim MyFieldLocatorString As String = "<<<W=200;H=120;N=Physician signature;A=&HC;>>>"
oWord.Selection.TypeText(MyFieldLocatorString)
'SIGN PDF HERE USING COSIGN Signature API
Dim mySAPI As New SAPICrypt
Dim myHandle As New SESHandle
Dim rc As Int32
rc = mySAPI.Init()
If rc <> 0 Then
MessageBox.Show("Init failed")
Exit Sub
End If
rc = mySAPI.HandleAcquire(myHandle)
If rc <> 0 Then
MessageBox.Show("failed at handleAcquire")
mySAPI.Finalize()
Exit Sub
End If
rc = mySAPI.Logon(myHandle, userName, "", password)
If rc <> 0 Then
MessageBox.Show("Login failed")
mySAPI.HandleRelease(myHandle)
mySAPI.Finalize()
Exit Sub
End If
Dim MyFieldSettings As New SAPILib.SigFieldSettings
With MyFieldSettings
.Invisible = 0
.Height = 200
.Width = 100
.AppearanceMask = myChosenAppearancesMask 'shows graphical image, name of signer and time
.SignatureType = SAPI_ENUM_SIGNATURE_TYPE.SAPI_ENUM_SIGNATURE_DIGITAL
End With
Dim myPDFfileName As String = "C:\\Users\Scott\Desktop\TestAutomation.pdf"
Dim myFileHandle As New SAPILib.FileHandle
rc = mySAPI.CreateFileHandleByName(myFileHandle, _
SAPI_ENUM_FILE_TYPE.SAPI_ENUM_FILE_ADOBE, 0, myPDFfileName)
If rc <> 0 Then
MessageBox.Show("Error in creating FileHandlebyName")
mySAPI.HandleRelease(myHandle)
mySAPI.Finalize()
Exit Sub
End If
'Assigns the SigFieldContext
Dim mySigFieldContext As New SAPIContext
Dim myNumberOfSigFields As Integer
rc = mySAPI.SignatureFieldEnumInitEx(myHandle, mySigFieldContext, _
SAPI_ENUM_FILE_TYPE.SAPI_ENUM_FILE_ADOBE, "", myFileHandle, 0, myNumberOfSigFields)
If rc <> 0 Then
MessageBox.Show("Error in SigFieldEnumInitEx")
mySAPI.HandleRelease(myFileHandle)
mySAPI.HandleRelease(myHandle)
mySAPI.Finalize()
Exit Sub
End If
Dim mySigFieldLocatorContext As New SAPIContext 'next line assigns its value in the function
rc = mySAPI.SignatureFieldLocatorEnumInit(myHandle, mySigFieldLocatorContext, _
myFileHandle, "<<<", ">>>", 0, myNumberOfSigFields)
If rc <> 0 Then
mySAPI.ContextRelease(mySigFieldContext)
MessageBox.Show("Error in SigFieldLocatorContext")
mySAPI.HandleRelease(myFileHandle)
mySAPI.HandleRelease(myHandle)
mySAPI.Finalize()
Exit Sub
End If
Dim mySigFieldHandle As New SigFieldHandle
rc = mySAPI.SignatureFieldEnumCont(myHandle, mySigFieldContext, mySigFieldHandle)
'assigns the first(only) value to mySigFieldHandle
If rc <> 0 Then
mySAPI.ContextRelease(mySigFieldLocatorContext)
mySAPI.ContextRelease(mySigFieldContext)
MessageBox.Show("Error in SigFieldLocatorContext")
mySAPI.HandleRelease(myFileHandle)
mySAPI.HandleRelease(myHandle)
mySAPI.Finalize()
Exit Sub
End If
'//Create the Field
rc = mySAPI.SignatureFieldSignEx(myHandle, mySigFieldHandle, myChosenAppearancesMask, _
Nothing)
If rc <> 0 Then
MessageBox.Show("Error in sigfieldSignEx")
End If
'release resources
mySAPI.HandleRelease(mySigFieldHandle)
mySAPI.HandleRelease(myFileHandle)
mySAPI.ContextRelease(mySigFieldContext)
mySAPI.ContextRelease(mySigFieldLocatorContext)
mySAPI.Logoff(myHandle)
mySAPI.HandleRelease(myHandle)
End Sub
Thanks!
The FileHandle object can be created using either CreateFileHandleByName or CreateFileHandleByMem functions and this is the proper way to instantiate the object in our COM. Replacing the line Dim myFileHandle As New SAPILib.FileHandle with Dim myFileHandle As SAPILib.FileHandle = Nothing will solve your issue.
I'm developing an application as a windows service. The service retrieves a path from app.config, but for some reason part of the retrieved path is changing during the execution and replaced with C:\Windows\System32.
This is my app.config
[...]
<appSettings>
<add key="Freq_Minutes" value="1" />
<add key="Connectionstring" value="Server=FENIX\SQL2005;Database=amoselprat;Uid=amos;Pwd=mosa;"/>
<add key="AMOSEsdara_Path" value="C:\TEMP\AMOS_ESDARA"/>
<add key="EsdaraAMOS_Path" value="C:\TEMP\ESDARA_AMOS"/>
</appSettings >
[...]
This is the function that retrieves the key
Public Function GetInfo(ByVal Label As String) As String
Dim Value As String
Try
Value = System.Configuration.ConfigurationManager.AppSettings(Label).ToString
Catch ex As Exception
Value = Nothing
End Try
Return Value
End Function
And this is troubled code
Public Sub Components(ByVal AutoNumber As String)
Dim sw As StreamWriter
Dim File As String
File = GetInfo("AMOSEsdara_Path") & "\AMOS_ESDA_COMP_" & Autonumber & ".xml"
Try
EventLog_AMOSEsdara.WriteEntry("AMOSEsdara Interface - Creating components file " & File)
sw = File.CreateText(File)
[...]
Catch Ex As Exception
EventLog_AMOSEsdara.WriteEntry("AMOSEsdara Interface - Error creating file " & File & " Error: " & Ex.Message)
End Try
End Sub
Running as a service EventLog is writting the below error:
AMOSEsdara Interface - Error creating file AMOS_ESDARA\AMOS_ESDA_COMP_000006.xml Error: Can not find a part of the path 'C:\Windows\system32\AMOS_ESDARA\AMOS_ESDA_COMP_000006.xml'.
I tried to use the same code into a Console Application instead Service Application and it is working fine. The retrieved path is correct and the XML file is created successfully at C:\TEMP\AMOS_ESDARA
What I'm missing? Thanks in advance.
Solved.
Public Function GetInfo(ByVal Label As String) As String
Dim Value As String
System.IO.Directory.SetCurrentDirectory((System.AppDomain.CurrentDomain.BaseDirectory))
Try
Value = System.Configuration.ConfigurationManager.AppSettings(Label).ToString
Catch ex As Exception
Value = Nothing
End Try
Return Value
End Function