コード例 #1
0
 private void CheckFile(string file, out ulong path, out ulong language, out ulong extension)
 {
     language  = 0;
     path      = 0;
     extension = 0;
     string[] pieces = file.Split('.');
     if (pieces.Length == 3)
     {
         path      = Hash64.HashString(pieces[0]);
         extension = Hash64.HashString(pieces[2]);
         language  = ulong.Parse(pieces[1]);
     }
     else if (pieces.Length == 2)
     {
         path      = Hash64.HashString(pieces[0]);
         extension = Hash64.HashString(pieces[1]);
     }
     else
     {
         this.Error(
             "Filename did not appear to be valid. It must be either path/to/file.ext or path/to/file.language.ext in format.");
     }
     if (index.Entry2Id(path, extension, 0).Count == 0)
     {
         this.Error("Could not find the file in the file index. Please check the spelling and that you used / and not \\.");
     }
 }
コード例 #2
0
 /// <summary>
 /// Gets the group with the given key.
 /// </summary>
 /// <param name="key">The key, nor null.</param>
 /// <returns>The cache group.</returns>
 protected virtual IDiskCacheGroup GetGroup(string key)
 {
     var hash = new Hash64();
     hash = hash.Add(key);
     string path = Path.Combine(cacheDirectoryPath, hash.ToString());
     return new Group(this, key, new DirectoryInfo(path));
 }
コード例 #3
0
        public void LoadXnd(out bool hasRedirectionType)
        {
            hasRedirectionType = false;

            Hash64 hash    = GetFolderHash();
            var    address = ClassName.GetDirectory() + hash.ToString().ToLower() + "/";
            var    files   = CEngine.Instance.FileManager.GetFiles(address, "*.metadata");

            if (files == null || files.Count == 0)
            {
                Profiler.Log.WriteLine(Profiler.ELogTag.Warning, "MetaData", $"MetaClass {address} is empty");
            }

            foreach (var i in files)
            {
                var MetaHash = CEngine.Instance.FileManager.GetPureFileFromFullName(i, false);
                var meta     = new MetaData(i);
                this.Metas[System.Convert.ToUInt32(MetaHash)] = meta;

                if (CIPlatform.Instance.PlayMode != CIPlatform.enPlayMode.Game)
                {
                    bool isRedirection = false;
                    meta.LoadMetaData(i, out isRedirection);
                    System.Diagnostics.Debug.Assert(MetaHash == meta.MetaHash.ToString());
                    if (isRedirection)
                    {
                        hasRedirectionType = true;
                    }
                }
            }
        }
コード例 #4
0
            public TestIsolationServer GetTestIsolationServer(DebuggerSetup debuggerSetup)
            {
                if (server != null)
                {
                    return(server);
                }

                try
                {
                    statusReporter("Attaching to AutoCAD.");

                    string ipcPortName = "AcadTestIsolationContext." + Hash64.CreateUniqueHash();
                    Guid   uniqueId    = Guid.NewGuid();
                    server = new TestIsolationServer(ipcPortName, uniqueId);
                    process.Start(ipcPortName, uniqueId, debuggerSetup);
                    return(server);
                }
                catch
                {
                    if (process != null)
                    {
                        process.Dispose();
                    }
                    if (server != null)
                    {
                        server.Dispose();
                    }
                    throw;
                }
            }
コード例 #5
0
        internal TeamCityExtension(string flowId)
        {
            this.flowId = flowId ?? Hash64.CreateUniqueHash().ToString();

            currentStepStack = new Stack <string>();
            continuationMap  = new MultiMap <string, Continuation>();
        }
コード例 #6
0
        MetaClass CreateMetaClass(System.Type type)
        {
            var cname = RttiHelper.GetTypeSaveString(type);

            var klass = new MetaClass();

            klass.MetaType = type;
            var csIdx    = cname.IndexOf('|');
            var fileName = cname;

            if (csIdx >= 0)
            {
                fileName = cname.Substring(csIdx + 1);
            }
            klass.ClassName = RName.GetRName(MetaDirectory.Name + "/" + fileName);

            MetaData curVer = new MetaData();

            curVer.BuildMetaData(type);

            Hash64 hash = klass.GetFolderHash();
            string dir  = klass.ClassName.GetDirectory() + hash.ToString();

            if (EngineNS.CEngine.Instance.FileManager.DirectoryExists(dir))
            {
                bool hasRedirection = false;
                klass.LoadXnd(out hasRedirection);
#if PWindow
                //if (hasRedirection)
                //    klass.Save2Xnd(false);
#endif
                MetaData data = klass.FindMetaData(curVer.MetaHash);
                if (data == null)
                {
                    klass.RegMetaData(curVer.MetaHash, curVer);
                    var xnd = IO.XndHolder.NewXNDHolder();
                    curVer.Save2Xnd(xnd.Node);
                    IO.XndHolder.SaveXND(dir + "/" + curVer.MetaHash + ".MetaData", xnd);
                }
            }
            else
            {
                CEngine.Instance.FileManager.CreateDirectory(dir);

                var sw = new System.IO.StreamWriter(dir + "/typename.txt", false);
                sw.WriteLine(cname);
                sw.Close();

                klass.RegMetaData(curVer.MetaHash, curVer);
                var xnd = IO.XndHolder.NewXNDHolder();
                curVer.Save2Xnd(xnd.Node);
                IO.XndHolder.SaveXND(dir + "/" + curVer.MetaHash + ".MetaData", xnd);
            }

            klass.CurrentVersion = curVer;
            Klasses.Add(cname, klass);

            return(klass);
        }
コード例 #7
0
ファイル: FileManager.cs プロジェクト: huangdonghai/titan3d
        public void InitFiles()
        {
#if PWindow
            if (EngineNS.IO.FileManager.UseCooked != null)
            {
                return;
            }

            var files = CEngine.Instance.FileManager.GetFiles(RName.GetRName("Shaders", RName.enRNameType.Engine).Address, "*.*", SearchOption.AllDirectories);
            if (files == null)
            {
                return;
            }
            foreach (var f in files)
            {
                bool error = false;
                var  i     = CEngine.Instance.FileManager.NormalizePath(f, out error);
                if (error)
                {
                    continue;
                }
                if (i.EndsWith(".shaderinc") ||
                    i.EndsWith(".cginc") ||
                    i.EndsWith(".shadingenv") ||
                    i.EndsWith(".compute"))
                {
                    var desc = new HLSLFileDesc();
                    desc.Directory = CEngine.Instance.FileManager.GetPathFromFullName(i);
                    desc.FileName  = CEngine.Instance.FileManager.GetPureFileFromFullName(i);
                    desc.HLSLCode  = System.IO.File.ReadAllText(i);
                    Hash64.CalcHash64(ref desc.HashCode, desc.HLSLCode);
                    FileDescDict.Add(desc.Directory + desc.FileName, desc);
                }
            }
            foreach (var i in FileDescDict)
            {
                GetDepends(i.Value);
            }

            foreach (var i in FileDescDict)
            {
                if (i.Key.EndsWith(".shadingenv") || i.Key.EndsWith(".compute"))
                {
                    var allDepends = new List <HLSLFileDesc>();
                    CollectDependTree(i.Value, allDepends);
                    allDepends.Sort((left, right) =>
                    {
                        return(left.FullName.CompareTo(right.FullName));
                    });
                    string AllCode = i.Value.HLSLCode;
                    foreach (var j in allDepends)
                    {
                        AllCode += j.HLSLCode;
                    }
                    Hash64.CalcHash64(ref i.Value.HashWithDepends, AllCode);
                }
            }
#endif
        }
コード例 #8
0
 public ReportFilePool(IDiskCacheGroup cacheGroup, int numberOfFiles)
 {
     for (var i = 0; i < numberOfFiles; i++)
     {
         var uniqueFilename = string.Format("{0}.{1}.html", ReportName, Hash64.CreateUniqueHash());
         files.Add(cacheGroup.GetFileInfo(uniqueFilename));
     }
 }
コード例 #9
0
 public Material(uint sec_id, string mat_name)
 {
     id       = sec_id;
     size     = 0U;
     hashname = Hash64.HashString(mat_name, 0UL);
     skipped  = new byte[48];
     count    = 0U;
 }
コード例 #10
0
        internal static async Task SearchForCubelights(Dictionary <uint, FileEntry> fileEntries, string outPath, IProgress <ProgressRecord> progress, CancellationToken ct)
        {
            var s = new System.Diagnostics.Stopwatch();

            s.Start();

            progress.Report(new ProgressRecord("Looking for worlds", 0, 0));

            var levels = fileEntries.Values
                         .Where(fe => fe.PathIds.HasUnHashed)
                         .Where(fe => fe.ExtensionIds.ToString() == "world")
                         .Select(fe => fe.Parent.EntryPath)
                         .ToList();
            var files = ImmutableHashSet.CreateRange(fileEntries.Select(i => i.Value.PathIds.Hashed));

            var interestingPaths = new ConcurrentBag <string>();
            var total            = levels.Count;
            var completed        = 0;

            var progressReporter = Task.Run(async() =>
            {
                while (completed < total && !ct.IsCancellationRequested)
                {
                    await Task.Delay(100);
                    progress.Report(new ProgressRecord("Checking cubelight names", total, completed));
                }
            });

            var opts = new ParallelOptions();

            opts.CancellationToken = ct;
            Parallel.ForEach(levels, levelname =>
            {
                for (var i = 1000; i <= 1000000; i++)
                {
                    var path = $"{levelname}/cube_lights/{i}";
                    var hsh  = Hash64.HashString(path);
                    if (files.Contains(hsh))
                    {
                        interestingPaths.Add(path);
                    }
                }
                var domeocc = $"{levelname}/cube_lights/dome_occlusion";
                if (files.Contains(Hash64.HashString(domeocc)))
                {
                    interestingPaths.Add(domeocc);
                }
                Interlocked.Increment(ref completed);
            });

            File.WriteAllLines(outPath, interestingPaths, new UTF8Encoding());

            completed = total;
            s.Stop();

            Console.WriteLine("Bruteforced {1} combinations in {0} ms", s.ElapsedMilliseconds, total * 999000);
            await progressReporter;
        }
コード例 #11
0
ファイル: SimpleDiskCache.cs プロジェクト: citizenmatt/gallio
        /// <summary>
        /// Gets the group with the given key.
        /// </summary>
        /// <param name="key">The key, nor null.</param>
        /// <returns>The cache group.</returns>
        protected virtual IDiskCacheGroup GetGroup(string key)
        {
            var hash = new Hash64();

            hash = hash.Add(key);
            string path = Path.Combine(cacheDirectoryPath, hash.ToString());

            return(new Group(this, key, new DirectoryInfo(path)));
        }
コード例 #12
0
        internal static async Task SearchForStreams(Dictionary <uint, FileEntry> fileEntries, string outPath, IProgress <ProgressRecord> progress, CancellationToken ct)
        {
            var s = new System.Diagnostics.Stopwatch();

            s.Start();
            progress.Report(new ProgressRecord("Loading bank/stream names", 0, 0));

            var pendingBankfile   = File.ReadAllLinesAsync("Data/banknames", ct);
            var pendingStreamfile = File.ReadAllLinesAsync("Data/streamnames", ct);

            // It's immutable. Very threadsafe.
            var files = ImmutableHashSet.CreateRange(fileEntries.Select(i => i.Value.PathIds.Hashed));

            var interestingBanks = (await pendingBankfile)
                                   .Where(i => files.Contains(Hash64.HashString(i)))
                                   .Select(i => i.Split("/").Last())
                                   .ToList();
            var streamNames = await pendingStreamfile;

            var interestingPaths = new ConcurrentBag <string>();
            int completed        = 0;
            int total            = streamNames.Length;

            var progressReporter = Task.Run(async() =>
            {
                while (completed < total && !ct.IsCancellationRequested)
                {
                    await Task.Delay(100);
                    progress.Report(new ProgressRecord("Checking stream names", total, completed));
                }
            });

            var opts = new ParallelOptions();

            opts.CancellationToken = ct;
            Parallel.ForEach(streamNames, opts, (s) =>
            {
                for (var i = 0; i < interestingBanks.Count; i++)
                {
                    var path = $"soundbanks/streamed/{interestingBanks[i]}/{s}";
                    var hsh  = Hash64.HashString(path);
                    if (files.Contains(hsh))
                    {
                        interestingPaths.Add(path);
                    }
                }
                Interlocked.Increment(ref completed);
            });

            File.WriteAllLines(outPath, interestingPaths, new UTF8Encoding());

            completed = total;
            s.Stop();
            Console.WriteLine("Bruteforced {1} combinations in {0} ms", s.ElapsedMilliseconds, total * interestingBanks.Count);
        }
