예제 #1
0
파일: ccUtil.cs 프로젝트: uuware/difftool
        static public string readResource(System.Reflection.Assembly asse, string sFileFullName)
        {
            string sTxt = string.Empty;

            try
            {
                System.IO.Stream strm = asse.GetManifestResourceStream(sFileFullName);
                if (strm == null)
                {
                    for (int i = 0; i < asse.GetManifestResourceNames().Length; i++)
                    {
                        if (asse.GetManifestResourceNames()[i].EndsWith("." + sFileFullName))
                        {
                            strm = asse.GetManifestResourceStream(asse.GetManifestResourceNames()[i]);
                            break;
                        }
                    }
                }
                if (strm != null)
                {
                    byte[] srcByte = new byte[strm.Length];
                    strm.Read(srcByte, 0, (int)strm.Length);
                    //sTxt = new System.IO.StreamReader(strm,System.Text.Encoding.Default).ReadToEnd();
                    strm.Close();
                    sTxt = AutoEncoding(srcByte);
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return(sTxt);
        }
예제 #2
0
        public static string GetResourceName(System.Reflection.Assembly asm, string resourceName)
        {
            if (resourceName == null)
            {
                return(null);
            }

#if EXACT
            foreach (string thisRessourceName in asm.GetManifestResourceNames())
            {
                if (System.StringComparer.OrdinalIgnoreCase.Equals(thisRessourceName, resourceName))
                {
                    return(thisRessourceName);
                } // End if (thisRessourceName != null && thisRessourceName.EndsWith(resourceName, System.StringComparison.OrdinalIgnoreCase))
            }     // Next thisRessourceName
#endif

            foreach (string thisRessourceName in asm.GetManifestResourceNames())
            {
                if (thisRessourceName.EndsWith(resourceName, System.StringComparison.OrdinalIgnoreCase))
                {
                    return(thisRessourceName);
                } // End if (thisRessourceName != null && thisRessourceName.EndsWith(resourceName, System.StringComparison.OrdinalIgnoreCase))
            }     // Next thisRessourceName

            return(resourceName);
        } // End Function GetResourceName
 // 音声ファイルのリソース名指定に誤りがないかチェックをする
 private bool IsContainsResource(System.Reflection.Assembly assembly, string name)
 {
     if (assembly.GetManifestResourceNames().Contains(name))
     {
         return(true);
     }
     Console.WriteLine($"name : {name} はリソースに存在しません。");
     Console.WriteLine("リソースに含まれるファイル:");
     foreach (var resoureName in assembly.GetManifestResourceNames())
     {
         Console.WriteLine(resoureName);
     }
     return(false);
 }
예제 #4
0
        /// <summary>
        /// Returns a <see cref="Parser"/> instance based on the embedded regex definitions.
        /// <remarks>The embedded regex definitions may be outdated. Consider passing in external yaml definitions using <see cref="Parser.FromYaml"/> or
        /// <see cref="Parser.FromYamlFile"/></remarks>
        /// </summary>
        /// <returns></returns>
        public static Parser GetDefault()
        {
            System.Reflection.Assembly asm = typeof(Parser).Assembly;

            string yaml = null;

            foreach (string str in asm.GetManifestResourceNames())
            {
                if (str.EndsWith("UAParser.regexes.yaml", System.StringComparison.OrdinalIgnoreCase))
                {
                    yaml = str;
                    break;
                } // End if(str.EndsWith("UAParser.regexes.yaml", System.StringComparison.OrdinalIgnoreCase))
            }     // Next str


            using (System.IO.Stream strm = asm.GetManifestResourceStream(yaml))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(strm))
                {
                    yaml = sr.ReadToEnd();
                } // End Using sr
            }     // End Using strm

            return(new Parser(new MinimalYamlParser(yaml)));



            /*
             * using (var stream = typeof(Parser).Assembly.GetManifestResourceStream("UAParser.regexes.yaml"))
             * // ReSharper disable once AssignNullToNotNullAttribute
             * using (var reader = new StreamReader(stream))
             *  return new Parser(new MinimalYamlParser(reader.ReadToEnd()));
             */
        }
예제 #5
0
파일: SQL.cs 프로젝트: sarasara100/Pdf2Svg
        } // End Function GetDbType

        public static string GetEmbeddedSqlScript(string strScriptName, ref System.Reflection.Assembly ass)
        {
            string strReturnValue = null;

            bool bNotFound = true;

            foreach (string strThisRessourceName in ass.GetManifestResourceNames())
            {
                if (strThisRessourceName != null && strThisRessourceName.EndsWith(strScriptName, StringComparison.OrdinalIgnoreCase))
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(ass.GetManifestResourceStream(strThisRessourceName)))
                    {
                        bNotFound      = false;
                        strReturnValue = sr.ReadToEnd();
                        break;
                    }
                } // End if (strThisRessourceName != null && strThisRessourceName.EndsWith(strScriptName, StringComparison.OrdinalIgnoreCase) )
            }

            if (bNotFound)
            {
                throw new System.Exception("No script called \"" + strScriptName + "\" found in embedded ressources.");
            }

            return(strReturnValue);
        } // End Function GetEmbeddedSqlScript
예제 #6
0
        private ResourceManager InternalGetResourceManager(Type resourceType, string resourceName)
        {
            ResourceManager resourceManager = null;

            System.Reflection.Assembly assembly = resourceType.Assembly;
            if (string.IsNullOrEmpty(resourceName))
            {
                string[] manifestResourceNames = assembly.GetManifestResourceNames();
                for (int i = 0; i < manifestResourceNames.Length; ++i)
                {
                    string resName = manifestResourceNames[i];
                    if (resName.EndsWith(ResourcesExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        resName = resName.Substring(0, resName.Length - ResourcesExtension.Length);
                    }
                    if (resName == resourceType.Name || resName == resourceType.FullName)
                    {
                        resourceName = resName;
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(resourceName))
            {
                string resourceKey = string.Concat(assembly.FullName, " | ", resourceName);
                if (!_resourceManagers.TryGetValue(resourceKey, out resourceManager) || resourceManager == null)
                {
                    resourceManager = new ResourceManager(resourceName, assembly);
                    _resourceManagers[resourceKey] = resourceManager;
                }
            }
            return(resourceManager);
        }
예제 #7
0
        public void DrawO(int i, int j)
        {
            System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();

            string[] s = executingAssembly.GetManifestResourceNames();

            System.IO.Stream stream = executingAssembly.GetManifestResourceStream("tic_tac_toe.images.o.png");
            byte[]           b      = new byte[stream.Length];
            stream.Read(b, 0, (int)stream.Length);

            var img = new BitmapImage();

            using (var mem = new System.IO.MemoryStream(b))
            {
                mem.Position = 0;
                img.BeginInit();
                img.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                img.CacheOption   = BitmapCacheOption.OnLoad;
                img.UriSource     = null;
                img.StreamSource  = mem;
                img.EndInit();
            }
            img.Freeze();
            imageCells[i, j].Source = img;
        }
예제 #8
0
        private void InitializeForm()
        {
            Text = Program.MonitorTitle;
            Size = new Size(640, 400);
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            string iconResourceName             = assembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith("Program.ico"));

            if (!string.IsNullOrWhiteSpace(iconResourceName))
            {
                Icon = new Icon(assembly.GetManifestResourceStream(iconResourceName));
            }
            _MonitorRichTextBox = new MonitorRichTextBox()
            {
                ReadOnly       = true,
                Dock           = DockStyle.Fill,
                BorderStyle    = BorderStyle.None,
                Font           = new Font("Consolas", 11),
                BackColor      = Program.BackColor,
                ForeColor      = Program.ForeColor,
                ScrollBars     = RichTextBoxScrollBars.Both,
                LanguageOption = RichTextBoxLanguageOptions.DualFont,
            };
            Controls.Add(_MonitorRichTextBox);

            StartNormalMonitorProcess();

            if (Program.MonitorType == MonitorType.File)
            {
                StartFileMonitorProcess();
            }
        }
예제 #9
0
        private static string GetEmbeddedResource(System.Reflection.Assembly asm, string resourceName)
        {
            string resource = null;

            string foundResourceName = null;

            foreach (string thisResourceName in asm.GetManifestResourceNames())
            {
                if (thisResourceName.EndsWith(resourceName, System.StringComparison.OrdinalIgnoreCase))
                {
                    foundResourceName = thisResourceName;
                    break;
                }
            } // Next thisResourceName

            if (foundResourceName == null)
            {
                throw new System.IO.InvalidDataException("The provided resourceName is not present.");
            }

            using (System.IO.Stream strm = asm.GetManifestResourceStream(foundResourceName))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(strm))
                {
                    resource = sr.ReadToEnd();
                } // End Using sr
            }     // End Using strm

            return(resource);
        } // End Function GetEmbeddedResource
        public static string GetText(string name)
        {
            string text = "";

            try
            {
                System.Reflection.Assembly oAsm = System.Reflection.Assembly.GetExecutingAssembly();

                string fn = "";
                foreach (string n in oAsm.GetManifestResourceNames())
                {
                    if (n.Contains(name))
                    {
                        fn = n;
                        break;
                    }
                }
                Stream       oStrm = oAsm.GetManifestResourceStream(fn);
                StreamReader oRdr  = new StreamReader(oStrm);
                text = oRdr.ReadToEnd();
            }
            catch (Exception ex)
            {
                FileSystem.AppendDebug("Error while getting text from resource", ex);
            }

            return(text);
        }
