Downloading files in Visual Studio - vb.net

I am using the code recommended by Microsoft.
My.Computer.Network.DownloadFile("mydlurl", "C:\jb\jb.exe")
But that throws an unhandled exception on my friends computer, and some other people, but some can use it.
I tried using downloadasync with a progress bar, but it freezes before it even starts.(Does nothing)
Here is my code that runs an unhandled exception on some computers.
If My.Computer.FileSystem.FileExists("C:\jb\jb.exe") Then
Else
'jbinfo.Text = "Please wait as your file is being downloaded."
My.Computer.Network.DownloadFile("http://download1580.mediafire.com/g/abcdefghijklmnop/myfile.exe", "C:\jb\jb.exe", "", "", True, 500, True) '<Maybe fix. Lets try.
End If
The exception message is:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.Net.WebException: The server committed a protocol violation. Section=ResponseStatusLine
at Microsoft.VisualBasic.MyServices.Internal.WebClientCopy.DownloadFile(Uri address, String destinationFileName)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(Uri address, String destinationFileName, ICredentials networkCredentials, Boolean showUI, Int32 connectionTimeout, Boolean overwrite, UICancelOption onUserCancel)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(String address, String destinationFileName, String userName, String password, Boolean showUI, Int32 connectionTimeout, Boolean overwrite, UICancelOption onUserCancel)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(String address, String destinationFileName, String userName, String password, Boolean showUI, Int32 connectionTimeout, Boolean overwrite)
at MyApp.Main.Button1_Click_1(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

If I run this I get a ProtocolViolation, this is probably because DownloadFile expects a 200 OK, followed by the download, but Mediafire is sending you a 302 FOUND instead and redirects the request to a new location where the download page for this download is.
This is to prevent you from using MediaFire as a file hosting platform to distribute files without people actually knowing you're using MediaFire (makes sense right?).
You won't be able to use wc.DownloadFile or any other .NET framework method that expects a file here. You'll need to actually implement the proper 'handshake' with Mediafire so to speak, so they send you a new location, then go there and show that to the users.

Related

ASP.NET Generic Runtime Error when opening a PDF in new tab - Stopped working

I am hosting my site with Windows Server 2012 running IIS8. The code is written in VB.NET.
Up until yesterday, my pages would open PDF's in a new tab for viewing (not download) after a link button is clicked. The link button would work only if the associated file exists in the database.
If (myreader(49) = "" And myreader(52).ToString() = "0") Then
lnkAttachment.Text = "N/A"
lnkAttachment.Enabled = False
Else
lnkAttachment.Text = "Click Here"
lnkAttachment.Enabled = True
Once the button is clicked it would open the PDF in a new tab. It stopped working and now shows a generic Runtime Error.
The code that generates the link to this page is:
Protected Sub lnkAttachment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkAttachment.Click
Dim wdwOpen As String = "window.open('" & "../Attachment/" & Session("ID") & ".pdf" & "','_blank');"
Response.Write("<script>")
Response.Write(wdwOpen)
Response.Write("</script>")
End Sub
I have the web.config file and IIS Error Page Settings supposed to be showing detailed error information:
<system.web>
<customErrors mode="Off"/>
</system.web>
I have multiple applications setup under this IIS site. The one with the problem (WO) is the only one I cannot open PDF's in. I have another application under this site that has no issues displaying the PDF file. I want to say this is an IIS issue but I cannot pinpoint what the error is.
I have gone into the C:\inetpub\logs\LogFiles\W3SVC1 file and found this line:
2016-07-20 13:29:22 (server ip address) GET /WO/Attachment/40147.pdf - 443 - 192.168.0.2 Mozilla/5.0+(iPhone;+CPU+iPhone+OS+9_3_2+like+Mac+OS+X)+AppleWebKit/601.1.46+(KHTML,+like+Gecko)+Version/9.0+Mobile/13F69+Safari/601.1 - 500 0 0 31
It shows a 500 error but for the life of me I cannot solve this problem. I have found a plethora of information through web searches, but I cannot find one to the specific problem. How does the code work one day and then stop the next, and only for one application under a site in IIS.
Any ideas as to what can be the problem?
EDIT:
Excerpt from Event Viewer per illinoistim Comment:
Event code: 3008
Event message: A configuration error has occurred.
Event time: 7/21/2016 6:55:26 AM
Event time (UTC): 7/21/2016 11:55:26 AM
Event ID: 949451611c784e7695ead3f75ea8d6b5
Event sequence: 125
Event occurrence: 3
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1/ROOT/WO-15-131135755702094878
Trust level: Full
Application Virtual Path: /WO
Application Path: C:\inetpub\wwwroot\OHAS\WODB\
Machine name: (Machine Name)
Process information:
Process ID: 22580
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: ConfigurationErrorsException
Exception message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. (C:\inetpub\wwwroot\OHAS\WODB\attachment\web.config line 86)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Web.Configuration.RuntimeConfig.GetSectionObject(String sectionName)
at System.Web.Configuration.RuntimeConfig.GetSection(String sectionName, Type type, ResultsIndex index)
at System.Web.Configuration.RuntimeConfig.get_Identity()
at System.Web.HttpContext.SetImpersonationEnabled()
at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
Request information:
Request URL: (site URL)
Request path: /WO/attachment/40147.pdf
User host address: 192.168.20.1
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 57
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Web.Configuration.RuntimeConfig.GetSectionObject(String sectionName)
at System.Web.Configuration.RuntimeConfig.GetSection(String sectionName, Type type, ResultsIndex index)
at System.Web.Configuration.RuntimeConfig.get_Identity()
at System.Web.HttpContext.SetImpersonationEnabled()
at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
Custom event details:
So here was the deal. Thanks to illinoistim's comments about going to the event viewer, I was able to use the content to search around.
Apparently I had inadvertently copied the web.config file from the root folder into the attachment sub folder. I was going to make changes to my web.config file so I copied it to a temp folder on my desktop in case things went sideways. I suspect that since I have a programmable mouse, and the file was still stored in the clipboard, I must have had the attachment folder selected and hit my "paste" button on the mouse. Both .config files have the tag . This tag is only allowed at the application level.

Xaml Designer not loading

today i've installed Visual Studio Community 2015 with Update 1 and when it try to load the Xaml Designer (even of a new project) it throws an exception:
An unhandled exception has occured
System.Runtime.InteropServices.COMException
The app did not start. (Exception from HRESULT: 0x8027025B)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.AppPackageNativeMethods.IApplicationActivationManager.ActivateApplication(String appUserModelId, String activationContext, ActivateOptions options, Int32& processId)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.DesignerWrtUtility.ActivateApplication(String appUserModelId, String activationContext, Object site, Boolean isRunningElevated)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.ActivateApplicationInternal(String appUserModelId, String activationContext, Object site)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateDesignerProcess(String applicationPath, String clientPort, Uri hostUri, IDictionary environmentVariables, Int32& processId, Object& processData)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, IIsolationTarget isolationTarget, String baseDirectory)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func'2 func, CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0'1.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
I had the same problem, this fixed it:
uninstall Visual Studio
uninstall all Windows SDKs/Emulators
install everything again
After that everything worked fine again.
If you're using an HP:
Delete the "Platform" environment variable in Control Panel > System > Advanced System Settings > Environment Variables [...] =HPD. (source)
If you're not using an HP, try following these steps:
Close any instance of Visual Studio
Open Visual Studio and create a new C# UWP empty project (name it whatever you want)
Run the newly created "useless" project, then close it as Visual Studio
Re-open your previous project. (source)
If you recently upgraded to the Windows 10 SDK from 10240 to 10586, then try setting the project Properties > Application > "Target version" to Windows 10 (10.0; Build 10240). (source)
Let me know if this helps!