コード例 #13
0
 public Topology(uint sec_id, obj_data obj)
 {
     id       = sec_id;
     size     = 0U;
     unknown1 = 0U;
     count1   = (uint)(obj.faces.Count / 3);
     facelist = obj.faces;
     count2   = 0U;
     items2   = new byte[0];
     hashname = Hash64.HashString(obj.object_name + ".Topology", 0UL);
 }
コード例 #14
0
 public void RegEffect(Hash64 hash, CGfxEffect effect)
 {
     lock (Effects)
     {
         if (effect.Desc.GetHash64() != hash)
         {
             hash = effect.Desc.GetHash64();
         }
         Effects[hash] = effect;
     }
 }
コード例 #15
0
 public Object3D(string object_name, uint parent)
 {
     id       = 0U;
     size     = 0U;
     hashname = Hash64.HashString(object_name, 0UL);
     count    = 0U;
     items    = new List <Vector3D>();
     rotation = new Matrix3D(1f, 0.0f, 0.0f, 0.0f, 0.0f, 1f, 0.0f, 0.0f, 0.0f, 0.0f, 1f, 0.0f, 0.0f, 0.0f, 0.0f,
                             0.0f);
     position = new Vector3D(0.0f, 0.0f, 0.0f);
     parentID = parent;
 }
コード例 #16
0
        public static async System.Threading.Tasks.Task LoadAllShaders(CRenderContext rc)
        {
            var sm         = CRenderContext.ShaderModelString;
            var shaderPath = CEngine.Instance.FileManager.DDCDirectory + sm + "/";
            var shaders    = CEngine.Instance.FileManager.GetFiles(shaderPath, "*.shader");

            Profiler.Log.WriteLine(Profiler.ELogTag.Info, "LoadShaders", $"Begin LoadShaders Number = {shaders.Count}");
            var t1  = Support.Time.HighPrecision_GetTickCount();
            var smp = Thread.ASyncSemaphore.CreateSemaphore(shaders.Count);

            foreach (var i in shaders)
            {
                if (MultiThreadCompile)
                {
                    CEngine.Instance.EventPoster.RunOn(async() =>
                    {
                        var fileName = CEngine.Instance.FileManager.GetPureFileFromFullName(i, false);
                        Hash64 hash  = Hash64.TryParse(fileName);
                        var effect   = new CGfxEffect();
                        if (await effect.LoadFromXndAsync(rc, hash) == 0)
                        {
                            CEngine.Instance.EffectManager.RegEffect(hash, effect);
                        }
                        else
                        {
                            CEngine.Instance.FileManager.DeleteFile(shaderPath + hash.ToString() + ".shader");
                        }
                        smp.Release();
                        return(true);
                    }, Thread.Async.EAsyncTarget.TPools);
                }
                else
                {
                    var    fileName = CEngine.Instance.FileManager.GetPureFileFromFullName(i, false);
                    Hash64 hash     = Hash64.TryParse(fileName);
                    var    effect   = new CGfxEffect();
                    if (await effect.LoadFromXndAsync(rc, hash) == 0)
                    {
                        CEngine.Instance.EffectManager.RegEffect(hash, effect);
                    }
                    else
                    {
                        CEngine.Instance.FileManager.DeleteFile(shaderPath + hash.ToString() + ".shader");
                    }
                    smp.Release();
                }
            }
            await smp.Await();

            var t2 = Support.Time.HighPrecision_GetTickCount();

            Profiler.Log.WriteLine(Profiler.ELogTag.Info, "LoadShaders", $"End LoadShaders, Times = {(t2 - t1) / 1000} ms");
        }
コード例 #17
0
        /// <summary>
        /// Creates an uninitialized host.
        /// </summary>
        /// <param name="hostSetup">The host setup.</param>
        /// <param name="logger">The logger for host message output.</param>
        /// <param name="runtimePath">The runtime path where the hosting executable will be found.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="hostSetup"/>
        /// <paramref name="logger"/>, or <paramref name="runtimePath"/> is null.</exception>
        public IsolatedProcessHost(HostSetup hostSetup, ILogger logger, string runtimePath)
            : base(hostSetup, logger, PingInterval)
        {
            if (runtimePath == null)
            {
                throw new ArgumentNullException("runtimePath");
            }

            this.runtimePath = runtimePath;
            uniqueId         = Hash64.CreateUniqueHash().ToString();

            logConsoleOutputBufferTimer = new Timer(LogConsoleOutputBufferTimeoutExpired);
        }
コード例 #18
0
ファイル: Attachment.cs プロジェクト: citizenmatt/gallio
        /// <summary>
        /// Creates an attachment.
        /// </summary>
        /// <param name="name">The name of attachment, or null to automatically assign one.  The attachment
        /// name must be unique within the scope of the currently executing test step.</param>
        /// <param name="contentType">The content type, not null.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="contentType"/> is null.</exception>
        internal /*to prevent subclassing outside of the framework*/ Attachment(string name, string contentType)
        {
            if (name != null && name.Length > 100)
            {
                throw new ArgumentException("name must be 100 chars or less", "name");
            }

            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            this.name        = name ?? Hash64.CreateUniqueHash().ToString();
            this.contentType = contentType;
        }
コード例 #19
0
        private void UpdateHash64()
        {
            if (Modifiers.Count == 0)
            {
                mHash64 = Hash64.Empty;
                return;
            }
            string mdfStr = "";

            for (int i = 0; i < Modifiers.Count; i++)
            {
                mdfStr += Modifiers[i].Name;
            }
            Hash64.CalcHash64(ref mHash64, mdfStr);
        }
コード例 #20
0
 public CGfxEffect TryGetEffect(ref Hash64 hash)
 {
     lock (Effects)
     {
         CGfxEffect result;
         if (Effects.TryGetValue(hash, out result) == true)
         {
             if (hash != result.Desc.GetHash64())
             {
                 System.Diagnostics.Debug.Assert(false);
             }
             return(result);
         }
     }
     return(null);
 }
コード例 #21
0
 public Geometry(uint sec_id, obj_data newobject)
 {
     this.id           = sec_id;
     this.size         = 0U;
     this.vert_count   = (uint)newobject.verts.Count;
     this.header_count = 5U;
     this.headers.Add(new GeometryHeader(3U, 1U));
     this.headers.Add(new GeometryHeader(2U, 7U));
     this.headers.Add(new GeometryHeader(3U, 2U));
     this.headers.Add(new GeometryHeader(3U, 20U));
     this.headers.Add(new GeometryHeader(3U, 21U));
     this.verts    = newobject.verts;
     this.uvs      = newobject.uv;
     this.normals  = newobject.normals;
     this.hashname = Hash64.HashString(newobject.object_name + ".Geometry", 0UL);
 }
コード例 #22
0
        public void SaveXML(IO.XmlHolder xml, Hash64 hash)
        {
            if (this.MtlShaderPatch.Name.RNameType == RName.enRNameType.Editor && this.MtlShaderPatch.Name.Name.Contains("MaterialEditor/Mats/"))
            {
                return;
            }
            if (xml == null)
            {
                xml = IO.XmlHolder.NewXMLHolder("EffectDesc", "");

                Save2XML(xml.RootNode);
            }

            var file = GetShaderInfoFileName(hash);

            IO.XmlHolder.SaveXML(file, xml);
        }
コード例 #23
0
        public Hash64 GetFolderHash()
        {
            var cname = RttiHelper.GetTypeSaveString(MetaType);

            cname = cname.Replace('+', '.');
            cname = cname.ToLower();
            var idx = cname.IndexOf('|');

            if (idx >= 0)
            {
                cname = cname.Substring(idx + 1);
            }
            Hash64 hash = new Hash64();

            Hash64.CalcHash64(ref hash, cname);
            return(hash);
        }
コード例 #24
0
        internal void UpdateHash64(bool UpdateMacro)
        {
            if (UpdateMacro)
            {
                UpdateMacroArray();
            }

            String = "";
            if (MtlShaderPatch != null)
            {
                String += MtlShaderPatch.ToString();
            }
            if (MdfQueueShaderPatch != null)
            {
                String += MdfQueueShaderPatch.ToString();
            }
            if (ShaderMacros != null)
            {
                String += ShaderMacros.ToString();
            }
            String += EnvShaderPatch.ToString();

            Hash64.CalcHash64(ref NameHash, String);
        }
コード例 #25
0
        public void PopulateCatalog_WhenPluginXmlContainsPreprocessorInstructions_AppliesThem()
        {
            string pluginContents = "<plugin pluginId=\"pluginId\" xmlns=\"http://www.gallio.org/\"><traits><?ifdef A?><name>A</name><?endif?><?ifdef B?><property>B</property><?endif?></traits></plugin>";

            PluginLoaderTest.RunWithTemporaryPluginFile((pluginDir, pluginFile) =>
            {
                Guid installationId   = Guid.NewGuid();
                var loader            = new CachingPluginLoader();
                loader.InstallationId = installationId;
                loader.AddPluginPath(pluginFile);
                loader.DefinePreprocessorConstant("A");

                Hash64 hash          = new Hash64().Add(pluginFile).Add("A").Add(installationId.ToString());
                var cacheDir         = CachingPluginLoader.GetCurrentUserPluginCacheDir();
                string cacheFilePath = Path.Combine(cacheDir, hash + ".xml");

                if (System.IO.File.Exists(cacheFilePath))
                {
                    System.IO.File.Delete(cacheFilePath);
                }

                // First pass.
                {
                    Plugin plugin = null;
                    var catalog   = MockRepository.GenerateMock <IPluginCatalog>();
                    catalog.Expect(x => x.AddPlugin(null, null)).IgnoreArguments()
                    .Do((Gallio.Common.Action <Plugin, DirectoryInfo>) delegate(Plugin pluginArg, DirectoryInfo baseDirectoryArg)
                    {
                        plugin = pluginArg;
                    });

                    loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance());

                    catalog.VerifyAllExpectations(); // added one plugin

                    Assert.AreEqual(new PropertySet()
                    {
                        { "name", "A" }
                    }, plugin.Traits.PropertySet);
                }

                // Check cache file.
                {
                    Assert.IsTrue(File.Exists(cacheFilePath));

                    Cache cache = Assert.XmlDeserialize <Cache>(File.ReadAllText(cacheFilePath));

                    Assert.AreEqual(installationId.ToString(), cache.InstallationId);
                    Assert.AreEqual(1, cache.PluginInfos.Count);
                    Assert.AreEqual(pluginDir, cache.PluginInfos[0].BaseDirectory);
                    Assert.AreEqual("pluginId", cache.PluginInfos[0].Plugin.PluginId);
                    Assert.AreEqual(pluginFile, cache.PluginInfos[0].PluginFile);
                    Assert.AreEqual(File.GetLastWriteTimeUtc(pluginFile), cache.PluginInfos[0].PluginFileModificationTime);
                }

                // Second pass should restore from cache.
                {
                    Plugin plugin = null;
                    var catalog   = MockRepository.GenerateMock <IPluginCatalog>();
                    catalog.Expect(x => x.AddPlugin(null, null)).IgnoreArguments()
                    .Do((Gallio.Common.Action <Plugin, DirectoryInfo>) delegate(Plugin pluginArg, DirectoryInfo baseDirectoryArg)
                    {
                        plugin = pluginArg;
                    });

                    loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance());

                    catalog.VerifyAllExpectations(); // added one plugin

                    Assert.AreEqual(new PropertySet()
                    {
                        { "name", "A" }
                    }, plugin.Traits.PropertySet);
                }
            }, pluginContents);
        }