예제 #11
0
        /// <summary>
        /// Writes the usage to the console
        /// </summary>
        /// <returns>string containing the usage text to be displayed</returns>
        private static string Usage()
        {
            try
            {
                System.Reflection.Assembly assemblyID = System.Reflection.Assembly.GetExecutingAssembly();
                string[]               resNames       = assemblyID.GetManifestResourceNames();
                System.IO.Stream       streamID       = assemblyID.GetManifestResourceStream("DumpConnection.usg.txt");
                System.IO.StreamReader sr             = new System.IO.StreamReader(streamID);

                string usage = sr.ReadToEnd();
                Console.WriteLine(usage);

                // tack on the version info:
                Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

                string ver = "DumpConnection.exe {0}.{1}";

                Console.WriteLine(ver.FormatString(v.Major.ToString(), v.Minor.ToString()));

                return(usage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error displaying usage text: ");
                Console.WriteLine(ex.StackTrace);
                Trace.WriteLine(ex.StackTrace);
                return(string.Empty);
            }
        }
예제 #12
0
        private static System.Reflection.Assembly ResolveAssembly(object sender, ResolveEventArgs args)
        {
            System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();

            string name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";

            var files = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name));


            if (files.Count() > 0)
            {
                string fileName = files.First();

                using (System.IO.Stream stream = thisAssembly.GetManifestResourceStream(fileName))
                {
                    if (stream != null)
                    {
                        byte[] data = new byte[stream.Length];

                        stream.Read(data, 0, data.Length);

                        return(System.Reflection.Assembly.Load(data));
                    }
                }
            }


            return(null);
        }
예제 #13
0
        public TemplateCommand(TemplateCommandOptions options)
        {
            if (options.Commands == null || options.Commands.Count == 0 || !Enum.TryParse(options.Commands[0], true, out _commandType))
            {
                throw new InvalidOptionException("Neither 'list' nor 'export' is found. You must specify a command type.");
            }
            switch (_commandType)
            {
            case TemplateCommandType.Export:
                _exportTemplateConfig = new ExportTemplateConfig
                {
                    All          = options.All,
                    OutputFolder = options.OutputFolder,
                    Templates    = options.Commands.Skip(1).ToArray()
                };
                if (_exportTemplateConfig.Templates.Length == 0)
                {
                    _exportTemplateConfig.All = true;
                }
                break;
            }
            _assembly = this.GetType().Assembly;
            var templateRegex = new Regex($"{Regex.Escape(_assembly.GetName().Name)}\\.{Regex.Escape(Constants.EmbeddedTemplateFolderName)}\\.([\\S.]+)\\.zip");

            _templates = _assembly.GetManifestResourceNames().Select(s => templateRegex.Match(s)).Where(s => s.Success).Select(s => s.Groups[1].Value).ToArray();
        }
 public static void AddEnvironmentConfiguration <TResource>(
     this IServiceCollection serviceCollection,
     Func <EnvironmentChooser> environmentChooserFactory)
 {
     serviceCollection.AddSingleton <IConfiguration>((s) =>
     {
         EnvironmentChooser environementChooser = environmentChooserFactory();
         Uri uri = new Uri(s.GetRequiredService <NavigationManager>().ToAbsoluteUri("").ToString());
         System.Reflection.Assembly assembly = typeof(TResource).Assembly;
         string environment      = environementChooser.GetCurrent(uri);
         string[] ressourceNames = new[]
         {
             assembly.GetName().Name + ".Configuration.appsettings.json",
             assembly.GetName().Name + ".Configuration.appsettings." + environment + ".json"
         };
         ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
         configurationBuilder.AddInMemoryCollection(new Dictionary <string, string>()
         {
             { "Environment", environment }
         });
         foreach (string resource in ressourceNames)
         {
             if (assembly.GetManifestResourceNames().Contains(resource))
             {
                 configurationBuilder.AddJsonFile(
                     new InMemoryFileProvider(assembly.GetManifestResourceStream(resource)), resource, false, false);
             }
         }
         return(configurationBuilder.Build());
     });
 }
