Search Results

Search found 474 results on 19 pages for 'filepath'.

Page 7/19 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Public class: Makes pointer from integer without cast

    - by meridimus
    I have written a class to help save and load data for the sake of persistence for my iPhone application but I have a problem with some NSUIntegers that I'm passing across. Basically, I have the code to use pointers, but eventually it has to start out being an actual value right? So I get this error warning: passing argument 1 of 'getSaveWithCampaign:andLevel:' makes pointer from integer without a cast My code is laid out like so. (Persistence is the name of the class) NSDictionary *saveData = [Persistence getSaveWithCampaign:currentCampaign andLevel:[indexPath row]]; Here's Persistence.m #import "Persistence.h" @implementation Persistence + (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:kSaveFilename]; } + (NSDictionary *)getSaveWithCampaign:(NSUInteger *)campaign andLevel:(NSUInteger *)level { NSString *filePath = [self dataFilePath]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSDictionary *saveData = [[NSDictionary alloc] initWithContentsOfFile:filePath]; NSString *campaignAndLevelKey = [self makeCampaign:campaign andLevelKey:level]; NSDictionary *campaignAndLevelData = [saveData objectForKey:campaignAndLevelKey]; [saveData release]; return campaignAndLevelData; } else { return nil; } } + (NSString *)makeCampaign:(NSUInteger *)campaign andLevelKey:(NSUInteger *)level { return [[NSString stringWithFormat:@"%d - ", campaign+1] stringByAppendingString:[NSString stringWithFormat:@"%d", level+1]]; } @end

    Read the article

  • Custom ADO.NET provider to intercept and modify sql queries.

    - by Faisal
    Our client has an application that stores blobs in database which has now grown enough to impact the performance of SQL Server. To overcome this issue, we are planning to offload all blobs to file system and leave the path of file in a new column in user table. Like if user has a table docs with columns id, name and content (blob); we would ask him to add a new column 'filepath' in this table. Our client is willing to make this change in this database. But when it comes to changing the sql queries to read and write into this table, they are not ready to accep this. Actually, they don't want any change that results in recompilation and deployment. Now we are planning to write a custom ADO.NET provider that will intercept the select queries add a column 'filepath' at the end of the select statement retieve the result set and modify the 'content' column value based on 'filepath' value Is there any use case that you think will certainly fail with this approach? I know this sounds dirty but do we have a better way?

    Read the article

  • PHP function: find argument's variable name, and function calls line number

    - by Majid
    I want to do something like this for simplifying logging operations. Any idea what I should put in for ?[1]? and ?[2]?? function log_var($var) { $line = ?[1]?; $var_name = ?[2]?; $line--; $filepath = 'log-' . date('Y-m-d'). '.txt'; $message = "$line, $var_name = $var\n"; $fp = fopen($filepath, "a"); fwrite($fp, $message); fclose($fp); @chmod($filepath, 0666); return TRUE; } This how I'd use the function in code (numbers are assumed to be line numbers in actual code): 23 $a = 'hello'; 24 log_var($a); 25 $b = 'bye'; 26 log_var($b); And this is what I want to be written to the log file: 23, a = hello 25, b = bye

    Read the article

  • Escaping an equals sign in DOS batch string replacement command

    - by Alastair
    Hi, I need to replace some text in a JNLP file using a DOS batch file to tune it for the local machine. The problem is that the search pattern contains an equals sign which is messing up the string replacement in the batch file. I want to replace the line, <j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/> with specific settings for the initial and max heap sizes. For example at the moment I have, for /f "tokens=* delims=" %%a in (%filePath%agility.jnlp) do ( set str=%%a set str=!str:initial-heap-size="100M"=initial-heap-size="%min%M"! echo !str!>>%filePath%new.jnlp) but the = in the search pattern is being read as part of the replacement command. How do I escape the equals sign so it is processed as text?

    Read the article

  • .NET Framework 4.5 remote install via PowerShell

    - by user251297
    I am trying to install .NET Framework 4.5 to the remote Win2008R2 Server via PowerShell session in such way (user is in the server Administrators group): $session = New-PSSession -ComputerName $server -Credential Get-Credential Invoke-Command -Session $session -ScriptBlock {Start-Process -FilePath "C:\temp\dotnetfx45_full_x86_x64.exe" -ArgumentList "/q /norestart" -Wait -PassThru} And then I get this error: Executable: C:\temp\dotnetfx45_full_x86_x64.exe v4.5.50709.17929 --- logging level: standard --- Successfully bound to the ClusApi.dll Error 0x80070424: Failed to open the current cluster Cluster drive map: '' Considering drive: 'C:\'... Drive 'C:\' has been selected as the largest fixed drive Directory 'C:\aa113be049433424d2d3ca\' has been selected for file extraction Extracting files to: C:\aa113be049433424d2d3ca\ Error 0x80004005: Failed to extract all files out of box container #0. Error 0x80004005: Failed to extract Exiting with result code: 0x80004005 === Logging stopped: 2013/09/04 16:29:51 === If I run command locally at the server - all works fine. Start-Process -FilePath "C:\temp\dotnetfx45_full_x86_x64.exe" ` -ArgumentList "/q /norestart" -Wait

    Read the article

  • OAF Page to Upload Files into Server from local Machine

    - by PRajkumar
    1. Create a New Workspace and Project File > New > General > Workspace Configured for Oracle Applications File Name – PrajkumarFileUploadDemo   Automatically a new OA Project will also be created   Project Name -- FileUploadDemo Default Package -- prajkumar.oracle.apps.fnd.fileuploaddemo   2. Create a New Application Module (AM) Right Click on FileUploadDemo > New > ADF Business Components > Application Module Name -- FileUploadAM Package -- prajkumar.oracle.apps.fnd.fileuploaddemo.server Check Application Module Class: FileUploadAMImpl Generate JavaFile(s)   3. Create a New Page Right click on FileUploadDemo > New > Web Tier > OA Components > Page Name -- FileUploadPG Package -- prajkumar.oracle.apps.fnd.fileuploaddemo.webui   4. Select the FileUploadPG and go to the strcuture pane where a default region has been created   5. Select region1 and set the following properties --     Attribute Property ID PageLayoutRN AM Definition prajkumar.oracle.apps.fnd.fileuploaddemo.server.FileUploadAM Window Title Uploading File into Server from Local Machine Demo Window Title Uploading File into Server from Local Machine Demo     6. Create Stack Layout Region Under Page Layout Region Right click PageLayoutRN > New > Region   Attribute Property ID MainRN AM Definition messageComponentLayout   7. Create a New Item messageFileUpload Bean under MainRN Right click on MainRN > New > messageFileUpload Set Following Properties for New Item --   Attribute Property ID MessageFileUpload Item Style messageFileUpload   8. Create a New Item Submit Button Bean under MainRN Right click on MainRN > New > messageLayout Set Following Properties for messageLayout --   Attribute Property ID ButtonLayout   Right Click on ButtonLayout > New > Item   Attribute Property ID Submit Item Style submitButton Attribute Set /oracle/apps/fnd/attributesets/Buttons/Go   9. Create Controller for page FileUploadPG Right Click on PageLayoutRN > Set New Controller Package Name: prajkumar.oracle.apps.fnd.fileuploaddemo.webui Class Name: FileUploadCO   Write Following Code in FileUploadCO processFormRequest   import oracle.cabo.ui.data.DataObject; import java.io.FileOutputStream; import java.io.InputStream; import oracle.jbo.domain.BlobDomain; import java.io.File; import oracle.apps.fnd.framework.OAException; public void processFormRequest(OAPageContext pageContext, OAWebBean webBean) { super.processFormRequest(pageContext, webBean);    if(pageContext.getParameter("Submit")!=null)  {   upLoadFile(pageContext,webBean);      } }   -- Use Following Code if want to Upload Files in Local Machine -- ----------------------------------------------------------------------------------- public void upLoadFile(OAPageContext pageContext,OAWebBean webBean) { String filePath = "D:\\PRajkumar";  System.out.println("Default File Path---->"+filePath);  String fileUrl = null;  try  {   DataObject fileUploadData =  pageContext.getNamedDataObject("MessageFileUpload"); //FileUploading is my MessageFileUpload Bean Id   if(fileUploadData!=null)   {    String uFileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");  // include this line    String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");  // For Mime Type    System.out.println("User File Name---->"+uFileName);    FileOutputStream output = null;    InputStream input = null;    BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, uFileName);    System.out.println("uploadedByteStream---->"+uploadedByteStream);                               File file = new File("D:\\PRajkumar", uFileName);    System.out.println("File output---->"+file);    output = new FileOutputStream(file);    System.out.println("output----->"+output);    input = uploadedByteStream.getInputStream();    System.out.println("input---->"+input);    byte abyte0[] = new byte[0x19000];    int i;         while((i = input.read(abyte0)) > 0)    output.write(abyte0, 0, i);    output.close();    input.close();   }  }  catch(Exception ex)  {   throw new OAException(ex.getMessage(), OAException.ERROR);  }     }   -- Use Following Code if want to Upload File into Server -- ------------------------------------------------------------------------- public void upLoadFile(OAPageContext pageContext,OAWebBean webBean) { String filePath = "/u01/app/apnac03r12/PRajkumar/";  System.out.println("Default File Path---->"+filePath);  String fileUrl = null;  try  {   DataObject fileUploadData =  pageContext.getNamedDataObject("MessageFileUpload");  //FileUploading is my MessageFileUpload Bean Id     if(fileUploadData!=null)   {    String uFileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");   // include this line    String contentType = (String) fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");   // For Mime Type    System.out.println("User File Name---->"+uFileName);    FileOutputStream output = null;    InputStream input = null;    BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, uFileName);    System.out.println("uploadedByteStream---->"+uploadedByteStream);                               File file = new File("/u01/app/apnac03r12/PRajkumar", uFileName);    System.out.println("File output---->"+file);    output = new FileOutputStream(file);    System.out.println("output----->"+output);    input = uploadedByteStream.getInputStream();    System.out.println("input---->"+input);    byte abyte0[] = new byte[0x19000];    int i;         while((i = input.read(abyte0)) > 0)    output.write(abyte0, 0, i);    output.close();    input.close();   }  }  catch(Exception ex)  {   throw new OAException(ex.getMessage(), OAException.ERROR);  }     }   10. Congratulation you have successfully finished. Run Your page and Test Your Work           -- Used Code to Upload files into Server   -- Before Upload files into Server     -- After Upload files into Server       -- Used Code to Upload files into Local Machine   -- Before Upload files into Local Machine       -- After Upload files into Local Machine

    Read the article

  • Using Diskpart in a PowerShell script won't allow script to reuse drive letter

    - by Kyle
    I built a script that mounts (attach) a VHD using Diskpart, cleans out some system files and then unmounts (detach) it. It uses a foreach loop and is suppose to clean multiple VHD using the same drive letter. However, after the 1st VHD it fails. I also noticed that when I try to manually attach a VHD with diskpart, diskpart succeeds, the Disk Manager shows the disk with the correct drive letter, but within the same PoSH instance I can not connect (set-location) to that drive. If I do a manual diskpart when I 1st open PoSH I can attach and detach all I want and I get the drive letter every time. Is there something I need to do to reset diskpart in the script? Here's a snippet of the script I'm using. function Mount-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)] [string]$DL, [string]$DiskpartScript = "$env:SystemDrive\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7 or Windows Server 2008 R2."} } process{ ## Diskpart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Select VDisk File="$Path" `nAttach VDisk Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart Start-Sleep -Seconds 3 @" Select VDisk File="$Path"`nSelect partition 1 `nAssign Letter="$DL" Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart } end { Remove-Item -Path $DiskpartScript -Force ; "" Write-Host "The VHD ""$Path"" has been successfully mounted." ; "" } } function Dismount-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [switch]$Remove, [switch]$NoConfirm, [string]$DiskpartScript = "$env:SystemDrive\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } function RemoveVHD { switch ($NoConfirm) { $false { ## Prompt for confirmation to delete the VHD file ## "" ; Write-Warning "Are you sure you want to delete the file ""$Path""?" $Prompt = Read-Host "Type ""YES"" to continue or anything else to break" if ($Prompt -ceq 'YES') { Remove-Item -Path $Path -Force "" ; Write-Host "VHD ""$Path"" deleted!" ; "" } else { "" ; Write-Host "Script terminated without deleting the VHD file." ; "" } } $true { ## Confirmation prompt suppressed ## Remove-Item -Path $Path -Force "" ; Write-Host "VHD ""$Path"" deleted!" ; "" } } } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7 or Windows Server 2008 R2."} } process{ ## DiskPart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Select VDisk File="$Path"`nDetach VDisk Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart Start-Sleep -Seconds 10 } end { if ($Remove) {RemoveVHD} Remove-Item -Path $DiskpartScript -Force ; "" } }

    Read the article

  • Generating/managing config files for hosted application

    - by mfinni
    I asked a question about config management, and haven't seen a reply. It's possible my question was too vague, so let's get down to brass tacks. Here's the process we follow when onboarding a new customer instance into our hosted application : how would you manage this? I'm leaning towards a Perl script to populate templates to generate shell scripts, config files, XML config files, etc. Looking briefly at CFengine and Chef, it seems like they're not going to reduce the amount of work, because I'd still have to manually specify all of the changes/edits within the tool. Doesn't seem to be much of a gain over touching the config files directly. We add a stanza to the main config file for the core (3rd-party) application. This stanza has values that defines the instance (customer) name the TCP listener port for this instance (not one currently used) the DB2 database name (serial numeric identifier, already exists, they get prestaged for us by the DBAs) three sub-config files, by name - they need to be created from 3 templates and be named after the instance The sub-config files define: The filepath for the DB2 volumes The filepath for the storage of objects The filepath for just one of the DB2 volumes (yes, redundant to the first item. We run some application commands, start the instance We do some LDAP thingies (make an OU for the instance, etc.) We add a stanza to the config file for our security listener that acts as a passthrough to LDAP instance name LDAP OU TCP port for instance DB2 database name We restart the security listener (off-hours), change the main config file from item 1, stop and restart the instance. It is now authenticating via LDAP. We add the stop and start commands for this instance to the HA failover scripts. We import an XML config file into the instance that defines things for the actual application for the customer - user names, groups, permissions, and business rules. The XML is supplied by the implementation team. Now, we configure the dataloading application We add a stanza to the existing top-level config file that points to a new customer-level config file. The new customer-level config file includes: the instance (customer) name the DB2 database name arbitrary number of sub-config files, by name Each of the sub-config files defines: filepaths to the directories for ingestion, feedback, backup, and failure those filepaths have a common path to a customer-specific folder, and then one folder for each sub-config file Each of those filepaths needs to be created We need to add this customer instance to our monitoring scripts that confirm the proper processes are running and can be logged into. Of course, those monitoring config files include the instance name, the TCP port, the DB2 database name, etc. There's also a reporting application that needs to be configured for the new instance. You get the idea. There's also XML that is loaded into WAS by the middleware team. We give them the values for them to plug into the XML - they could very easily hand us the template and we could give them back completed XML.

    Read the article

  • Monitoring settings in a configsection of your app.config for changes

    - by dotjosh
    The usage:public static void Main() { using(var configSectionAdapter = new ConfigurationSectionAdapter<ACISSInstanceConfigSection>("MyConfigSectionName")) { configSectionAdapter.ConfigSectionChanged += () => { Console.WriteLine("File has changed! New setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); }; Console.WriteLine("The initial setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); Console.ReadLine(); } }  The meat: public class ConfigurationSectionAdapter<T> : IDisposable where T : ConfigurationSection { private readonly string _configSectionName; private FileSystemWatcher _fileWatcher; public ConfigurationSectionAdapter(string configSectionName) { _configSectionName = configSectionName; StartFileWatcher(); } private void StartFileWatcher() { var configurationFileDirectory = new FileInfo(Configuration.FilePath).Directory; _fileWatcher = new FileSystemWatcher(configurationFileDirectory.FullName); _fileWatcher.Changed += FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = true; } private void FileWatcherOnChanged(object sender, FileSystemEventArgs args) { var changedFileIsConfigurationFile = string.Equals(args.FullPath, Configuration.FilePath, StringComparison.OrdinalIgnoreCase); if (!changedFileIsConfigurationFile) return; ClearCache(); OnConfigSectionChanged(); } private void ClearCache() { ConfigurationManager.RefreshSection(_configSectionName); } public T ConfigSection { get { return (T)Configuration.GetSection(_configSectionName); } } private System.Configuration.Configuration Configuration { get { return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } } public delegate void ConfigChangedHandler(); public event ConfigChangedHandler ConfigSectionChanged; protected void OnConfigSectionChanged() { if (ConfigSectionChanged != null) ConfigSectionChanged(); } public void Dispose() { _fileWatcher.Changed -= FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = false; _fileWatcher.Dispose(); } }

    Read the article

  • Powershell if statement not working - help!

    - by Dmart
    I have a batch file that takes a computer name as its argument and will install Java JRE on it remotely. Now, Im trying to run this Powershell script to repeatedly call the batch file and install Java on any system that it finds without the latest version. It seems to run error-free, but the statements inside the if code block never seem to run - even when the if conditional test evaluates to true. Can anyone look at this script and point out what I'm possibly missing? I'm using the Quest AD cmdlets, and BSOnPosh module. Thank you. get-qadcomputer -sizelimit 0 -name mypc* -searchroot 'OU=MyComputers,DC=MyDomain,DC=lcl'| test-host -property name |ForEach-Object -process { $targnm = $_.name $tststr=reg query "\\$targnm\HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" /v Java6FamilyVersion if(-not ($tststr | select-string -SimpleMatch '1.6.0_20')) { $mssg="Updating to JRE 6u20 on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append cmd /c \\server\apps\java\installjreremote.cmd $targnm } else { $mssg ="JRE 6u20 found on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append } }

    Read the article

  • Overloading methods that do logically different things, does this break any major principles?

    - by siva.k
    This is something that's been bugging me for a bit now. In some cases you see code that is a series of overloads, but when you look at the actual implementation you realize they do logically different things. However writing them as overloads allows the caller to ignore this and get the same end result. But would it be more sound to name the methods more explicitly then to write them as overloads? public void LoadWords(string filePath) { var lines = File.ReadAllLines(filePath).ToList(); LoadWords(lines); } public void LoadWords(IEnumerable<string> words) { // loads words into a List<string> based on some filters } Would these methods better serve future developers to be named as LoadWordsFromFile() and LoadWordsFromEnumerable()? It seems unnecessary to me, but if that is better what programming principle would apply here? On the flip side it'd make it so you didn't need to read the signatures to see exactly how you can load the words, which as Uncle Bob says would be a double take. But in general is this type of overloading to be avoided then?

    Read the article

  • Powershell Foreach-Object with if statement not working - help!

    - by Dmart
    I have a batch file that takes a computer name as its argument and will install Java JRE on it remotely. Now, Im trying to run this Powershell script to repeatedly call the batch file and install Java on any system that it finds without the latest version. It seems to run error-free, but the statements inside the if code block never seem to run - even when the if conditional test evaluates to true. Can anyone look at this script and point out what I'm possibly missing? I'm using the Quest AD cmdlets, and BSOnPosh module. Thank you. get-qadcomputer -sizelimit 0 -name mypc* -searchroot 'OU=MyComputers,DC=MyDomain,DC=lcl'| test-host -property name |ForEach-Object -process { $targnm = $_.name $tststr=reg query "\\$targnm\HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" /v Java6FamilyVersion if(-not ($tststr | select-string -SimpleMatch '1.6.0_20')) { $mssg="Updating to JRE 6u20 on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append cmd /c \\server\apps\java\installjreremote.cmd $targnm } else { $mssg ="JRE 6u20 found on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append } }

    Read the article

  • .NET Security Part 4

    - by Simon Cooper
    Finally, in this series, I am going to cover some of the security issues that can trip you up when using sandboxed appdomains. DISCLAIMER: I am not a security expert, and this is by no means an exhaustive list. If you actually are writing security-critical code, then get a proper security audit of your code by a professional. The examples below are just illustrations of the sort of things that can go wrong. 1. AppDomainSetup.ApplicationBase The most obvious one is the issue covered in the MSDN documentation on creating a sandbox, in step 3 – the sandboxed appdomain has the same ApplicationBase as the controlling appdomain. So let’s explore what happens when they are the same, and an exception is thrown. In the sandboxed assembly, Sandboxed.dll (IPlugin is an interface in a partially-trusted assembly, with a single MethodToDoThings on it): public class UntrustedPlugin : MarshalByRefObject, IPlugin { // implements IPlugin.MethodToDoThings() public void MethodToDoThings() { throw new EvilException(); } } [Serializable] internal class EvilException : Exception { public override string ToString() { // show we have read access to C:\Windows // read the first 5 directories Console.WriteLine("Pwned! Mwuahahah!"); foreach (var d in Directory.EnumerateDirectories(@"C:\Windows").Take(5)) { Console.WriteLine(d.FullName); } return base.ToString(); } } And in the controlling assembly: // what can possibly go wrong? AppDomainSetup appDomainSetup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase } // only grant permissions to execute // and to read the application base, nothing else PermissionSet restrictedPerms = new PermissionSet(PermissionState.None); restrictedPerms.AddPermission( new SecurityPermission(SecurityPermissionFlag.Execution)); restrictedPerms.AddPermission( new FileIOPermission(FileIOPermissionAccess.Read, appDomainSetup.ApplicationBase); restrictedPerms.AddPermission( new FileIOPermission(FileIOPermissionAccess.pathDiscovery, appDomainSetup.ApplicationBase); // create the sandbox AppDomain sandbox = AppDomain.CreateDomain("Sandbox", null, appDomainSetup, restrictedPerms); // execute UntrustedPlugin in the sandbox // don't crash the application if the sandbox throws an exception IPlugin o = (IPlugin)sandbox.CreateInstanceFromAndUnwrap("Sandboxed.dll", "UntrustedPlugin"); try { o.MethodToDoThings() } catch (Exception e) { Console.WriteLine(e.ToString()); } And the result? Oops. We’ve allowed a class that should be sandboxed to execute code with fully-trusted permissions! How did this happen? Well, the key is the exact meaning of the ApplicationBase property: The application base directory is where the assembly manager begins probing for assemblies. When EvilException is thrown, it propagates from the sandboxed appdomain into the controlling assembly’s appdomain (as it’s marked as Serializable). When the exception is deserialized, the CLR finds and loads the sandboxed dll into the fully-trusted appdomain. Since the controlling appdomain’s ApplicationBase directory contains the sandboxed assembly, the CLR finds and loads the assembly into a full-trust appdomain, and the evil code is executed. So the problem isn’t exactly that the sandboxed appdomain’s ApplicationBase is the same as the controlling appdomain’s, it’s that the sandboxed dll was in such a place that the controlling appdomain could find it as part of the standard assembly resolution mechanism. The sandbox then forced the assembly to load in the controlling appdomain by throwing a serializable exception that propagated outside the sandbox. The easiest fix for this is to keep the sandbox ApplicationBase well away from the ApplicationBase of the controlling appdomain, and don’t allow the sandbox permissions to access the controlling appdomain’s ApplicationBase directory. If you do this, then the sandboxed assembly can’t be accidentally loaded into the fully-trusted appdomain, and the code can’t be executed. If the plugin does try to induce the controlling appdomain to load an assembly it shouldn’t, a SerializationException will be thrown when it tries to load the assembly to deserialize the exception, and no damage will be done. 2. Loading the sandboxed dll into the application appdomain As an extension of the previous point, you shouldn’t directly reference types or methods in the sandboxed dll from your application code. That loads the assembly into the fully-trusted appdomain, and from there code in the assembly could be executed. Instead, pull out methods you want the sandboxed dll to have into an interface or class in a partially-trusted assembly you control, and execute methods via that instead (similar to the example above with the IPlugin interface). If you need to have a look at the assembly before executing it in the sandbox, either examine the assembly using reflection from within the sandbox, or load the assembly into the Reflection-only context in the application’s appdomain. The code in assemblies in the reflection-only context can’t be executed, it can only be reflected upon, thus protecting your appdomain from malicious code. 3. Incorrectly asserting permissions You should only assert permissions when you are absolutely sure they’re safe. For example, this method allows a caller read-access to any file they call this method with, including your documents, any network shares, the C:\Windows directory, etc: [SecuritySafeCritical] public static string GetFileText(string filePath) { new FileIOPermission(FileIOPermissionAccess.Read, filePath).Assert(); return File.ReadAllText(filePath); } Be careful when asserting permissions, and ensure you’re not providing a loophole sandboxed dlls can use to gain access to things they shouldn’t be able to. Conclusion Hopefully, that’s given you an idea of some of the ways it’s possible to get past the .NET security system. As I said before, this post is not exhaustive, and you certainly shouldn’t base any security-critical applications on the contents of this blog post. What this series should help with is understanding the possibilities of the security system, and what all the security attributes and classes mean and what they are used for, if you were to use the security system in the future.

    Read the article

  • iPad UIWebView PDF rendering is giving me weird visual artifacts

    - by ashwhite
    I am having some difficulty using a UIWebView to render PDF files on the iPad. Everything works fine in portrait mode, but turning the device to landscape produces strange visual quirkiness. Zooming in (but not out) even the slightest will correct it, but obviously that's not an ideal workaround. The issue occurs with any PDF file (I have tried several, all stored locally in the bundle, not retrieved from the web). I also created a clone of the project for iPhone, which seems to work just fine, so the problem is iPad-specific. The problem occurs both in the simulator as well as on a physical iPad. Screenshot http://dev.boxkite.net/images/ipad/ipad-pdf.png Code NSString* filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; NSData* data = [NSData dataWithContentsOfFile:filePath]; [self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil]; Thanks so much for your time.

    Read the article

  • Escaping an equals sign in DOS batch string replacement command

    - by Alastair
    I need to replace some text in a JNLP file using a DOS batch file to tune it for the local machine. The problem is that the search pattern contains an equals sign which is messing up the string replacement in the batch file. I want to replace the line, <j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/> with specific settings for the initial and max heap sizes. For example at the moment I have, for /f "tokens=* delims=" %%a in (%filePath%agility.jnlp) do ( set str=%%a set str=!str:initial-heap-size="100M"=initial-heap-size="%min%M"! echo !str!>>%filePath%new.jnlp) but the = in the search pattern is being read as part of the replacement command. How do I escape the equals sign so it is processed as text?

    Read the article

  • XtraReports Web Viewer not loading Parameters Popup

    - by Jan de Jager
    So were loading a a report from a saved file (this seems to not be the general way to do things), but the report viewer refuses to initialise the parameters popup. WTF!!! Here's the code: protected void Page_Load(object sender, EventArgs e) { string ReportName = Request["ReportName"]; XtraReport newReport = CreateReportFromFile(ReportName); newReport.RequestParameters = true; ReportViewerControl1.Report = newReport; } private XtraReport CreateReportFromFile(string filePath) { XtraReport report = new XtraReport(); report = XtraReport.FromFile(filePath, true); return report; }

    Read the article

  • SQL Server 2008: FileStream Insertion Failure w/ .NET 3.5SP1

    - by James Alexander
    I've configured a db w/ a FileStream group and have a table w/ File type on it. When attempting to insert a streamed file and after I create the table row, my query to read the filepath out and the buffer returns a null file path. I can't seem to figure out why though. Here is the table creation script: /****** Object: Table [dbo].[JobInstanceFile] Script Date: 03/22/2010 18:05:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[JobInstanceFile]( [JobInstanceFileId] [int] IDENTITY(1,1) NOT NULL, [JobInstanceId] [int] NOT NULL, [File] [varbinary](max) FILESTREAM NULL, [FileId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Created] [datetime] NOT NULL, CONSTRAINT [PK_JobInstanceFile] PRIMARY KEY CLUSTERED ( [JobInstanceFileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup], UNIQUE NONCLUSTERED ( [FileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[JobInstanceFile] ADD DEFAULT (newid()) FOR [FileId] GO Here's my proc I call to create the row before streaming the file: /****** Object: StoredProcedure [dbo].[JobInstanceFileCreate] Script Date: 03/22/2010 18:06:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create proc [dbo].[JobInstanceFileCreate] @JobInstanceId int, @Created datetime as insert into JobInstanceFile (JobInstanceId, FileId, Created) values (@JobInstanceId, newid(), @Created) select scope_identity() GO And lastly, here's the code I'm using: public int CreateJobInstanceFile(int jobInstanceId, string filePath) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsumerMarketingStoreFiles"].ConnectionString)) using (var fileStream = new FileStream(filePath, FileMode.Open)) { connection.Open(); var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { //create the JobInstanceFile instance var command = new SqlCommand("JobInstanceFileCreate", connection) { Transaction = tran }; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@JobInstanceId", jobInstanceId); command.Parameters.AddWithValue("@Created", DateTime.Now); int jobInstanceFileId = Convert.ToInt32(command.ExecuteScalar()); //read out the filestream transaction context to stream the file for storage command.CommandText = "select [File].PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from JobInstanceFile where JobInstanceFileId = @JobInstanceFileId"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@JobInstanceFileId", jobInstanceFileId); using (SqlDataReader dr = command.ExecuteReader()) { dr.Read(); //get the file path we're writing out to string writePath = dr.GetString(0); using (var writeStream = new SqlFileStream(writePath, (byte[])dr.GetValue(1), FileAccess.ReadWrite)) { //copy from one stream to another byte[] bytes = new byte[65536]; int numBytes; while ((numBytes = fileStream.Read(bytes, 0, 65536)) 0) writeStream.Write(bytes, 0, numBytes); } } tran.Commit(); return jobInstanceFileId; } catch (Exception e) { tran.Rollback(); throw e; } } } Can someone please let me know what I'm doing wrong. In the code, the following expression is returning null for the file path and shouldn't be: //get the file path we're writing out to string writePath = dr.GetString(0); The server is different then the computer the code is running on but the necessary shares appear to be in order and I have also run the following: EXEC sp_configure filestream_access_level, 2 Any help would be greatly appreciated. Thanks!

    Read the article

  • VB.NET Debug Error

    - by Daniel
    I get this error "Illegal characters in path" for this code: Dim strm As System.IO.FileStream strm = New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)

    Read the article

  • If url exists Objective-c

    - by HiGuy Smith
    Hey, I have a program that needs to tell if an online image exists, but the only way that I've gotten this to work is by loading the image in a NSData pointer and checking if the pointer exists. - (BOOL)exists { NSString *filePath = @"http://couleeapps.hostei.com/BottomBox.png"; NSURL *url = [NSURL URLWithString:filePath]; NSData *imageData = [NSData dataWithContentsOfURL:url]; if (imageData) { return YES; } return NO; } This has worked for me, but my problem is that I have a very slow connection, and it takes forever to download the image. So my question is: is there a way to check if a image (say "http://couleeapps.hostei.com/BottomBox.png") is available without having to download it? Help is much appreciated HiGuy

    Read the article

  • How to include multiple XML files in a single XML file for deserialization by XmlSerializer in .NET

    - by harrydev
    Hi, is it possible to use the XmlSerializer in .NET to load an XML file which includes other XML files? And how? This, in order to share XML state easily in two "parent" XML files, e.g. AB and BC in below. Example: using System; using System.IO; using System.Xml.Serialization; namespace XmlSerializerMultipleFilesTest { [Serializable] public class A { public int Value { get; set; } } [Serializable] public class B { public double Value { get; set; } } [Serializable] public class C { public string Value { get; set; } } [Serializable] public class AB { public A A { get; set; } public B B { get; set; } } [Serializable] public class BC { public B B { get; set; } public C C { get; set; } } class Program { public static void Serialize<T>(T data, string filePath) { using (var writer = new StreamWriter(filePath)) { var xmlSerializer = new XmlSerializer(typeof(T)); xmlSerializer.Serialize(writer, data); } } public static T Deserialize<T>(string filePath) { using (var reader = new StreamReader(filePath)) { var xmlSerializer = new XmlSerializer(typeof(T)); return (T)xmlSerializer.Deserialize(reader); } } static void Main(string[] args) { const string fileNameA = @"A.xml"; const string fileNameB = @"B.xml"; const string fileNameC = @"C.xml"; const string fileNameAB = @"AB.xml"; const string fileNameBC = @"BC.xml"; var a = new A(){ Value = 42 }; var b = new B(){ Value = Math.PI }; var c = new C(){ Value = "Something rotten" }; Serialize(a, fileNameA); Serialize(b, fileNameB); Serialize(c, fileNameC); // How can AB and BC be deserialized from single // files which include two of the A, B or C files. // Using ideally something like: var ab = Deserialize<AB>(fileNameAB); var bc = Deserialize<BC>(fileNameBC); // That is, so that A, B, C xml file // contents are shared across these two } } } Thus, the A, B, C files contain the following: A.xml: <?xml version="1.0" encoding="utf-8"?> <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Value>42</Value> </A> B.xml: <?xml version="1.0" encoding="utf-8"?> <B xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Value>3.1415926535897931</Value> </B> C.xml: <?xml version="1.0" encoding="utf-8"?> <C xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Value>Something rotten</Value> </C> And then the "parent" XML files would contain a XML include file of some sort (I have not been able to find anything like this), such as: AB.xml: <?xml version="1.0" encoding="utf-8"?> <AB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <A include="A.xml"/> <B include="B.xml"/> </AB> BC.xml: <?xml version="1.0" encoding="utf-8"?> <BC xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <B include="B.xml"/> <C include="C.xml"/> </BC> Of course, I guess this can be solved by implementing IXmlSerializer for AB and BC, but I was hoping there was an easier solution or a generic solution with which classes themselves only need the [Serializable] attribute and nothing else. That is, the split into multiple files is XML only and handled by XmlSerializer itself or a custom generic serializer on top of this. I know this should be somewhat possible with app.config (as in http://stackoverflow.com/questions/480538/use-xml-includes-or-config-references-in-app-config-to-include-other-config-files), but I would prefer a solution based on XmlSerializer. Thanks.

    Read the article

  • upload file from window application to Remote Web Server

    - by user208466
    string filePath = "C:\\test\\564.flv"; try { WebClient client = new WebClient(); NetworkCredential nc = new NetworkCredential(uName, password); Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv"); client.Credentials = nc; byte[] arrReturn = client.UploadFile(addy, filePath); Console.WriteLine(arrReturn.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } i am get this error "The remote server returned an error: (405) Method Not Allowed." what should i doo ??

    Read the article

  • FilePageSetupHeader in MS Project VBA project: Display image dynamically

    - by Anne Schuessler
    I want to display an image when printing a page from MS Page using the FilePageSetupHeader. It all works fine if I pass in the parameter for the Text property as a string as such FilePageSetupHeader Alignment:=pjRight, Text:="&P""C:\filepath\image.gif""" However, I'd prefer to be able to pass the filepath to the image to display as a variable. Somehow I can't get it right. So if I try something like the following: vImagePath = """&P""""" & prjFilePath & "\image.gif"""""" FilePageSetupHeader Alignment:=pjRight, Text:=vImagePath it just displays the path as a string. I'm pretty sure it boils down to something simple like escaping the quotes in the correct way, but I've been playing around with it for a while now and I can't seem to get it right. Any idea how this works?

    Read the article

  • ASP.Net MVC Toggling IsAjaxRequest property based on file upload?

    - by Jon
    I have a form all setup to upload a file and that is working fine. However the way my form is submitted is through AJAX. The button that submits is still a type="submit" in case JS is off. When I save my form the controller determines whether the IsAjaxRequest is true and if so returns some JSON otherwise it does a RedirectToAction. When I don't specify a filepath in my input type="file" it considers IsAjaxRequest as true. If there is a filepath set then it thinks that IsAjaxRequest is false. How is it determining that? My other problem is that when it thinks IsAjaxRequest is false and does a RedirectToAction("Index") I don't actually get sent to the Index view. Thanks

    Read the article

  • how to open a .pdf file in a panel or iframe using asp.net c#

    - by rahul
    I am trying to open a .pdf file on a button click. I want to open a .pdf file into a panel or some iframe. With the following code i can only open .pdf file in a separate window or in a save as mode. string filepath = Server.MapPath("News.pdf"); FileInfo file = new FileInfo(filepath); if (file.Exists) { Response.ClearContent(); Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = ReturnExtension(file.Extension.ToLower()); Response.TransmitFile(file.FullName); Response.End(); } how to assign a iframe to the below line Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

    Read the article

  • Problem with writeData

    - by zp26
    Hi, I have a problem with my code. I want to create a XML file like this: <name>myName<name> <x>myX<x> <y>myY<y> <z>myZ<z> but my file is: <name>myName<name><x>myX<x><y>myY<y><z>myZ<z> Can i have this text formatting? This is my code: -(void)salvataggioInXML:(NSString*)name:(float)x:(float)y:(float)z{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"filePosizioni.xml"]; NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; [myHandle seekToEndOfFile]; NSString *tagName = [NSString stringWithFormat:@"<name>%@<name>", name]; NSString *tagX = [NSString stringWithFormat:@"<x>%f<x>", name]; NSString *tagY = [NSString stringWithFormat:@"<y>%f<y>", name]; NSString *tagZ = [NSString stringWithFormat:@"<z>%f<z>", name]; NSData* dataName = [tagName dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataX = [tagX dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataY = [tagY dataUsingEncoding: NSASCIIStringEncoding]; NSData* dataZ = [tagZ dataUsingEncoding: NSASCIIStringEncoding]; [myHandle writeData:dataName]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataX]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataY]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; [myHandle writeData:dataZ]; NSLog(@"writeok"); [myHandle seekToEndOfFile]; NSLog(@"zp26 %@",filePath); }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >