private void ExecuteScript(FileInfo code)
{
this.progressLabel.Text = "Evaluating: " + code.Name;
Application.DoEvents();
this.Client.CodeManager.Execute<Object>(code, Make.Dictionary<Object>(host => this.Client));
this.progressBar.Increment(1);
}
public void TestWriteStructures(string file)
{
var structureReader = new StructureParsingManager();
var fileInfo = new FileInfo(file);
IStructureWorkspace structureWorkspace;
using (var readable = new FileReadableDataLocation(fileInfo))
{
structureWorkspace = structureReader.ParseStructures(readable);
}
ISdmxObjects structureBeans = structureWorkspace.GetStructureObjects(false);
string output = string.Format(CultureInfo.InvariantCulture, "test-sdmxv2.1-{0}", fileInfo.Name);
var writtingManager = new StructureWriterManager();
using (var outputStream = new FileStream(output, FileMode.Create))
{
writtingManager.WriteStructures(structureBeans, new SdmxStructureFormat(StructureOutputFormat.GetFromEnum(StructureOutputFormatEnumType.SdmxV21StructureDocument)), outputStream);
}
using (var readable = new FileReadableDataLocation(output))
{
XMLParser.ValidateXml(readable, SdmxSchemaEnumType.VersionTwoPointOne);
var structures = structureReader.ParseStructures(readable);
Assert.NotNull(structures);
}
}
public static ProcessStartInfo CreateTestAndCoverageProcessStartInfo(Settings settings, string[] fileNames)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = @"""" + settings.PartCoverPath + @"""";
startInfo.Arguments += " --target ";
startInfo.Arguments += @"""" + settings.MSTestPath + @"""";
startInfo.Arguments += " --target-work-dir ";
startInfo.Arguments += @"""" + settings.OutputPath + @""""; // trim trailing slash?
startInfo.Arguments += " --target-args ";
startInfo.Arguments += @"""";
foreach (string fileName in fileNames)
{
FileInfo f = new FileInfo(fileName);
startInfo.Arguments += " /testcontainer:";
startInfo.Arguments += f.Name;
}
startInfo.Arguments += " /noisolation";
startInfo.Arguments += " /nologo";
startInfo.Arguments += " /resultsfile:";
startInfo.Arguments += settings.TestLogFileName;
startInfo.Arguments += @"""";
startInfo.Arguments += " --include " + settings.CoverageReportingAssembliesRegEx;
startInfo.Arguments += " --output " + @"""" + Path.Combine(settings.OutputPath, settings.CoverageLogFileName) + @"""";
return startInfo;
}
/// <summary>
/// The process for backing up a directory index is simple:
/// a) create hard links to all the files in the lucene directory in a temp director
/// that gives us the current snapshot, and protect us from lucene's
/// deleting files.
/// b) copy the hard links to the destination directory
/// c) delete the temp directory
/// </summary>
public void Execute()
{
foreach (var file in Directory.EnumerateFiles(tempPath))
{
Notify("Copying " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
var fullName = new FileInfo(file).FullName;
FileCopy(file, Path.Combine(destination, Path.GetFileName(file)), fileToSize[fullName]);
Notify("Copied " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
}
try
{
IOExtensions.DeleteDirectory(tempPath);
}
catch (Exception e) //cannot delete, probably because there is a file being written there
{
logger.WarnException(
string.Format("Could not delete {0}, will delete those on startup", tempPath),
e);
foreach (var file in Directory.EnumerateFiles(tempPath))
{
MoveFileEx(file, null, MoveFileDelayUntilReboot);
}
MoveFileEx(tempPath, null, MoveFileDelayUntilReboot);
}
}
public void LoadPlugins(string pluginPath, bool checkSubDirs)
{
if(!Directory.Exists(pluginPath))
return;
if(Plugins.Any())
UnloadPlugins();
var dirInfo = new DirectoryInfo(pluginPath);
var files = dirInfo.GetFiles().Select(f => f.FullName).ToList();
if(checkSubDirs)
{
foreach(var dir in dirInfo.GetDirectories())
files.AddRange(dir.GetFiles().Select(f => f.FullName));
}
foreach(var file in files)
{
var fileInfo = new FileInfo(file);
if(fileInfo.Extension.Equals(".dll"))
{
var plugins = GetModule(file, typeof(IPlugin));
foreach(var p in plugins)
Plugins.Add(p);
}
}
Logger.WriteLine("Loading Plugins...", "PluginManager");
LoadPluginSettings();
}
public DisassembleResult Disassemble(string compiledFilePath, string additionalArguments = null)
{
if (!File.Exists(compiledFilePath))
{
throw new ArgumentException(
$"Compiled file not found in: {compiledFilePath}.",
nameof(compiledFilePath));
}
var workingDirectory = new FileInfo(this.DisassemblerPath).DirectoryName;
var arguments = this.BuildDisassemblerArguments(compiledFilePath, additionalArguments);
var disassemblerProcessStartInfo =
new ProcessStartInfo(this.DisassemblerPath)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = workingDirectory,
Arguments = arguments
};
this.UpdateDisassemblerProcessStartInfo(disassemblerProcessStartInfo);
string disassambledCode;
var isDisassembledSuccessfully =
this.ExecuteDisassemblerProcess(disassemblerProcessStartInfo, out disassambledCode);
return new DisassembleResult(isDisassembledSuccessfully, disassambledCode);
}
public void Execute()
{
var files = Directory.GetFiles(SourceFolder, "*.jpg");
foreach (var file in files)
{
try
{
DateTime dt;
using (var em = new ExifManager(file))
{
dt = em.DateTimeOriginal;
}
if (dt == DateTime.MinValue) continue;
var fi = new FileInfo(file);
var newName = Path.Combine(DestinantionFolder,
string.Format("{0}.jpg", dt.ToString("yyyy-MM-dd_HH.mm.ss")));
fi.MoveTo(newName);
}
catch
{
}
}
}
internal static bool ExtractArchive(string archive, string destination)
{
//REFACTOR: Only create RAR and ZIP classes after discovering that the file actually has a .zip or .rar extension
FileInfo archiveFI = new FileInfo(archive);
Rar rar = new Rar();
FastZip fz = new FastZip();
double archivesize = archiveFI.Length * 2;
char driveLetter = archiveFI.FullName[0];
if (!CheckDiskSpaceQuota(archivesize, driveLetter)) return false;
if (archiveFI.Extension == ".rar" || archiveFI.Extension == ".RAR")
return ExtractRarArchive(archive, destination, archiveFI, rar);
// ReSharper disable ConvertIfStatementToReturnStatement
if (archiveFI.Extension == ".zip" || archiveFI.Extension == ".ZIP")
// ReSharper restore ConvertIfStatementToReturnStatement
return ExtractZipArchive(archive, destination, fz);
//TODO: Should this return false?
return true;
}
private static bool ExtractRarArchive(string archive, string destination, FileInfo archiveFI, Rar rar)
{
Debugger.LogMessageToFile("[Archive extractor] Found RAR archive: " + archiveFI.FullName);
#region Open
if (!rar.Open(archive))
{
Debugger.LogMessageToFile("[Archive extractor] Failed to open archive: " + rar.LastErrorText);
//MessageBox.Show("Failed to open archive " + rar.LastErrorText);
return false;
}
Debugger.LogMessageToFile("[Archive extractor] Archive opened succesfully.");
#endregion
#region Extract
//TODO: Check if destination directory exists and if not, create it
if (!rar.Unrar(destination))
{
Debugger.LogMessageToFile("[Archive extractor] Failed to extract archive: " + rar.LastErrorText);
//MessageBox.Show("Failed to extract archive " + rar.LastErrorText);
return false;
}
Debugger.LogMessageToFile("[Archive extractor] Archive was extracted succesfully.");
#endregion
rar.Close();
DeleteLeftOfMultiparts(rar);
return true;
}
public static void SortLogs(string[] logs)
{
foreach (var logfile in logs)
{
FileInfo info = new FileInfo(logfile);
if (info.Length <= 1024)
{
try
{
string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar
+ "SMALL" + Path.DirectorySeparatorChar;
if (!Directory.Exists(destdir))
Directory.CreateDirectory(destdir);
File.Move(logfile, destdir + Path.GetFileName(logfile));
File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog"));
}
catch { }
continue;
}
MAVLinkInterface mine = new MAVLinkInterface();
try
{
using (mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
mine.logreadmode = true;
byte[] hbpacket = mine.getHeartBeat();
if (hbpacket.Length == 0)
continue;
MAVLink.mavlink_heartbeat_t hb = (MAVLink.mavlink_heartbeat_t)mine.DebugPacket(hbpacket);
mine.logreadmode = false;
mine.logplaybackfile.Close();
string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar
+ mine.MAV.aptype.ToString() + Path.DirectorySeparatorChar
+ hbpacket[3] + Path.DirectorySeparatorChar;
if (!Directory.Exists(destdir))
Directory.CreateDirectory(destdir);
File.Move(logfile, destdir + Path.GetFileName(logfile));
try
{
File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog"));
}
catch { }
}
}
catch { continue; }
}
}
public void test000_FirstPack()
{
FileInfo packFile = getPack("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
Stream @is = packFile.Open(System.IO.FileMode.Open, FileAccess.Read);
try
{
FileInfo tmppack = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1"));
FileInfo idxFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.idx"));
FileInfo tmpPackFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.pack"));
tmppack.Create().Close();
idxFile.Create().Close();
tmpPackFile.Create().Close();
IndexPack pack = new IndexPack(db, @is, tmppack);
pack.index(new TextProgressMonitor());
PackFile file = new PackFile(idxFile, tmpPackFile);
Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035")));
Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799")));
}
finally
{
@is.Close();
}
}
public void Load(FileInfo file)
{
using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
{
Load(stream);
}
}
/// <summary>
/// Writes the database to the location defined in the configuration file if it doesn't exist.
/// </summary>
public static void CheckForDatabase()
{
// A LocalSqlServer connection string get's added by default. Don't look at that one.
foreach (ConnectionStringSettings connection in ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>().Where(c => c.Name != "LocalSqlServer"))
{
try
{
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(connection.ConnectionString);
SqlCeConnectionStringBuilder sqlCEBuilder = new SqlCeConnectionStringBuilder(builder.ProviderConnectionString);
if (!File.Exists(sqlCEBuilder.DataSource))
{
FileInfo info = new FileInfo(sqlCEBuilder.DataSource);
if (!Directory.Exists(info.Directory.FullName))
{
Directory.CreateDirectory(info.Directory.FullName);
}
File.WriteAllBytes(info.FullName, EncounterTracker.Properties.Resources.EncounterTracker);
}
break;
}
catch
{
}
}
}
private void ExportChart(string fileName, ISymbolicDataAnalysisSolution solution, string formula) {
FileInfo newFile = new FileInfo(fileName);
if (newFile.Exists) {
newFile.Delete();
newFile = new FileInfo(fileName);
}
var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
using (ExcelPackage package = new ExcelPackage(newFile)) {
ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model");
FormatModelSheet(modelWorksheet, solution, formulaParts);
ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset");
WriteDatasetToExcel(datasetWorksheet, solution.ProblemData);
ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs");
WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset);
if (solution is IRegressionSolution) {
ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values");
WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution);
ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts");
AddCharts(chartsWorksheet);
}
package.Workbook.Properties.Title = "Excel Export";
package.Workbook.Properties.Author = "HEAL";
package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab";
package.Save();
}
}
/// <summary>
/// Explores the content of the folder using the given set of file masks.
/// </summary>
/// <param name="path">The root folder to explore.</param>
/// <param name="masks">A collection of file masks to match against.</param>
private void ExploreFolderWithMasks(String path, String[] masks)
{
this.knownPathes.Add(path);
//checks the directory for each mask provided
foreach (String mask in masks)
{
String[] files = Directory.GetFiles(path, mask);
foreach (String file in files)
{
//prevents the addition of the same file multiple times if it happens to match multiple masks
if (!this.foundFiles.Contains(file))
{
this.foundFiles.Add(file);
}
}
}
if (!recursive) return;
String[] dirs = Directory.GetDirectories(path);
foreach (String dir in dirs)
{
try
{
if (!this.knownPathes.Contains(dir))
{
FileInfo info = new FileInfo(dir);
if ((info.Attributes & FileAttributes.Hidden) == 0)
this.ExploreFolderWithMasks(dir, masks);
}
}
catch { /* Might be system folder.. */ };
}
}
public WebViewer(FileInfo file)
{
InitializeComponent();
File = file;
Text = Path.GetFileNameWithoutExtension(File.FullName);
_childBrowser = new WebControl();
_childBrowser.WebView = new WebView();
_childBrowser.WebView.FileDialog += OnProcessFileDialog;
_childBrowser.WebView.BeforeDownload += OnWebViewBeforeDownload;
_childBrowser.WebView.DownloadUpdated += OnWebViewDownloadUpdated;
_childBrowser.WebView.DownloadCompleted += OnWebViewDownloadCompleted;
_childBrowser.WebView.DownloadCanceled += OnWebViewDownloadCanceled;
_childBrowser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36";
Controls.Add(_childBrowser);
_browser = new WebControl();
_browser.WebView = new WebView();
_browser.Dock = DockStyle.Fill;
_browser.WebView.LoadCompleted += OnMainWebViewLoadComplete;
_browser.WebView.NewWindow += OnMainWebViewNewWindow;
_browser.WebView.BeforeDownload += OnWebViewBeforeDownload;
_browser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36";
Controls.Add(_browser);
_browser.BringToFront();
}
internal static IList<Test> LoadAll()
{
var file = new FileInfo("tests.xml");
if (!file.Exists)
return new Test[0];
XmlDocument xml = new XmlDocument();
using (var fs = file.OpenRead())
xml.Load(fs);
var ret = new List<Test>();
foreach (XmlNode node in xml.SelectNodes("/Tests/*"))
{
var n = node.SelectSingleNode("./Type");
if (n == null)
throw new InvalidOperationException("Test Type must be informed.");
var typeName = n.InnerText;
var type = FindType(typeName);
if (type == null)
throw new InvalidOperationException(string.Format("'{0}' is not a valid Test.", typeName));
var obj = (Test)Activator.CreateInstance(type);
node.ToEntity(obj);
ret.Add(obj);
}
return ret;
}
/// <summary>
/// Экспортирует массив данных в XLSX формат с учетом выбранной локали
/// </summary>
/// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
/// <param name="localisation">Локализация</param>
/// <returns>Успешное завершение операции</returns>
public override bool Export(String path, Localisation localisation)
{
try
{
if (!path.EndsWith(".xlsx"))
path += ".xlsx";
log.Info(String.Format("Export to .xlsx file to: {0}", path));
var timer = new Stopwatch();
timer.Start();
var file = new FileInfo(path);
using (var pck = new ExcelPackage(file))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
ws.Cells.AutoFitColumns();
pck.Save();
}
timer.Stop();
log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
return true;
}
catch (Exception ex)
{
log.Error("Can't export to .xlsx file!", ex);
return false;
}
}
public DecryptFile(FileInfo decryptedFile, FileInfo encryptedFile)
: this()
{
if (decryptedFile != null)
{
ID = System.IO.Path.GetFileNameWithoutExtension(decryptedFile.Name);
Name = decryptedFile.Name;
Path = decryptedFile.DirectoryName;
FileDateTime = decryptedFile.LastWriteTime.ToString();
Exists = decryptedFile.Exists;
}
else
{
Exists = false;
}
if (encryptedFile != null)
{
if (ID == null)
{
ID = System.IO.Path.GetFileNameWithoutExtension(encryptedFile.Name);
}
EncryptName = encryptedFile.Name;
EncryptPath = encryptedFile.DirectoryName;
EncryptDateTime = encryptedFile.LastWriteTime.ToString();
EncryptExists = encryptedFile.Exists;
}
else
{
EncryptExists = false;
}
}
/// <summary>
/// Archives the exception report.
/// The name of the PDF file is modified to make it easier to identify.
/// </summary>
/// <param name="pdfFile">The PDF file.</param>
/// <param name="archiveDirectory">The archive directory.</param>
public static void ArchiveException(FileInfo pdfFile, string archiveDirectory)
{
// Create a new subdirectory in the archive directory
// This is based on the date of the report being archived
DirectoryInfo di = new DirectoryInfo(archiveDirectory);
string archiveFileName = pdfFile.Name;
string newSubFolder = ParseFolderName(archiveFileName);
try
{
di.CreateSubdirectory(newSubFolder);
}
catch (Exception ex)
{
// The folder already exists so don't create it
}
// Create destination path
// Insert _EXCEPT into file name
// This will make it easier to identify as an exception in the archive folder
string destFileName = archiveFileName.Insert(archiveFileName.IndexOf("."), "_EXCEPT");
string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + destFileName;
// Move the file to the archive directory
try
{
pdfFile.MoveTo(destFullPath);
}
catch (Exception ex)
{
}
}
// http://stackoverflow.com/questions/12811850/setting-a-files-acl-to-be-inherited
private static void RemoveCustomACLs(string destination)
{
FileInfo fileInfo;
FileSecurity fileSecurity;
AuthorizationRuleCollection fileRules;
fileInfo = new FileInfo(destination);
fileSecurity = fileInfo.GetAccessControl();
fileSecurity.SetAccessRuleProtection(false, false);
fileSecurity.SetOwner(WindowsIdentity.GetCurrent().User);
/*
* Only fetch the explicit rules since I want to keep the inherited ones. Not
* sure if the target type matters in this case since I am not examining the
* IdentityReference.
*/
fileRules = fileSecurity.GetAccessRules(includeExplicit: true,
includeInherited: false, targetType: typeof(NTAccount));
/*
* fileRules is a AuthorizationRuleCollection object, which can contain objects
* other than FileSystemAccessRule (in theory), but GetAccessRules should only
* ever return a collection of FileSystemAccessRules, so we will just declare
* rule explicitly as a FileSystemAccessRule.
*/
foreach (FileSystemAccessRule rule in fileRules)
{
/*
* Remove any explicit permissions so we are just left with inherited ones.
*/
fileSecurity.RemoveAccessRule(rule);
}
fileInfo.SetAccessControl(fileSecurity);
}
/// <summary>
/// The normal PDF archival method.
/// </summary>
/// <param name="pdfFile">The PDF file.</param>
/// <param name="archiveDirectory">The archive directory.</param>
public static void ArchiveNormal(FileInfo pdfFile, string archiveDirectory)
{
// Create a new subdirectory in the archive directory
// This is based on the date of the report being archived
DirectoryInfo di = new DirectoryInfo(archiveDirectory);
string archiveFileName = pdfFile.Name;
string newSubFolder = ParseFolderName(archiveFileName);
try
{
di.CreateSubdirectory(newSubFolder);
}
catch (Exception ex)
{
// The folder already exists so don't create it
}
// Create destination path
string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + pdfFile.Name;
// Move the file to the archive directory
try
{
pdfFile.MoveTo(destFullPath);
}
catch (Exception ex)
{
// Unable to move the PDF to the archive
}
}
public byte[] FilenameToBytes(string filename)
{
byte[] data = null;
// get the file information form the selected file
FileInfo fInfo = new FileInfo(filename);
// get the length of the file to see if it is possible
// to upload it (with the standard 4 MB limit)
long numBytes = fInfo.Length;
double dLen = Convert.ToDouble(fInfo.Length / 1000000);
// set up a file stream and binary reader for the
// selected file
FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
// convert the file to a byte array
data = br.ReadBytes((int)numBytes);
br.Close();
fStream.Close();
fStream.Dispose();
return data;
}
public void Load()
{
// If configuration file exists then...
if (System.IO.File.Exists(FileName))
{
SettingsFile data;
// Deserialize and load data.
lock (saveReadFileLock)
{
data = Serializer.DeserializeFromXmlFile<SettingsFile>(FileName);
}
if (data == null) return;
//Programs.Clear();
//if (data.Programs != null) for (int i = 0; i < data.Programs.Count; i++) Programs.Add(data.Programs[i]);
Games.Clear();
if (data.Games != null) for (int i = 0; i < data.Games.Count; i++) Games.Add(data.Games[i]);
Pads.Clear();
if (data.Pads != null) for (int i = 0; i < data.Pads.Count; i++) Pads.Add(data.Pads[i]);
}
// Check if current app doesn't exist in the list then...
var currentFile = new System.IO.FileInfo(Application.ExecutablePath);
var currentGame = Games.FirstOrDefault(x => x.FileName == currentFile.Name);
if (currentGame == null)
{
// Add x360ce.exe
var item = x360ce.Engine.Data.Game.FromDisk(currentFile.Name);
var program = Programs.FirstOrDefault(x => x.FileName == currentFile.Name);
item.LoadDefault(program);
SettingsFile.Current.Games.Add(item);
}
else
{
currentGame.FullPath = currentFile.FullName;
}
}
internal static void Main(string[] args)
{
if (args.Length < 1)
{
System.Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"Usage: SetFileModifiedDate \"FilePath\""));
return;
}
string filePath = args[0];
if (!File.Exists(filePath))
{
System.Console.WriteLine("File: \"" + filePath + "\" doesn't exist!");
return;
}
FileAttributes attr = File.GetAttributes(filePath);
if ((attr & FileAttributes.ReadOnly) > 0)
{
System.Console.WriteLine("File: \"" + filePath + "\" is readonly!");
return;
}
FileInfo fi = new FileInfo(filePath);
fi.LastWriteTime = DateTime.Now.AddDays(-1);
System.Console.WriteLine("Modified date is now set to: " + fi.LastWriteTime.ToString("ddMMMyyTHH:mm:ss fff"));
}
/// <summary>
/// Gets the file fingerprints from the application folder
/// As the sha1 is calculated based on the content of the file,
/// there is a possibility that one key can have multiple fingerprints (duplicate files)
/// </summary>
/// <param name="appPath">The path to the application folder</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Return a dictionary of file fingerprints, with sha1 as key and a list of file fingerprints as value.</returns>
public async Task<Dictionary<string, List<FileFingerprint>>> GetFileFingerprints(string appPath, System.Threading.CancellationToken cancellationToken)
{
Dictionary<string, List<FileFingerprint>> fingerprints = new Dictionary<string, List<FileFingerprint>>();
appPath = Path.GetFullPath(appPath);
foreach (string file in Directory.GetFiles(appPath, "*", SearchOption.AllDirectories))
{
FileInfo fileInfo = new FileInfo(file);
FileFingerprint print = new FileFingerprint();
print.Size = fileInfo.Length;
print.FileName = fileInfo.FullName.Replace(appPath, string.Empty).TrimStart('\\');
print.SHA1 = await this.CalculateSHA1(fileInfo.FullName, cancellationToken);
if (fingerprints.ContainsKey(print.SHA1))
{
fingerprints[print.SHA1].Add(print);
}
else
{
fingerprints.Add(print.SHA1, new List<FileFingerprint>() { print });
}
}
return fingerprints;
}
public Credentials()
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+ Path.DirectorySeparatorChar + "Gradians.com" ;
string local = desktop + Path.DirectorySeparatorChar + ".local" ;
FileInfo localCnfg = new FileInfo(local) ;
remote = !localCnfg.Exists ;
if (remote) {
ftpServer = "109.74.201.62" ;
username = "gutenberg" ;
password = "shibb0leth" ;
bankRelPath = "bank" ;
} else {
// parse the local configuration file
string[] lines = File.ReadAllLines(local) ;
foreach (string line in lines) {
string[] tokens = line.Split('=') ;
if (tokens.Length != 2) continue ;
if (String.Compare(tokens[0],"username", true) == 0) {
username = tokens[1];
} else if (String.Compare(tokens[0],"password", true) == 0) {
password = tokens[1] ;
} else if (String.Compare(tokens[0], "bank", true) == 0) {
bankRelPath = tokens[1] ;
}
}
ftpServer = "localhost" ;
}
}
public static string UpdateStatus(string status, TwUser user, string replyId)
{
Regex regex = new Regex(@"\[(.*?)\]");
List<FileInfo> media = new List<FileInfo>();
foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
{
status = status.Replace(match.Value, "");
FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
if (!file.Exists)
throw new FileNotFoundException("File not found", file.FullName);
media.Add(file);
}
if (media.Count > 4) //limited by the twitter API
throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");
if (user == null)
user = TwUser.LoadCredentials();
string encodedStatus = Util.EncodeString(status);
if (media.Count == 0)
return InternalUpdateStatus(user, encodedStatus, replyId);
else
return InternalUpdateWithMedia(user, encodedStatus, replyId, media);
}
public CmsProcessableFile(
FileInfo file,
int bufSize)
{
_file = file;
_bufSize = bufSize;
}
public string Save(FileInfo file)
{
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
{
return Save(file.Name, fileStream);
}
}