예제 #15
0
        /// <summary>
        /// Loads given type <typeparamref name="T"/> from provided <paramref name="path"/>.
        /// Will throw <see cref="System.IO.FileNotFoundException"/> in case of the <paramref name="path"/> being not existing.
        /// Will throw <see cref="InvalidCastException"/> in case of the item behind <paramref name="path"/> is not of type <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T"><see cref="class"/> type which will be loaded from <paramref name="assembly"/>.</typeparam>
        /// <param name="assembly">The <see cref="System.Reflection.Assembly"/> where to look the <paramref name="path"/> up.</param>
        /// <param name="path">Path to the xaml file. 'Example: ArmA.Studio.Data.Configuration.StringItem.xaml' </param>
        /// <returns></returns>
        protected static T LoadFromEmbeddedResource <T>(System.Reflection.Assembly assembly, string path) where T : class
        {
            var resNames = from name in assembly.GetManifestResourceNames() where name.EndsWith(".xaml") where name.Equals(path) select name;

            foreach (var res in resNames)
            {
                var resSplit = res.Split('.');
                var header   = resSplit[resSplit.Count() - 2];
                using (var stream = assembly.GetManifestResourceStream(res))
                {
                    try
                    {
                        var obj = XamlReader.Load(stream);
                        if (!(obj is T))
                        {
                            throw new InvalidCastException();
                        }
                        return(obj as T);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            throw new System.IO.FileNotFoundException();
        }
예제 #16
0
        protected IEnumerable <SourceFile> GenerateStaticSourceFiles()
        {
            System.Reflection.Assembly assembly = GetType().Assembly;
            string[] codeFiles = assembly.GetManifestResourceNames();

            foreach (string codeFile in codeFiles)
            {
                int prefixIndex = codeFile.LastIndexOf("CodeResources");
                if (prefixIndex > 0)
                {
                    string relative = codeFile.Substring(prefixIndex + "CodeResources.".Length);

                    string[] split = relative.Split('.');
                    if (split.Length >= 2)
                    {
                        string fileName   = $"{split[split.Length - 2]}.{split[split.Length - 1]}";
                        string folderPath = string.Empty;
                        if (split.Length > 2)
                        {
                            folderPath = string.Join("\\", split.Take(split.Length - 2));
                        }

                        using (Stream stream = assembly.GetManifestResourceStream(codeFile))
                        {
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                yield return(new SourceFile {
                                    FileName = Path.Combine(folderPath, fileName), SourceCode = reader.ReadToEnd()
                                });
                            }
                        }
                    }
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Writes the usage to the console
        /// </summary>
        /// <returns>string containing the usage text to be displayed</returns>
        private static string Usage()
        {
            try
            {
                System.Reflection.Assembly assemblyID = System.Reflection.Assembly.GetExecutingAssembly();
                string[]               resNames       = assemblyID.GetManifestResourceNames();
                System.IO.Stream       streamID       = assemblyID.GetManifestResourceStream("Umbriel.GIS.Metadata.GISMetaLinq.usg.txt");
                System.IO.StreamReader sr             = new System.IO.StreamReader(streamID);

                string usage = sr.ReadToEnd();
                Console.WriteLine(usage);

                // tack on the version info:
                string  tail;
                Version v   = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                string  ver = v.Major.ToString() + "." + v.Minor.ToString() + "." + v.Revision.ToString() + "." + v.Build.ToString();

                tail = "GISMetaLinq.exe " + ver;

                Console.WriteLine(tail);

                return(usage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error displaying usage text: ");
                Console.WriteLine(ex.StackTrace);
                Trace.WriteLine(ex.StackTrace);
                return(string.Empty);
            }
        }
예제 #18
0
        public static void LoadResources(string strCulture)
        {
            try
            {
                System.Reflection.Assembly targetAsmbly = System.Reflection.Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "PACT.Globalization.dll");
                System.Reflection.Assembly satAsmbly    = targetAsmbly.GetSatelliteAssembly(new CultureInfo(strCulture));
                string[] resources = satAsmbly.GetManifestResourceNames();
                string   strName   = "";
                string   strValue  = "";
                UIResources.Clear();
                foreach (string resource in resources)
                {
                    string                baseName        = resource.Substring(0, resource.LastIndexOf('.'));
                    ResourceManager       resourceManager = new ResourceManager(baseName, satAsmbly);
                    ResourceSet           resourceSet     = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
                    IDictionaryEnumerator enumerator      = resourceSet.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        strName  = enumerator.Key.ToString();
                        strValue = enumerator.Value.ToString();
                        UIResources.Add(strName, strValue);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string GetText(string name)
        {
            string text = "";

            try
            {
                System.Reflection.Assembly oAsm = System.Reflection.Assembly.GetExecutingAssembly();

                string fn = "";
                foreach (string n in oAsm.GetManifestResourceNames())
                {
                    if (n.EndsWith("." + name))
                    {
                        fn = n;
                        break;
                    }
                }
                Stream       oStrm = oAsm.GetManifestResourceStream(fn);
                StreamReader oRdr  = new StreamReader(oStrm);
                text = oRdr.ReadToEnd();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(text);
        }
예제 #20
0
        public static string GetResource(System.Type t, string endsWith)
        {
            System.Reflection.Assembly ass = t.Assembly;

            string res = null;

            foreach (string str in ass.GetManifestResourceNames())
            {
                if (str.EndsWith(endsWith, System.StringComparison.OrdinalIgnoreCase))
                {
                    res = str;
                    break;
                } // End if(str.EndsWith(endsWith, System.StringComparison.OrdinalIgnoreCase))
            }     // Next str


            using (System.IO.Stream strm = ass.GetManifestResourceStream(res))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(strm))
                {
                    res = sr.ReadToEnd();
                } // End Using sr
            }     // End Using strm

            return(res);
        } // End Function GetResource
예제 #21
0
 public override bool DeleteAllDataBase()
 {
     System.Reflection.Assembly assCurrent = System.Reflection.Assembly.GetExecutingAssembly();
     // Getting all types in current assembly
     string[] arrStrAssembly = assCurrent.GetManifestResourceNames();
     foreach (string strCurrent in arrStrAssembly)
     {
         if (strCurrent.StartsWith("mdlDataBaseAccess.Tabelas"))
         {
             string strTableName = strCurrent.Substring("mdlDataBaseAccess.Tabelas.Xsd".Length);
             strTableName = strTableName.Substring(0, strTableName.Length - 4);
             strTableName = strTableName.Substring(0, 1).ToLower() + strTableName.Substring(1);
             if (strTableName == "tbModulos")
             {
                 continue;
             }
             string strSQL = GetDeleteFull(strTableName);
             vExecuteCommand(strSQL);
             if (m_excError != null)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #22
0
파일: Reader.cs 프로젝트: catonice/kudocode
        public static ConfigurationBuilder ConfigurationBuilder <TResource>(
            Func <EnvironmentChooser> environmentChooserFactory)
        {
            var environementChooser = environmentChooserFactory();
            var environment         = "development";

            try
            {
                //var uri = new Uri(s.GetRequiredService<NavigationManager>().GetAbsoluteUri());
                // environment = environementChooser.GetCurrent(uri);
            }
            catch (Exception)
            {
            }

            System.Reflection.Assembly assembly = typeof(TResource).Assembly;
            var ressourceNames = new[]
            {
                assembly.GetName().Name + ".appsettings.json",
                assembly.GetName().Name + ".appsettings." + environment + ".json"
            };
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(new Dictionary <string, string>()
            {
                { "Environment", environment }
            });
            Console.WriteLine(string.Join(",", assembly.GetManifestResourceNames()));
            Console.WriteLine(string.Join(",", ressourceNames));
            foreach (var resource in ressourceNames)
            {
                if (((IList)assembly.GetManifestResourceNames()).Contains(resource))
                {
                    using (var stream = assembly.GetManifestResourceStream(resource))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            configurationBuilder.AddJsonFile(
                                new InMemoryFileProvider(reader.ReadToEnd()), resource, false, false);
                            Console.WriteLine($"ADDED: {resource}");
                        }
                    }
                }
            }

            return(configurationBuilder);
        }
예제 #23
0
        public static string GetResourceName(this System.Reflection.Assembly assembly, string fileNameInAssembly)
        {
            var resName = from name in assembly.GetManifestResourceNames()
                          where name.ToLower().EndsWith(fileNameInAssembly.ToLower())
                          select name;

            return(resName.FirstOrDefault());
        }
예제 #24
0
        public void LoadManifestResource(System.Reflection.Assembly assembly)
        {
            string[] files     = assembly.GetManifestResourceNames();
            string   tmpFolder = "_tempview";

            if (!System.IO.Directory.Exists(tmpFolder))
            {
                Directory.CreateDirectory(tmpFolder);
            }
            foreach (string item in files)
            {
                int offset = item.IndexOf(".views");
                if (offset > 0)
                {
                    string url = GetResourceUrl(item.Substring(offset + 6, item.Length - offset - 6));
                    string ext = System.IO.Path.GetExtension(item).ToLower();
                    ext = ext.Substring(1, ext.Length - 1);
                    if (mExts.ContainsKey(ext))
                    {
                        string urlname  = url;
                        string filename = tmpFolder + System.IO.Path.DirectorySeparatorChar + item;
                        SaveTempFile(assembly, item, filename);
                        FileResource fr;
                        bool         nogzip    = !(Server.ServerConfig.NoGzipFiles.IndexOf(ext) >= 0);
                        bool         cachefile = Server.ServerConfig.CacheFiles.IndexOf(ext) >= 0;
                        if (Debug)
                        {
                            fr = new NoCacheResource(filename, urlname);
                            if (nogzip)
                            {
                                fr.GZIP = true;
                            }
                        }
                        else
                        {
                            if (cachefile)
                            {
                                fr = new FileResource(filename, urlname);
                            }
                            else
                            {
                                fr = new NoCacheResource(filename, urlname);
                                if (nogzip)
                                {
                                    fr.GZIP = true;
                                }
                            }
                        }
                        mResources[urlname] = fr;
                        fr.Load();
                        if (Server.EnableLog(EventArgs.LogType.Info))
                        {
                            Server.BaseServer.Log(EventArgs.LogType.Info, null, "load static resource " + urlname);
                        }
                    }
                }
            }
        }
        private void Initialize()
        {
            ILog logger = LogProvider.For <CosmosDbStorage>();

            // create database
            logger.Info($"Creating database : {database}");
            Task <DatabaseResponse> databaseTask = Client.CreateDatabaseIfNotExistsAsync(database);

            // create document collection
            Task <ContainerResponse> containerTask = databaseTask.ContinueWith(t =>
            {
                logger.Info($"Creating document collection : {collection}");
                Database resultDatabase = t.Result.Database;
                return(resultDatabase.CreateContainerIfNotExistsAsync(collection, "/type"));
            }, TaskContinuationOptions.OnlyOnRanToCompletion).Unwrap();

            // create stored procedures
            Task storedProcedureTask = containerTask.ContinueWith(t =>
            {
                Container = t.Result;
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                string[] storedProcedureFiles       = assembly.GetManifestResourceNames().Where(n => n.EndsWith(".js")).ToArray();
                foreach (string storedProcedureFile in storedProcedureFiles)
                {
                    logger.Info($"Creating storedprocedure : {storedProcedureFile}");
                    Stream stream = assembly.GetManifestResourceStream(storedProcedureFile);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        stream?.CopyTo(memoryStream);
                        Microsoft.Azure.Cosmos.Scripts.StoredProcedureProperties sp = new Microsoft.Azure.Cosmos.Scripts.StoredProcedureProperties
                        {
                            Body = Encoding.UTF8.GetString(memoryStream.ToArray()),
                            Id   = Path.GetFileNameWithoutExtension(storedProcedureFile)?
                                   .Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Last()
                        };

                        Task <Microsoft.Azure.Cosmos.Scripts.StoredProcedureResponse> spTask = Container.Scripts.ReplaceStoredProcedureAsync(sp);
                        spTask.ContinueWith(x =>
                        {
                            if (x.Status == TaskStatus.Faulted && x.Exception.InnerException is CosmosException ex && ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                            {
                                return(Container.Scripts.CreateStoredProcedureAsync(sp));
                            }

                            return(Task.FromResult(x.Result));
                        }).Unwrap().Wait();
                    }
                    stream?.Close();
                }
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            storedProcedureTask.Wait();
            if (storedProcedureTask.IsFaulted || storedProcedureTask.IsCanceled)
            {
                throw new ApplicationException("Unable to create the stored procedures", databaseTask.Exception);
            }
        }
예제 #26
0
        private System.IO.Stream GetResourceStream(string path)
        {
            // TODO: this needs to change
            System.Reflection.Assembly assembly = typeof(ResourceReader).Assembly;
            string assemblyPrefix = assembly.GetManifestResourceNames()[0].Split('.')[0];

            path = assemblyPrefix + "." + path.Replace('\\', '.').Replace('/', '.').TrimStart('.');
            return(assembly.GetManifestResourceStream(path));
        }
예제 #27
0
 private System.Drawing.Icon GetTrayIcon(string iconType)
 {
     lock (trayIconLock)
     {
         assembly = System.Reflection.Assembly.GetExecutingAssembly();
         var path = assembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(".Sources.Images.TrayIcon-" + iconType + ".ico"));
         System.IO.Stream stream = assembly.GetManifestResourceStream(path);
         return(new System.Drawing.Icon(stream));
     }
 }
예제 #28
0
        public static System.IO.Stream GetManifestResourceStreamIgnoreCase(this System.Reflection.Assembly assembly, string name)
        {
            var key = assembly.FullName + name;
            var r   = keyValuePairs.GetOrAdd(key, keyName =>
            {
                return(assembly.GetManifestResourceNames().FirstOrDefault(f => f.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
            });

            return(assembly.GetManifestResourceStream(r));
        }
예제 #29
0
		} // End Function DeserializeXmlFromEmbeddedRessource


        private static string FindName(System.Reflection.Assembly asm, string resourceName)
        {
            foreach (string thisResourceName in asm.GetManifestResourceNames())
            {
                if (thisResourceName.EndsWith(resourceName))
                    return thisResourceName;
            }

            return null;
        }
        /// <summary>
        /// Use Kelvin too
        /// </summary>
        /// <returns>the catalog deserialized from disk, or NULL</returns>
        public static Catalog Load()
        {
            if (Preferences.InMediumTrust)
            {
                try
                {
                    string xmlFileName = Path.GetDirectoryName(Preferences.CatalogFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + ".xml";
                    if (System.IO.File.Exists(xmlFileName))
                    {
                        Catalog c1 = Kelvin <Catalog> .FromXmlFile(xmlFileName);

                        return(c1);
                    }
                }
                catch (Exception ex)
                {     // [v6] : if cannot load from .DAT or .XML, try to load from compiled resource
                    try
                    { // http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=75
                        System.Reflection.Assembly a = System.Reflection.Assembly.Load("WebAppCatalogResource");
                        string[] resNames            = a.GetManifestResourceNames();

                        Catalog c2 = Kelvin <Catalog> .FromResource(a, resNames[0]);

                        return(c2);
                    }
                    catch (Exception e1)
                    {
                        throw new Exception("Searcharoo Catalog.Load() ", e1);
                    }
                }
                return(null);
            }
            else
            {   // hopefully in Full trust
                // using Binary serialization requires the Binder because of the embedded 'full name'
                // of the serializing assembly - all the above methods using Xml do not have this requirement
                if (System.IO.File.Exists(Preferences.CatalogFileName))
                {
                    object deserializedCatalogObject;
                    using (System.IO.Stream stream = new System.IO.FileStream(Preferences.CatalogFileName, System.IO.FileMode.Open))
                    {
                        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        //object m = formatter.Deserialize (stream); // This doesn't work, SerializationException "Cannot find the assembly <random name>"
                        formatter.Binder          = new CatalogBinder(); // This custom Binder is REQUIRED to find the classes in our current 'Temporary ASP.NET Files' assembly
                        deserializedCatalogObject = formatter.Deserialize(stream);
                    } //stream.Close();
                    Catalog catalog = deserializedCatalogObject as Catalog;
                    return(catalog);
                }
                else
                {
                    return(null);
                }
            }
        }