Access denied error message when creating multipart zip archive using DotNetZip - zip

Example code:
Using Zip As ZipFile = New ZipFile()
Zip.AddFile("E:\Projects\HOPS\HOPS v1.56\Website\Photos\Pubs.zip")
Zip.MaxOutputSegmentSize = 20 * 1024 * 1024
Zip.TempFileFolder = "E:\Temp\Photos\Temp"
Zip.Save("E:\Temp\Photos\Archive.zip")
End Using
Generates the following error message:
Access to the path is denied.
Comment out the Zip.MaxOutputSegmentSize line and the code works generating a single zip file. When it fails, it has managed to create the file .z01 file. I don't think it's a permissions problems on the target folder because I've given "Everyone" full access to try and get it working plus it's able to create it when not attempting to break into 20MB chunks.
The full error message is this:
[UnauthorizedAccessException: Access to the path is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
+10556971 System.IO.File.Move(String sourceFileName, String destFileName) +351
Ionic.Zip.ZipSegmentedStream.TruncateBackward(UInt32 diskNumber, Int64
offset) +694 Ionic.Zip.ZipEntry.Write(Stream s) +1302
Ionic.Zip.ZipFile.Save() +1162 Ionic.Zip.ZipFile.Save(String
fileName) +366 PhotoImport.Page_Load(Object sender, EventArgs e) in
E:\Projects\HOPS\HOPS v1.56\Website\Pubs\PhotoImport.aspx.vb:48
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+2428
Later - bit more information from Process Monitor:
w3wp.exe CreateFile C:\Windows\System32\inetsrv ACCESS DENIED
Hmm, why is it trying to write to that folder?

Related

Write into file from assets folder uwp

I'd like to write text content into a file that is located Assets folder, so I access file but I don't have access to write into it, my code is:
try {
//get the file
StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/test.txt"));
//try to write sring to it
await FileIO.WriteTextAsync(storageFile, "my string");
} catch (Exception ex) {
Debug.WriteLine("error: " + ex);
}
and I get the error:
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
error: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at MyProject.MainPage.<overWriteHtmlSrcFile>d__6.MoveNext()
Have to mention that I need to change this file due app scenario, or maybe is there a way to create this file in public app folder and then move it in assets.
Files located into Assets folder are read only that's why you get this exception. Like you mentioned at the end, there is a method to create your file in a public location, write what you need into it and then just move the file in assets folder. It will be like:
try {
//create file in public folder
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
//write sring to created file
await FileIO.WriteTextAsync(sampleFile, htmlSrc);
//get asets folder
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");
//move file from public folder to assets
await sampleFile.MoveAsync(assetsFolder, "new_file_name.txt", NameCollisionOption.ReplaceExisting);
} catch (Exception ex) {
Debug.WriteLine("error: " + ex);
}

Accessing the file share from Azure Worker Role

We want migrate our FTP servers in Windows Azure. We created clean virtual machine image and installed FTP Server there. Now, to be able to process the files resided in the FTP directory ,directly from Windows Azure data center, we created the file share and endpoints (port 445 TCP and UDP). If we are trying to access the FTP Server's file share from the Worker Role we are getting usually 'Access to the path '...' is denied.'. We are able to access the FTP Server's file share over the remote desktop from the Worker Role, what mean the Firewall and FTP configuration are correct. Can a worker role access the file shares in the Windows Azure data center?
The code:
try
{
const string networkShare = #"...";
Directory.GetFiles(networkShare).ToList().ForEach(file => Trace.TraceInformation(file));
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
The exception:
Exception thrown on running: System.UnauthorizedAccessException: Access to the path '...' is denied.
Server stack trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.CommonInit()
at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption, Boolean checkHost)
at System.IO.Directory.InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
at KALCIK.NET.Plugin.ReadFromShare.ReadFromSharePlugin.Manipulate(String valueToManipulate)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at KALCIK.NET.Plugin.Contracts.TextManipulationPluginBase.Manipulate(String valueToManipulate)
at KALCIK.NET.CloudServices.WorkerRole.BusinessLayers.WorkOrderProcessing.ProcessWorkOrder(Tuple`2 workOrder) in c:\Development\Samples\CloudServicesPlugInSample\CloudServices.WorkerRole\BusinessLayers\WorkOrderProcessing.cs:line 56
at KALCIK.NET.CloudServices.WorkerRole.WorkOrderProcessorService.Run() in c:\Development\Samples\CloudServicesPlugInSample\CloudServices.WorkerRole\WorkOrderProcessorService.cs:line 67; TraceSource 'WaWorkerHost.exe' event
Yes the problem seems to be the user, under the host process is running. To resolve this issue you can create the new user with the administrator privileges (for example with the help of start up task, when the role is starting) and impersonate the executed code. You can see the sample implementation here.
public class WorkerRole : RoleEntryPoint
{
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle() : base(true) { }
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.WriteLine("TestWorkerRole entry point called", "Information");
while (true)
{
try
{
SafeTokenHandle safeTokenHandle;
var returnValue = LogonUser("username", Environment.MachineName, "password", 2, 0, out safeTokenHandle);
if (returnValue)
{
using (safeTokenHandle)
{
using (var impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
const string networkSharePath = #"UNCPath";
Directory.GetFiles(networkSharePath).ToList().ForEach(file => Trace.TraceInformation(file));
}
}
}
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
}
}
}
I think it's a security issue: the user (under which the Working Role runs) is not able to authenticate on the network share. Try a "net use" before your Directory.GetFiles
"net use" from C# : Access a Remote Directory from C#

Check If File Exists, Download and Save File in J2ME

I want to edit my question.
If file still not exist, download and save it, that my case.
To check if file exist, I've try by this code
private boolean isXmlFileExist(){
try{
FileConnection fCon = (FileConnection) Connector.open("file:///"+Resource.XML_PATH + "/" + Resource.XML_FILENAME, Connector.READ);
return fCon.exists();
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
In my resource class
public static final String XML_PATH = "/xml";
public static final String XML_FILENAME = "template.xml";
I have create 'xml' folder under res folder and i have put file 'template.xml' there. But this code always return false.
Whether we can not use the res folder? So, what is the correct path.
Files under res folder are always available because they are packaged with the class files. So, you do not need to check with FileConnection if they exist.
To access these files you can use Class.getResourceAsStream.
For example:
private InputStream open (String fileName) {
return getClass().getResourceAsStream(fileName);
}
// call it like this
open(Resource.XML_PATH + "/" + Resource.XML_FILENAME);

XNA graphicsdevice.present crashes on "value does not fall within the expected range"

I have an XNA application, that when run on a certain laptop (dell, Win 7 64bit) will crash.
Sometimes it crashes after a few minutes, sometimes it takes many hours, but it always crashes eventually.
The application is written in XNA4.0 VS2010
I had to add an event to AppDomain.CurrentDomain.UnhandledException just to catch this exception,
here is the stack trace :
System.ArgumentException: Value does not fall within the expected range.
at Microsoft.Xna.Framework.Graphics.GraphicsDevice.Present(tagRECT* pSource, tagRECT* pDest, HWND__* hOverride)
at Microsoft.Xna.Framework.GraphicsDeviceManager.Microsoft.Xna.Framework.IGraphicsDeviceManager.EndDraw()
at Microsoft.Xna.Framework.Game.EndDraw()
at Microsoft.Xna.Framework.Game.DrawFrame()
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.Game.HostIdle(Object sender, EventArgs e)
at Microsoft.Xna.Framework.GameHost.OnIdle()
at Microsoft.Xna.Framework.WindowsGameHost.RunOneFrame()
at Microsoft.Xna.Framework.WindowsGameHost.ApplicationIdle(Object sender, EventArgs e)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Microsoft.Xna.Framework.WindowsGameHost.Run()
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at Moof.Moof.Run()
at Moof.Program.Main(String[] args)
Any ideas ?
Thanks.
Try updating your graphics drivers, links below.
Intel: http://downloadcenter.intel.com/
AMD/ATI: http://support.amd.com/us/gpudownload/Pages/index.aspx
NVIDIA: http://www.nvidia.com/Download/index.aspx?lang=en-us

'Activate feature' step error :Object Reference not set to an instance of an object

I created a custom timer job and implemented it through a feature event in sharepoint.
when i tried to activate it, its showing this particular error:
Object reference not set to an instance of an object. at TimerJobExample.MyFeatureReceiver.FeatureActivated(SPFeatureReceiverProperties properties) in C:\Documents and Settings\admin-shuklag.INFRADEV\My Documents\Visual Studio 2008\Projects\TimerJobExample\TimerJobExample\MyFeatureReceiver.cs:line 22
at Microsoft.SharePoint.SPFeature.DoActivationCallout(Boolean fActivate, Boolean fForce)
at Microsoft.SharePoint.SPFeature.Activate(SPSite siteParent, SPWeb webParent, SPFeaturePropertyCollection props, Boolean fForce)
at Microsoft.SharePoint.SPFeatureCollection.AddInternal(Guid featureId, SPFeaturePropertyCollection properties, Boolean force, Boolean fMarkOnly)
at Microsoft.SharePoint.SPFeatureCollection.Add(Guid featureId)
at Microsoft.SharePoint.WebControls.FeatureActivator.BtnActivateFeature_Click(Object objSender, EventArgs evtargs)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
The error line is highlighted below
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
// make sure the job isn't already registered
//error line
**foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)**
{
if (job.Name == List_JOB_NAME)
job.Delete();
}
SampleTimer listLoggerJob = new SampleTimer(List_JOB_NAME, site.WebApplication);
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 5;
listLoggerJob.Schedule = schedule;
listLoggerJob.Update();
}
what could be the problem?
Based on your feature receiver, I can see only two possibilities:
Double check that the Scope attribute in feature.xml is set to Site. If it is set to Web, you will get an Object Reference not set exception when trying to use your site variable.
As Janis said, look inside the MyCustomJob constructor. Make sure that all variables are properly initialized.
The problem was with the scope of the feature. It was set to Web, and for a feature to be activated at this level, u need an admin account or an account with elevated privileges.
You can either add the application pool id to farm admin accounts or
run the code with elevated rights.

Resources