コード例 #26
0
        /// <inheritdoc />
        protected override void LoadPlugins(PluginCallback pluginCallback, IProgressMonitor progressMonitor)
        {
            // Attempt to read the old cache.
            string cacheFilePath;

            try
            {
                Hash64 hash = new Hash64();
                foreach (string pluginPath in PluginPaths)
                {
                    hash = hash.Add(pluginPath);
                }
                foreach (string constant in InitialPreprocessorConstants)
                {
                    hash = hash.Add(constant);
                }
                hash = hash.Add(InstallationId.ToString());

                string cacheDirPath  = GetCurrentUserPluginCacheDir();
                string cacheFileName = hash + ".xml";
                cacheFilePath = Path.Combine(cacheDirPath, cacheFileName);

                if (Directory.Exists(cacheDirPath))
                {
                    if (File.Exists(cacheFilePath))
                    {
                        Cache oldCache = ReadCacheFile(cacheFilePath);
                        if (oldCache != null)
                        {
                            foreach (var pluginInfo in oldCache.PluginInfos)
                            {
                                pluginCallback(pluginInfo.Plugin, new DirectoryInfo(pluginInfo.BaseDirectory), pluginInfo.PluginFile);
                            }
                            return;
                        }
                    }
                }
                else
                {
                    Directory.CreateDirectory(cacheDirPath);
                }
            }
            catch (Exception)
            {
                // Fallback on any failure.
                // There can be all sorts of weird security exceptions that will prevent
                // us from manipulating the local application data directory.
                base.LoadPlugins(pluginCallback, progressMonitor);
                return;
            }

            // Load plugin metadata.
            var newCache = new Cache
            {
                InstallationId = InstallationId.ToString()
            };

            base.LoadPlugins((plugin, baseDirectory, pluginFile) =>
            {
                newCache.PluginInfos.Add(new CachePluginInfo
                {
                    Plugin        = plugin,
                    BaseDirectory = baseDirectory.FullName,
                    PluginFile    = pluginFile,
                    PluginFileModificationTime = File.GetLastWriteTimeUtc(pluginFile)
                });

                pluginCallback(plugin, baseDirectory, pluginFile);
            }, progressMonitor);

            // Attempt to store it in the cache.
            try
            {
                WriteCacheFile(cacheFilePath, newCache);
            }
            catch (Exception)
            {
                // Ignore any failure.
            }
        }
コード例 #27
0
        /// <inheritdoc />
        protected override void LoadPlugins(PluginCallback pluginCallback, IProgressMonitor progressMonitor)
        {
            // Attempt to read the old cache.
            string cacheFilePath;
            try
            {
                Hash64 hash = new Hash64();
                foreach (string pluginPath in PluginPaths)
                    hash = hash.Add(pluginPath);
                foreach (string constant in InitialPreprocessorConstants)
                    hash = hash.Add(constant);
                hash = hash.Add(InstallationId.ToString());

                string cacheDirPath = GetCurrentUserPluginCacheDir();
                string cacheFileName = hash + ".xml";
                cacheFilePath = Path.Combine(cacheDirPath, cacheFileName);

                if (Directory.Exists(cacheDirPath))
                {
                    if (File.Exists(cacheFilePath))
                    {
                        Cache oldCache = ReadCacheFile(cacheFilePath);
                        if (oldCache != null)
                        {
                            foreach (var pluginInfo in oldCache.PluginInfos)
                                pluginCallback(pluginInfo.Plugin, new DirectoryInfo(pluginInfo.BaseDirectory), pluginInfo.PluginFile);
                            return;
                        }
                    }
                }
                else
                {
                    Directory.CreateDirectory(cacheDirPath);
                }
            }
            catch (Exception)
            {
                // Fallback on any failure.
                // There can be all sorts of weird security exceptions that will prevent
                // us from manipulating the local application data directory.
                base.LoadPlugins(pluginCallback, progressMonitor);
                return;
            }

            // Load plugin metadata.
            var newCache = new Cache
            {
                InstallationId = InstallationId.ToString()
            };

            base.LoadPlugins((plugin, baseDirectory, pluginFile) =>
            {
                newCache.PluginInfos.Add(new CachePluginInfo
                {
                    Plugin = plugin,
                    BaseDirectory = baseDirectory.FullName,
                    PluginFile = pluginFile,
                    PluginFileModificationTime = File.GetLastWriteTimeUtc(pluginFile)
                });

                pluginCallback(plugin, baseDirectory, pluginFile);
            }, progressMonitor);

            // Attempt to store it in the cache.
            try
            {
                WriteCacheFile(cacheFilePath, newCache);
            }
            catch (Exception)
            {
                // Ignore any failure.
            }
        }