How can I establish a secure channel for SSL/TLS from a handheld device?

I am trying to call a REST method from a handheld device (Windows CE / Compact framework) with this code:
public static HttpWebRequest SendHTTPRequestNoCredentials(string uri, HttpMethods method, string data, string contentType)
{
ExceptionLoggingService.Instance.WriteLog("Reached
fileXferREST.SendHTTPRequestNoCredentials");
WebRequest request = null;
try
{
request = WebRequest.Create(uri);
request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
request.ContentType = contentType;
((HttpWebRequest)request).Accept = contentType;
((HttpWebRequest)request).KeepAlive = false;
((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;
if (method != HttpMethods.GET && method != HttpMethods.DELETE)
{
byte[] arrData = Encoding.UTF8.GetBytes(data);
request.ContentLength = arrData.Length;
using (Stream oS = request.GetRequestStream())
{
oS.Write(arrData, 0, arrData.Length);
}
}
else
{
request.ContentLength = 0;
}
}
catch (Exception ex)
{
String msgInnerExAndStackTrace = String.Format(
"{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException,
ex.StackTrace);
ExceptionLoggingService.Instance.WriteLog(String.Format("From
FileXferREST.SendHTTPRequestNoCredentials(): {0}", msgInnerExAndStackTrace));
}
return request as HttpWebRequest;
}
The vals being passed to the method are:
uri: "https://seastore.nrbq.ad/ggr.web/api/inventory/sendXML/duckbill/platypus/INV_3_20090313214959000.xml"
HttpMethods: HttpMethods.POST
data: [ some xml ]
contentType: "application/xml"
...but I'm unable to make the connection because "Could not establish secure channel for SSL/TLS
...System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host"
So what must I do to establish a secure channel for SSL/TLS, so that the existing connection is not so rudely closed by the emotionally remote host?
Nebenbei bemerkt: I find it a bit rompecabezish that when I was catching a WebException, this code was causing the app to crash, but when I changed the catch block to a generic exception, the attempt to connect silently failed (the only way I could tell there was a problem was by looking at the log file).
To be more specific, with the WebException code in HttpWebRequest SendHTTPRequestNoCredentials()'s catch block, like so:
catch (WebException webex)
{
HttpWebResponse hwr = (HttpWebResponse)webex.Response;
HttpStatusCode hsc = hwr.StatusCode;
String webExMsgAndStatusCode = String.Format("{0} Status code == {1}", webex.Message,
hsc.ToString());
ExceptionLoggingService.Instance.WriteLog(String.Format("From
FileXferREST.SendHTTPRequestNoCredentials: {0}", webExMsgAndStatusCode));
}
...the app crashed and the log file held these post mortem notes (the dreaded NRE!):
Date: 3/13/2009 11:40:15 PM
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/13/2009 11:40:31 PM
Message: From frmMain.SendInventories: NullReferenceException; Inner Ex: ; Stack Trace: at
HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
at HHS.FileXferREST.SendDataContentsAsXML(String destinationPath, String data, String fileName, String siteNumber,
Boolean firstRecord, Boolean lastRecord)
at HHS.frmMain.SendInventories()
at HHS.frmMain.menuItemSEND_Inventories_Click(Object sender, EventArgs e)
. . .
However, with the generic Exception code in the catch block (as shown at the top of this post), the app seemed to be strolling through the park on a sunny summer Sunday morn -- no exception message or crash or sign of any wintery discontent whatsoever -- but the log file reveals this:
Date: 3/13/2009 11:54:52 PM
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/13/2009 11:54:54 PM
Message: From FileXferREST.SendHTTPRequestNoCredentials(): Could not establish secure channel for SSL/TLS; Inner Ex:
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveNoCheck(Byte[] buffer, Int32 index, Int32 request, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Connection.System.Net.ISslDataTransport.Receive(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.SslConnectionState.ClientSideHandshake()
at System.Net.SslConnectionState.PerformClientHandShake()
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
; Stack Trace: at System.Net.HttpWebRequest.finishGetRequestStream()
at System.Net.HttpWebRequest.GetRequestStream()
at HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
at HHS.FileXferREST.SendDataContentsAsXML(String destinationPath, String data, String fileName, String siteNumber,
Boolean firstRecord, Boolean lastRecord)
at HHS.frmMain.SendInventories()
at HHS.frmMain.menuItemSEND_Inventories_Click(Object sender, EventArgs e)
. . .
Notwithstanding that last interesting tidbit, what really matters is: How can I establish a secure channel for SSL/TLS from a handheld device?
UPDATE
I called the code from a "sandbox" app running on my PC and get a similar, albeit not identical, exception. This is what it caught:
Message: From SendHTTPRequestNoCredentials(): The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.; Inner Ex: System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
. . .
UPDATE 2
Based on some of the comments here, and the links that accompany them, I was thinking I needed to add this within my code:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
...in some context:
public static HttpWebRequest SendHTTPRequestNoCredentials(string uri, HttpMethods method, string data, string
contentType)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
WebRequest request = null;
try
{
request = WebRequest.Create(uri);
...but, although this is a .NET 3.5 client app, and, according to this [http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback
(v=vs.90).aspx], ServerCertificateValidationCallback is supposedly available in 3.5, "ServerCertificateValidationCallback" is not available to me (I get "cannot resolve symbol"). It seems this is in the System.Net assembly, but attempts to add a reference to System.Net to my project are futile, as there is no such assembly available via Add References on the .NET tab. The alphabetically-ordered list goes from "System.Messaging" to "System.Net.Irda"
I reckon this lack is because this is a feature-poor Compact Framework project.
Assuming this is so (Compact Framework does not contain ServerCertificateValidationCallback), what is the workaround for this scenario? How can I have my client handheld app accept the self-signed ssl certificate on the server (REST app running on a local network)?
UPDATE 3
Should I check/tick either or both of the following in Control Panel > Programs > Turn Windows features on or off > Internet Information Services > World Wide Web Service > Security:
Client Certificate Mapping Authentication
IIS Client Certificate Mapping Authentication
?
UPDATE 4
I can access ServicePoint, like so:
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
...but does this do me any good. Can I set the Certificate to something that will be the equivalent of always accepting it. IOW, what do I need here:
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
svcPoint.Certificate = ???
UPDATE 5
Even with this code:
namespace HHS
{
using System.Net;
using System.Security.Cryptography.X509Certificates;
class TrustAllCertificatesPolicy : ICertificatePolicy
{
public TrustAllCertificatesPolicy()
{
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}
}
private void frmMain_Load(object sender, EventArgs e)
{
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();
}
...I still get this:
Message: Reached FileXferREST.SendHTTPRequestNoCredentials
Date: 3/18/2009 11:41:09 PM
Message: From FileXferREST.SendHTTPRequestNoCredentials(): Could not establish secure channel for SSL/TLS; Inner Ex: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveNoCheck(Byte[] buffer, Int32 index, Int32 request, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Connection.System.Net.ISslDataTransport.Receive(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.SslConnectionState.ClientSideHandshake()
at System.Net.SslConnectionState.PerformClientHandShake()
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
; Stack Trace: at System.Net.HttpWebRequest.finishGetRequestStream()
at System.Net.HttpWebRequest.GetRequestStream()
at HHS.FileXferREST.SendHTTPRequestNoCredentials(String uri, HttpMethods method, String data, String contentType)
. . .
BTW, TrustAllCertificatesPolicy's (empty) constructor is probably moot, as it is grayed out.
The .NET Compact Framework does not have ServerCertificateValidationCallback.
What you could do is to set a CertificatePolicy class to validate the certificate.
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public TrustAllCertificatePolicy()
{
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}
...
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
See this link for more information.
Look at my answer Here
In a nutshell certificate management and security is not implemented well in CE and you will need to create your own web request object from Microsofts object. More details can be found at this link http://labs.rebex.net/HTTPS

Windows Azure Drive - Access Denied Exception

I am trying to write a test WCF service which writes image files into Azure Drive storage:
Below is the code I have written:
var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("mydrives");
container.CreateIfNotExist();
CloudPageBlob pageBlob = container.GetPageBlobReference("myvhd");
CloudDrive drive = new CloudDrive(pageBlob.Uri, storageAccount.Credentials);
try
{
drive.Create(100);
driveLetter = drive.Mount(0, DriveMountOptions.None);
var fileExtension = Path.GetExtension(file.FileName);
var fileName = string.Format("{0:10}_{1}{2}", DateTime.Now.Ticks, Guid.NewGuid(), fileExtension);
File.WriteAllBytes(driveLetter + "\\" + fileName, file.FileStream);
}
catch (CloudDriveException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
file.FileStream is the byte array that I am getting from Silverlight client.
This code works perfectly when I run it locally. I could even see the drive blobs and images uploaded using the storage emulator viewer.
But as soon as I publish it to the cloud and run it, I get the following exception:
<InnerException i:nil="true"/><Message>Access to the path 'd:\1634586886770888071_aa98357b-888d-4dde-a231-1ca5d5c73b49.jpeg' is denied.</Message><StackTrace>
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
at ProcessService.FileService.UploadDCMToDrive(FileToTransfer file) in C:\Users\Vinod\Desktop\TestAzure_Vinod\ProcessService\FileService.svc.cs:line 68
at SyncInvokeUploadDCMToDrive(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.UnauthorizedAccessException</Type>
I tried starting the application with elevated permissions (as per this) but I still get the same error. Can anyone shed some light on this please?
UPDATE: I created a folder using the below code:
DirectoryInfo di = new DirectoryInfo(driveLetter + "\\images");
if (!di.Exists)
di.Create();
Now I am getting this error:
Could not find a part of the path 'd:\images\test.jpeg
It's really weird :-(

Getting file permission on read while using MMF

I have two processes. One writing in a memory mapped file using .NET 4 MemoryMappedFiles and the other reading the file using FileStream in .NET 3.5 (MONO). Everything works fine when I get the permission, no problem reading or writing the file. The problem is to obtain a permission.
Writing MMF (the Writer):
MemoryMappedFile.CreateFromFile
(filenameToMap, FileMode.Create, "Something",
Marshal.SizeOf(objectToMap), MemoryMappedFileAccess.ReadWrite);
Reading MMF (the Reader):
new FileStream(filenameToMap, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
First I start the Writer, then the Reader.
I tested it using this naive approach:
while (true)
{
try
{
new FileStream(mapPath + "map.mp", FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
break;
}
catch { }
}
After roughly 10 seconds, the Reader usually gets permission and everything runs smooth. If I would catch the exception, it would throw:
IOException: Sharing violation on path
C:\path at
System.IO.FileStream..ctor
(System.String path, FileMode mode,
FileAccess access, FileShare share,
Int32 bufferSize, Boolean anonymous,
FileOptions options) [0x00000] in
:0
Any idea why these two processes don't share the file properly from beginning?