コード例 #28
0
        /// <summary>
        ///     The load local mods.
        /// </summary>
        /// 
        public void LoadMods(bool overrride = false)
        {
            var watch = Stopwatch.StartNew();

            if (Directory.Exists(modsDirectory))
            {
                watch.Restart();

                if (overrride)
                    this._modsList.Clear();

                List<string> leftovers = this.modsList.Keys.ToList();

                string[] pdmods = Directory.GetFiles(modsDirectory, "*.pdmod");

                //System.Threading.Tasks.Parallel.ForEach(pdmods, file =>
                foreach (string file in pdmods)
                {
                    if (!File.Exists(file))
                        return;//continue;

                    if (LoadSingleMod(file))
                    {
                        leftovers.Remove(file);
                    }
                }//);

                watch.Stop();
                Console.WriteLine("LoadLocalMods.pdmods - " + watch.ElapsedMilliseconds + " ms");

                watch.Restart();
                foreach (string left in leftovers)
                    RemoveModsList(left);

                watch.Stop();
                Console.WriteLine("LoadLocalMods.pdmods.leftovers - " + watch.ElapsedMilliseconds + " ms");

            }
            else
            {
                if (this.CanCreateDirectory(modsDirectory))
                {
                    Directory.CreateDirectory(modsDirectory);
                }
            }

            watch.Restart();

            //load in override folder
            if (Directory.Exists(Path.Combine(StaticStorage.settings.AssetsFolder, "mod_overrides")))
            { 
                List<BundleMod> mod_overrides_mods = new List<BundleMod>();
                string[] mod_overrides = Directory.EnumerateDirectories(Path.Combine(StaticStorage.settings.AssetsFolder, "mod_overrides")).ToArray();

                foreach (string mo in mod_overrides)
                {
                    if (!Directory.Exists(mo))
                        continue;//continue;
                    if (new DirectoryInfo(mo).Name == "Bundle_Modder_Shared")
                        continue;//continue;

                    string[] allfiles = System.IO.Directory.GetFiles(mo, "*.*", System.IO.SearchOption.AllDirectories);
                    BundleMod mo_mod = new BundleMod();
                    mo_mod.Name = new DirectoryInfo(mo).Name;
                    mo_mod.Author = "<UNKNOWN>";
                    mo_mod.Description = "This mod is installed in \"mod_overrides\" folder. No description for this mod is availiable. This mod was not matched with any local mods. You can only uninstall this mod.";
                    mo_mod.file = mo;
                    mo_mod.status = BundleMod.ModStatus.Unrecognized;
                    mo_mod.type = BundleMod.ModType.mod_override;
                    mo_mod.actionStatus = BundleMod.ModActionStatus.Missing;
                    mo_mod.UtilizesOverride = true;

                    if (File.Exists(Path.Combine(mo, "mod.txt")))
                    {
                        try
                        {
                            OverrideMod overrideModInformation = OverrideMod.Deserialize(File.ReadAllText(Path.Combine(mo, "mod.txt")));

                            if(!String.IsNullOrWhiteSpace(overrideModInformation.Name))
                                mo_mod.Name = overrideModInformation.Name;
                            
                            if(!String.IsNullOrWhiteSpace(overrideModInformation.Author))
                                mo_mod.Author = overrideModInformation.Author;

                            if (!String.IsNullOrWhiteSpace(overrideModInformation.Description))
                                mo_mod.Description = overrideModInformation.Description;
                            
                            mo_mod.status = BundleMod.ModStatus.Installed;
                            mo_mod.actionStatus = BundleMod.ModActionStatus.None;
                        }
                        catch(Exception exc)
                        {
                        }
                    }

                    foreach (string mo_entry in allfiles)
                    {
                        if (mo_entry.EndsWith("mod.txt"))
                            continue;
                        
                        BundleRewriteItem mo_bri = new BundleRewriteItem();
                        string filepath = mo_entry.Substring(mo.Length + 1).Replace('\\', '/');
                        string[] pathelements = filepath.Split('.');
                        if (pathelements.Length > 3)
                            continue;

                        string entrypath = pathelements[0];
                        if (pathelements.Length == 2)
                        {
                            mo_bri.BundlePath = Hash64.HashString(pathelements[0]);
                            mo_bri.BundleExtension = Hash64.HashString(pathelements[1]);
                        }
                        else if (pathelements.Length == 3)
                        {
                            mo_bri.BundlePath = Hash64.HashString(pathelements[0]);
                            UInt32 lang = 0;
                            if (UInt32.TryParse(pathelements[1], out lang))
                                mo_bri.BundleLanguage = lang;
                            mo_bri.BundleExtension = Hash64.HashString(pathelements[2]);
                            mo_bri.IsLanguageSpecific = true;
                        }
                        else
                            continue;
                        mo_bri.ModName = mo_mod.Name;
                        mo_bri.ModAuthor = mo_mod.Author;
                        mo_bri.ModDescription = mo_mod.Description;
                        mo_bri.ReplacementFile = "";
                        if (mo_bri.isOverrideable()
                            //&& !bri.ReplacementFile.EndsWith(".script")
                            )
                        {

                            if (string.IsNullOrEmpty(HashIndex.GetUnhashed(mo_bri.BundlePath)) ||
                                string.IsNullOrEmpty(HashIndex.GetUnhashed(mo_bri.BundleExtension))
                                )
                            {
                                continue;
                            }
                        }
                        mo_mod.ItemQueue.Add(mo_bri);
                    }
                    mod_overrides_mods.Add(mo_mod);
                }

                //check vs others
                Dictionary<string, BundleMod> temporarylocalModsList_master = this.modsList;

                foreach (BundleMod mo_bm in mod_overrides_mods)
                {
                    bool modMatch = false;

                    List<BundleMod> matched_mods = temporarylocalModsList_master.Values.Where(mod => mod.getEscapedName().Equals(mo_bm.Name) || mod.Name.Equals(mo_bm.Name)).ToList();

                    foreach (BundleMod bm in matched_mods)
                    {
                        modMatch = true;
                        if (mo_bm.ItemQueue.Count > bm.ItemQueue.Count) //the override mod contains too many files, not equal
                        {
                            mo_bm.canInstall = false;
                            mo_bm.canUninstall = true;
                            mo_bm.actionStatus = BundleMod.ModActionStatus.Missing;
                            mo_bm.status = BundleMod.ModStatus.Unrecognized;

                            AddModsList(mo_bm.file, mo_bm);
                        }
                        else
                        {
                            bool[] mo_checklist = new bool[mo_bm.ItemQueue.Count];

                            int checklist_i = 0;
                            bool mo_onlyfolder = !(bm.ItemQueue.Any(x => !x.isOverrideable())); //isOverradable
                            foreach (BundleRewriteItem mo_bri in mo_bm.ItemQueue)
                            {
                                if (bm.ItemQueue.Any(x => x.BundlePath == mo_bri.BundlePath && x.BundleExtension == mo_bri.BundleExtension))
                                    mo_checklist[checklist_i] = true;
                                checklist_i++;
                            }

                            bool mo_equal = !mo_checklist.Any(x => !x);
                            /*
                            for (checklist_i = 0; mo_equal && checklist_i < mo_bm.ItemQueue.Count; checklist_i++)
                                if (!mo_checklist[checklist_i])
                                    mo_equal = false;
                            */
                            if (!mo_equal)
                            {
                                mo_bm.canInstall = false;
                                mo_bm.canUninstall = true;
                                mo_bm.actionStatus = BundleMod.ModActionStatus.Missing;
                                mo_bm.status = BundleMod.ModStatus.Unrecognized;

                                AddModsList(mo_bm.file, mo_bm);
                            }
                            else
                            {
                                if (mo_onlyfolder || InstalledModsListContains(bm) > -1)
                                {
                                    bm.status = BundleMod.ModStatus.Installed;//installed
                                }
                                else
                                {
                                    bm.actionStatus = BundleMod.ModActionStatus.ForcedReinstall;
                                    bm.status = BundleMod.ModStatus.ParticallyInstalled;//installed

                                    foreach (BundleRewriteItem bri in bm.ItemQueue)
                                        bri.toReinstall = true;
                                }
                            }
                        }
                    }

                    if (!modMatch)
                    {
                        mo_bm.canInstall = false;
                        mo_bm.canUninstall = true;

                        AddModsList(mo_bm.file, mo_bm);
                    }

                }
            }

            watch.Stop();
            Console.WriteLine("LoadLocalMods.overrides - " + watch.ElapsedMilliseconds + " ms");

            watch.Restart();

            //BLT Mods
            if ( Directory.Exists( Path.Combine( StaticStorage.settings.AssetsFolder, "..", "mods") ) )
            {
                if( Directory.Exists( Path.Combine( StaticStorage.settings.AssetsFolder, "..", "mods", "base") ) )
                {
                    List<string> bltmods = Directory.EnumerateDirectories(Path.Combine(StaticStorage.settings.AssetsFolder, "..", "mods")).ToList();

                    foreach (string bltmod in bltmods)
                    {
                        if (!Directory.Exists(bltmod))
                            continue;

                        if (Path.GetFileNameWithoutExtension(bltmod).Equals("log") || Path.GetFileNameWithoutExtension(bltmod).Equals("base"))
                            continue;

                        if (!File.Exists(Path.Combine(bltmod, "mod.txt")))
                            continue;


                        BundleMod blt_mod = new BundleMod();
                        blt_mod.Name = new DirectoryInfo(bltmod).Name;
                        blt_mod.Author = "<UNKNOWN>";
                        blt_mod.Description = "This is a BLT Hook mod. No description for this mod is availiable. This mod doesn't have a proper description. You can enable/disable this mod as well as uninstall it.";
                        blt_mod.file = bltmod;
                        blt_mod.status = BundleMod.ModStatus.Installed;
                        blt_mod.type = BundleMod.ModType.lua;
                        blt_mod.actionStatus = BundleMod.ModActionStatus.None;
                        blt_mod.UtilizesOverride = false;
                        blt_mod.UtilizesBundles = false;
                        blt_mod.enabled = true;

                        try
                        {
                            FileStream bltModfs = new FileStream(Path.Combine(bltmod, "mod.txt"), FileMode.Open);
                            using (StreamReader bltModsr = new StreamReader(bltModfs))
                            {
                                try
                                {
                                    //JsonConvert
                                    dynamic jsonDe = JsonConvert.DeserializeObject(bltModsr.ReadToEnd());
                                    //dynamic jsonDe = null;
                                    if (jsonDe != null)
                                    {
                                        if (jsonDe.name != null)
                                        {
                                            blt_mod.Name = jsonDe.name;
                                        }
                                        if (jsonDe.author != null)
                                        {
                                            blt_mod.Author = jsonDe.author;
                                        }
                                        if (jsonDe.description != null)
                                        {
                                            blt_mod.Description = jsonDe.description;
                                        }
                                    }
                                }
                                catch (Exception exc)
                                {
                                    blt_mod.Description += " Failed parsing mods.txt of " + Path.GetFileNameWithoutExtension(bltmod) + ", Message: " + exc.Message;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            blt_mod.Description += " Failed parsing mods.txt of " + Path.GetFileNameWithoutExtension(bltmod) + ", Message: " + e.Message;
                        }
                        AddModsList(bltmod, blt_mod, true);
                    }
                }

                LoadBLTModManagement();
            }

            watch.Stop();
            Console.WriteLine("LoadLocalMods.blt_mods - " + watch.ElapsedMilliseconds + " ms");
        }
コード例 #29
0
 public static string GetShaderInfoFileName(Hash64 hash)
 {
     return(CEngine.Instance.FileManager.DDCDirectory + "shaderinfo/" + hash.ToString().ToLower() + ".xml");
 }
コード例 #30
0
            public void VisitEmbedTag(EmbedTag tag)
            {
                AttachmentData attachment = testStepRun.TestLog.GetAttachment(tag.AttachmentName);

                if (attachment == null)
                {
                    return;
                }

                string src = formatter.GetAttachmentFileInfo(testStepRun.Step.Id, attachment).FullName;

                writer.Write("<div class=\"logStreamEmbed\">");
                if (attachment.ContentType.StartsWith("image/"))
                {
                    writer.Write("<a href=\"");
                    writer.Write(src);
                    writer.Write("\" class=\"attachmentLink\">");
                    writer.Write("<img class=\"embeddedImage\" src=\"");
                    WriteHtmlEncoded(writer, src);
                    writer.Write("\" alt=\"Attachment: ");
                    WriteHtmlEncoded(writer, attachment.Name);
                    writer.Write("\" /></a>");
                }
                else if ((attachment.ContentType.StartsWith("text/html") || attachment.ContentType.StartsWith("text/xhtml")) &&
                         attachment.IsText)
                {
                    writer.Write(attachment.GetText());
                }
                else if (attachment.ContentType.StartsWith("text/") &&
                         attachment.IsText)
                {
                    writer.Write("<pre>");
                    WriteHtmlEncodedWithBreaks(writer, attachment.GetText());
                    writer.Write("</pre>");
                }
                else if (flashEnabled && attachment.ContentType.StartsWith(MimeTypes.FlashVideo))
                {
                    string placeholderId = "video-" + Hash64.CreateUniqueHash();
                    writer.Write("<div id=\"");
                    writer.Write(placeholderId);
                    writer.Write("\">");

                    writer.Write("<script type=\"text/javascript\">");
                    writer.Write("swfobject.embedSWF('");
                    WriteHtmlEncoded(writer, new Uri(Path.Combine(formatter.jsDir, "player.swf")).ToString());
                    writer.Write("', '");
                    writer.Write(placeholderId);
                    writer.Write("', '400', '300', '9.0.98', '");
                    WriteHtmlEncoded(writer, new Uri(Path.Combine(formatter.jsDir, "expressInstall.swf")).ToString());
                    writer.Write("', {file: '");
                    WriteHtmlEncoded(writer, new Uri(src).ToString());
                    writer.Write("'}, {allowfullscreen: 'true', allowscriptaccess: 'always'}, {id: '");
                    writer.Write(placeholderId);
                    writer.Write("'})");
                    writer.Write("</script>");

                    writer.Write("</div>");
                }
                else
                {
                    writer.Write("Attachment: <a href=\"");
                    WriteHtmlEncoded(writer, src);
                    writer.Write("\" class=\"attachmentLink\">");
                    WriteHtmlEncoded(writer, attachment.Name);
                    writer.Write("</a>");
                }
                writer.Write("</div>");
            }
コード例 #31
0
 public void writePackage(String name)
 {
     UInt64 hashed_name = Hash64.HashString(name);
 }
コード例 #32
0
        private string GetTemporaryConfigurationFilePath()
        {
            switch (ConfigurationFileLocation)
            {
            case ConfigurationFileLocation.None:
                return(null);

            case ConfigurationFileLocation.Temp:
                return(SpecialPathPolicy.For("Hosting").CreateTempFileWithUniqueName().FullName);

            case ConfigurationFileLocation.AppBase:
                if (applicationBaseDirectory == null)
                {
                    throw new InvalidOperationException("The configuration file was to be written to the application base directory but none was specified in the host setup.");
                }

                for (; ;)
                {
                    string path = Path.Combine(GetCanonicalApplicationBaseDirectory(null), Hash64.CreateUniqueHash() + ".tmp.config");
                    if (!File.Exists(path))
                    {
                        return(path);
                    }
                }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #33
0
        public void PopulateCatalog_WhenPluginXmlContainsPreprocessorInstructions_AppliesThem()
        {
            string pluginContents = "<plugin pluginId=\"pluginId\" xmlns=\"http://www.gallio.org/\"><traits><?ifdef A?><name>A</name><?endif?><?ifdef B?><property>B</property><?endif?></traits></plugin>";

            PluginLoaderTest.RunWithTemporaryPluginFile((pluginDir, pluginFile) =>
            {
                Guid installationId = Guid.NewGuid();
                var loader = new CachingPluginLoader();
                loader.InstallationId = installationId;
                loader.AddPluginPath(pluginFile);
                loader.DefinePreprocessorConstant("A");

                Hash64 hash = new Hash64().Add(pluginFile).Add("A").Add(installationId.ToString());
                var cacheDir = CachingPluginLoader.GetCurrentUserPluginCacheDir();
                string cacheFilePath = Path.Combine(cacheDir, hash + ".xml");

                if (System.IO.File.Exists(cacheFilePath))
                    System.IO.File.Delete(cacheFilePath);

                // First pass.
                {
                    Plugin plugin = null;
                    var catalog = MockRepository.GenerateMock<IPluginCatalog>();
                    catalog.Expect(x => x.AddPlugin(null, null)).IgnoreArguments()
                        .Do((Action<Plugin, DirectoryInfo>)delegate(Plugin pluginArg, DirectoryInfo baseDirectoryArg)
                        {
                            plugin = pluginArg;
                        });

                    loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance());

                    catalog.VerifyAllExpectations(); // added one plugin

                    Assert.AreEqual(new PropertySet() { { "name", "A" } }, plugin.Traits.PropertySet);
                }

                // Check cache file.
                {
                    Assert.IsTrue(File.Exists(cacheFilePath));

                    Cache cache = Assert.XmlDeserialize<Cache>(File.ReadAllText(cacheFilePath));

                    Assert.AreEqual(installationId.ToString(), cache.InstallationId);
                    Assert.AreEqual(1, cache.PluginInfos.Count);
                    Assert.AreEqual(pluginDir, cache.PluginInfos[0].BaseDirectory);
                    Assert.AreEqual("pluginId", cache.PluginInfos[0].Plugin.PluginId);
                    Assert.AreEqual(pluginFile, cache.PluginInfos[0].PluginFile);
                    Assert.AreEqual(File.GetLastWriteTimeUtc(pluginFile), cache.PluginInfos[0].PluginFileModificationTime);
                }

                // Second pass should restore from cache.
                {
                    Plugin plugin = null;
                    var catalog = MockRepository.GenerateMock<IPluginCatalog>();
                    catalog.Expect(x => x.AddPlugin(null, null)).IgnoreArguments()
                        .Do((Action<Plugin, DirectoryInfo>)delegate(Plugin pluginArg, DirectoryInfo baseDirectoryArg)
                        {
                            plugin = pluginArg;
                        });

                    loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance());

                    catalog.VerifyAllExpectations(); // added one plugin

                    Assert.AreEqual(new PropertySet() { { "name", "A" } }, plugin.Traits.PropertySet);
                }
            }, pluginContents);
        }