Beispiel #1
0
        private string GetVersion(System.Reflection.Assembly assembly)
        {
            switch (Type)
            {
            case AssemblyVersionType.File:
                return(assembly?.GetCustomAttribute <System.Reflection.AssemblyFileVersionAttribute>()?.Version);

            case AssemblyVersionType.Informational:
                return(assembly?.GetCustomAttribute <System.Reflection.AssemblyInformationalVersionAttribute>()?.InformationalVersion);

            default:
                return(assembly?.GetName().Version?.ToString());
            }
        }
Beispiel #2
0
        public static string GetText(string name)
        {
            string text = "";

            try
            {
                System.Reflection.Assembly oAsm = System.Reflection.Assembly.GetExecutingAssembly();
                Stream       oStrm = oAsm.GetManifestResourceStream(oAsm.GetName().Name + "." + name);
                StreamReader oRdr  = new StreamReader(oStrm);
                text = oRdr.ReadToEnd();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return(text);
        }
        void initialize(System.Reflection.Assembly assembly)
        {
            string groupName = null;

            object[] attrobjs = assembly.GetCustomAttributes(typeof(LocalizationAttribute), true /* inherit */);
            if (attrobjs != null && attrobjs.Length > 0 && attrobjs[0] != null) // focus on only the first.
            {
                LocalizationAttribute locAttr = (LocalizationAttribute)attrobjs[0];
                groupName = locAttr.locGroupName;
                if (groupName == null)
                {
                    groupName = assembly.GetName().Name;
                }
            }
            LocalizationGroupStack.Push(groupName);
            m_Pushed       = true;
            m_LocGroupName = groupName;
        }
        /// <summary>
        /// Returns the current version of the specified assembly
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static HtmlString ApplicationVersion(this HtmlHelper helper, System.Reflection.Assembly assembly = null)
        {
            if (assembly == null)
            {
                assembly = System.Reflection.Assembly.GetExecutingAssembly();
            }
            var version = assembly.GetName().Version;
            var product = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true).FirstOrDefault() as System.Reflection.AssemblyProductAttribute;

            if (version != null && product != null)
            {
                return(new HtmlString(string.Format(Statics.AssemblyVersionFormat, version.Major, version.Minor, version.Build, version.Revision)));
            }
            else
            {
                return(new HtmlString(""));
            }
        }
        public static String AssemblyVersionInfo(this System.Reflection.Assembly assembly)
        {
            System.Reflection.AssemblyName AsmName = assembly.GetName();

            Version AsemVersion = AsmName.Version;
            String  InfoStr;

            if (AsemVersion.Build != 0)
            {
                String buildNoString = DateTimeBuildNo.ToBuildDateString(AsemVersion.Build, AsemVersion.Revision);
                InfoStr = String.Format("{0} {1}", AsemVersion.ToString(), buildNoString);
            }
            else
            {
                InfoStr = AsemVersion.ToString();
            }
            return(InfoStr);
        }
Beispiel #6
0
 /// <summary>
 /// Dispara a exception de segurança.
 /// </summary>
 /// <param name="message">Mensagem de exception.</param>
 /// <param name="parameters"></param>
 private void ThrowSecurityException(string message, params object[] parameters)
 {
     System.Reflection.AssemblyName  assemblyName = null;
     System.Security.Policy.Evidence evidence     = null;
     try
     {
         System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
         assemblyName = callingAssembly.GetName();
         if (callingAssembly != System.Reflection.Assembly.GetExecutingAssembly())
         {
             evidence = callingAssembly.Evidence;
         }
     }
     catch
     {
     }
     throw new SecurityException(string.Format(message, parameters), assemblyName, null, null, null, SecurityAction.Demand, this, this, evidence);
 }
Beispiel #7
0
        protected override AuthenticateUIType GetPlatformUI()
        {
            Random r = new Random();
            string key;

            do
            {
                key = "xamarin_auth_" + r.Next();
            } while (PhoneApplicationService.Current.State.ContainsKey(key));

            PhoneApplicationService.Current.State[key] = this;


            System.Reflection.Assembly assembly = typeof(Authenticator).Assembly;
            string assembly_name = assembly.GetName().Name;

            return(new Uri("/" + assembly_name + ";component/WebAuthenticatorPage.xaml?key=" + key, UriKind.Relative));
        }
Beispiel #8
0
        public static IDictionary DefaultClientProperties()
        {
            System.Reflection.Assembly assembly =
                System.Reflection.Assembly.GetAssembly(typeof(ConnectionBase));
            string version = assembly.GetName().Version.ToString();
            //TODO: Get the rest of this data from the Assembly Attributes
            Hashtable table = new Hashtable();

            table["product"]   = Encoding.UTF8.GetBytes("RabbitMQ");
            table["version"]   = Encoding.UTF8.GetBytes(version);
            table["platform"]  = Encoding.UTF8.GetBytes(".NET");
            table["copyright"] = Encoding.UTF8.GetBytes("Copyright (C) 2007-2008 LShift Ltd., " +
                                                        "Cohesive Financial Technologies LLC., " +
                                                        "and Rabbit Technologies Ltd.");
            table["information"] = Encoding.UTF8.GetBytes("Licensed under the MPL.  " +
                                                          "See http://www.rabbitmq.com/");
            return(table);
        }
Beispiel #9
0
        public static string GetVersion()
        {
            string ourVersion = string.Empty;

            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                ourVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            else
            {
                System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                if (assemblyInfo != null)
                {
                    ourVersion = assemblyInfo.GetName().Version.ToString();
                }
            }
            return(ourVersion);
        }
Beispiel #10
0
        //public static DateTime GetTodayWithCustomTime(int hour, int minute, int second)
        //{
        //    int year = DateTime.Now.Year;
        //    int month = DateTime.Now.Month;
        //    int day = DateTime.Now.Day;

        //    return new DateTime(year, month, day, hour, minute, second);

        //}

        public static BitmapImage GetImage(object o)
        {
            // Aktuelle Assembly referenzieren
            System.Reflection.Assembly assembly =
                o.GetType().Assembly;

            // Das eingebettete Bild in einen Stream lesen
            System.IO.Stream stream =
                assembly.GetManifestResourceStream(
                    assembly.GetName().Name + ".Images.msn_phone.png");

            BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();

            //image.SetSource(imageStream );
            image.StreamSource = stream;
            // Den Stream in ein Bitmap umwandeln
            return(image);
        }
        } // End Function GetAssemblyDirectory

        public static void GetDependencies(System.Reflection.Assembly ass,
                                           System.Collections.Generic.List <System.Reflection.Assembly> ls,
                                           System.Collections.Generic.List <string> paths, string name)
        {
            name += "/" + ass.GetName().Name;
            paths.Add(name);

            //if (StringComparer.OrdinalIgnoreCase.Equals(ass.GetName().Name, "Microsoft.ReportViewer.ProcessingObjectModel"))
            if (true)
            {
                string assemblyPath = GetAssemblyDirectory(ass);
                System.Console.WriteLine(assemblyPath);
                string assemblyFileName = System.IO.Path.GetFileName(assemblyPath);

                string assemblyOutputDirectory = @"d:\reportviewerz\";
                if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
                {
                    assemblyOutputDirectory = "/root/reportviewerz/";
                }

                if (!System.IO.Directory.Exists(assemblyOutputDirectory))
                {
                    System.IO.Directory.CreateDirectory(assemblyOutputDirectory);
                }

                System.IO.File.Copy(assemblyPath, assemblyOutputDirectory + assemblyFileName);
            } // End if



            System.Reflection.AssemblyName[] asmNames = ass.GetReferencedAssemblies();

            foreach (System.Reflection.AssemblyName asmn in asmNames)
            {
                System.Reflection.Assembly ass2 = System.Reflection.Assembly.Load(asmn);

                if (!ls.Contains(ass2))
                {
                    ls.Add(ass2);
                    GetDependencies(ass2, ls, paths, name);
                    //ls.AddRange(GetDependencies(ass2));
                } // End if (!ls.Contains(ass2))
            }     // Next asmn
        }         // End Sub GetDependencies
Beispiel #12
0
 //构造
 public AssemInfoManagerClass(object obj, System.Reflection.Assembly assembly)
 {
     //重新生成唯一值
     this._guid = Guid.NewGuid();
     //暂时不定义
     //获取当前运行dll版本
     this._version = assembly.GetName().Version;
     //获取core版本
     //Command名
     this._cmdName = obj.ToString();
     if (_cmdName.Contains("Class"))
     {
         this._dllName = _cmdName.Substring(0, _cmdName.IndexOf("Class")) + "dll";
     }
     else
     {
         this._dllName = _cmdName + ".dll";
     }
 }
        public static byte[] ExtractImage(String fileName)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            Stream resFilestream = assembly.GetManifestResourceStream(assembly.GetName().Name + ".Resources." + fileName);

            if (resFilestream != null)
            {
                BinaryReader br = new BinaryReader(resFilestream);
                byte[]       ba = new byte[resFilestream.Length];
                resFilestream.Read(ba, 0, ba.Length);
                br.Close();
                return(ba);
            }
            else
            {
                Log.Warning("Embedded Resource with name {fileName} not found", fileName);
                return(null);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Считывание  текста из файла.
 /// </summary>
 /// <param name="name">Название файла.</param>
 /// <returns></returns>
 private string GetSql(string name)
 {
     try
     {
         // Получаем текущий объект класса Assembly
         System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
         // Получаем объект класса Stream к ресурсам текущей сборки.
         System.IO.Stream str = asm.GetManifestResourceStream(asm.GetName().Name + "." + name);
         // Считываем и возвращаем содержимое.
         System.IO.StreamReader reader = new System.IO.StreamReader(str);
         return(reader.ReadToEnd());
     }
     catch (Exception ex)
     {
         // Отлавливаем возникшие исключения.
         System.Windows.Forms.MessageBox.Show("В методе GetSql возникла ошибка: " + ex.Message);
         throw ex;
     }
 }
        public string GetVersion()
        {
            string version = "";

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                version = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(); // ApplicationDeployment.CurrentDeployment.CurrentVersion;
            }
            else
            {
                Logger.Info("This is not Network Deployed, as this is not OnceClick deploy application");
                System.Reflection.Assembly _assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                if (_assemblyInfo != null)
                {
                    version = _assemblyInfo.GetName().Version.ToString();
                }
            }
            return(version);
        }
Beispiel #16
0
        static SettingsPersister()
        {
            System.Reflection.Assembly         a = System.Reflection.Assembly.GetExecutingAssembly();
            System.Diagnostics.FileVersionInfo fileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location);

            string root         = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            string folder       = String.Format(@"Growl Extras\Feed Monitor\{0}", a.GetName().Version.ToString());
            string configFolder = System.IO.Path.Combine(root, folder);

            if (!configFolder.EndsWith(@"\"))
            {
                configFolder += @"\";
            }
            if (!System.IO.Directory.Exists(configFolder))
            {
                System.IO.Directory.CreateDirectory(configFolder);
            }
            configPath = System.IO.Path.Combine(configFolder, "user.config");
        }
Beispiel #17
0
        private void ReflectiveSetup(System.Reflection.Assembly specificAssembly)
        {
            string ThisExecutableFile = specificAssembly.CodeBase;

            if (ThisExecutableFile.IndexOf("file:///") >= 0)
            {
                ThisExecutableFile = specificAssembly.CodeBase.Replace("file:///", string.Empty).Replace('/', '\\');
            }
            else             // network path is file://server/share/path, so leave the double slashes to get \\server\share\path
            {
                ThisExecutableFile = specificAssembly.CodeBase.Replace("file:", string.Empty).Replace('/', '\\');
            }

            _version   = specificAssembly.GetName().Version.ToString();
            _name      = specificAssembly.ManifestModule.Name;
            _fullpath  = ThisExecutableFile;
            _processor = Enum.GetNames(typeof(System.Reflection.ProcessorArchitecture))[(int)specificAssembly.GetName().ProcessorArchitecture];
            _builddate = RetrieveLinkerTimestamp(ThisExecutableFile).ToString();
        }
Beispiel #18
0
        public static RSACryptoServiceProvider GetRsaProvider(System.Reflection.Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            byte[] bytes = assembly.GetName().GetPublicKey();
            if (bytes.Length == 0)
            {
                throw new Exception("No public key in assembly.");
            }

            RSAParameters            parameters = GetRSAParameters(bytes);
            RSACryptoServiceProvider rsa        = new RSACryptoServiceProvider();

            rsa.ImportParameters(parameters);
            return(rsa);
        }
Beispiel #19
0
        public Dashboard()
        {
            currentOptions = new Options();
            InitializeComponent();
            initialyzeSpeechEngine();

            myWindows = new List <string>();
            refreshProcessesList();
            fetchProfiles();

            ghk = new GlobalHotkey(0x0004, Keys.None, this);
            System.Reflection.Assembly     assembly     = System.Reflection.Assembly.GetExecutingAssembly();
            System.Reflection.AssemblyName assemblyName = assembly.GetName();

            Version version = assemblyName.Version;

            this.Text += " version : " + version.ToString();
            refreshSettings();
        }
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="assembly">A reference to a <see cref="System.Reflection.Assembly"/> whose version should be written as a property.</param>
        /// <param name="propertyName">A specific string to use for the property name. If null or empty string, the assembly 'simple' name will be used.</param>
        /// <param name="filter">A <see cref="ILogEventFilter"/> instance used to determine if the property should be added or not.</param>
        public AssemblyVersionLogEntryContextProvider(System.Reflection.Assembly assembly, string propertyName, ILogEventFilter filter) : base(filter)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

#if !CONTRACTS_ONLY
            var name = assembly.GetName();
            _PropertyName = propertyName;

            if (String.IsNullOrEmpty(_PropertyName))
            {
                _PropertyName = name.Name;
            }

            _Version = name.Version.ToString();
#endif
        }
Beispiel #21
0
 /// <summary>
 /// Gets the application name. Automatically initialized to the entry assembly name (exe).
 /// <locDE><para />Liefert den Anwendungsnamen. Automatisch initialisiert mit dem Namen der Startassembly (exe).</locDE>
 /// </summary>
 /// <returns>
 /// The application name. Automatically initialized to the entry assembly name (exe).
 /// <locDE><para />Der Anwendungsname. Automatisch initialisiert mit dem Namen der Startassembly (exe).</locDE>
 /// </returns>
 public static string GetAppName()
 {
     if (null == _AppName)
     {
         try
         {
             System.Reflection.Assembly assembly = EntryAssembly;
             if (null != assembly)
             {
                 _AppName = assembly.GetName().Name;
             }
         }
         catch
         {
             _AppName = "Unknown";
         }
     }
     return(_AppName);
 }
Beispiel #22
0
        private string GetVersion()
        {
            string ourVersion = string.Empty;

            // This will only work when running from deployed app not from VS.
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                ourVersion = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            else
            {
                System.Reflection.Assembly assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
                if (assemblyInfo != null)
                {
                    ourVersion = assemblyInfo.GetName().Version.ToString();
                }
            }
            return(ourVersion);
        }
Beispiel #23
0
        /// <summary>

        /// Retrieves a given file's contents from the embed resource.

        /// </summary>

        /// <param name="fileName">string containing resource file to retrieve.</param>

        /// <history>

        /// [Curtis_Beard]		09/01/2006	Created

        /// [Curtis_Beard]		10/11/2006	CHG: Close stream

        /// </history>

        public static string GetContents(string fileName)

        {
            try

            {
                System.Reflection.Assembly _assembly = System.Reflection.Assembly.GetExecutingAssembly();

                string _name = _assembly.GetName().Name;

                string _contents = string.Empty;



                Stream _stream = _assembly.GetManifestResourceStream(string.Format("{0}.Output.{1}", _name, fileName));



                if (_stream != null)

                {
                    using (StreamReader _reader = new StreamReader(_stream))

                    {
                        _contents = _reader.ReadToEnd();
                    }

                    _stream.Close();
                }

                _assembly = null;



                return(_contents);
            }

            catch {}



            return(string.Empty);
        }
Beispiel #24
0
        private void GameMain_Load(object sender, EventArgs e)
        {
            // カーソルをオリジナルのものに変更
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            Cursor myCursor = new Cursor(asm.GetManifestResourceStream(asm.GetName().Name + ".Resources.hand_cursor.cur"));

            this.Cursor = myCursor;

            // キャラクタが選ばれていたらゲーム開始
            if (chara == 1 || chara == 2)
            {
                PlayGame();
            }
            else      // そうじゃなきゃ終了
            {
                this.Close();
                this.Dispose();
            }
        }
Beispiel #25
0
        public static String VersionFor(System.Reflection.Assembly a)
        {
#if DEBUG
            string[] v = a.GetName().Version.ToString().Split('.');
            return(String.Format("{0}-{1}{2}-{3}", v[0].Substring(0, 2), v[0].Substring(2), v[1], v[2]));
#else
            string version_txt = Path.Combine(Path.GetDirectoryName(PortableSettingsProvider.ExecutablePath), PortableSettingsProvider.ExecutableName + "-Version.txt");
            if (!File.Exists(version_txt))
            {
                return("Unknown");
            }
            using (System.IO.StreamReader sr = new StreamReader(version_txt))
            {
                String line1 = sr.ReadLine();
                sr.Close();
                return(line1.Trim());
            }
#endif
        }
        public frmModuleMainBase()
        {
            InitializeComponent();
            if (CheckDesingModel.IsDesingMode)
            {
                return;
            }
            ButtonMap          = new Dictionary <Control, Type>();
            FunctionCollection = new ModuleFunctionCollection();

            //获得模块信息
            System.Reflection.Assembly s          = this.GetType().Assembly;
            AssemblyModuleAttribute    ModuleInfo = (AssemblyModuleAttribute)AssemblyModuleAttribute.GetCustomAttribute(s, typeof(AssemblyModuleAttribute));

            ModuleID   = s.GetName().Name;
            ModuleName = ModuleInfo.ModuleName;
            ModuleImg  = ModuleInfo.ModulePNGLarge;
            this.Load += FrmModuleMainBase_Load;
        }
Beispiel #27
0
        public Management()
        {
            //this.AddFunction(typeof(frmMyUser), "账号管理");
            //this.AddFunction(typeof(frmMyRole), "角色管理");
            //this.AddFunction(typeof(frmRibbonStyle), "Ribbon设置");
            //this.AddFunction(typeof(frmSetting), "系统设置");
            //this.AddFunction(typeof(frmCompanyInfo), "公司信息");
            //this.AddFunction(typeof(frmSystemAuthority), "功能注册");

            FunctionCollection = new ModuleFunctionCollection();

            //获得模块信息
            System.Reflection.Assembly s          = this.GetType().Assembly;
            AssemblyModuleAttribute    ModuleInfo = (AssemblyModuleAttribute)AssemblyModuleAttribute.GetCustomAttribute(s, typeof(AssemblyModuleAttribute));

            ModuleID   = s.GetName().Name;
            ModuleName = ModuleInfo.ModuleName;
            ModuleImg  = ModuleInfo.ModulePNGLarge;
        }
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            const int    OrcasMajorVersionNumber    = 9;
            const string TemplateWizardAssemblyName = "Microsoft.VisualStudio.TemplateWizard";
            const string SuppressOpeningItems       = "$__suppress_opening_items__$";

            bool?templateWizardIsOrcasOrLater = TemplateWizardIsOrcasOrLater;

            // If we haven't yet determined whether we are being called by the pre-Orcas version of TemplateWizard or not, do so now.
            if (!templateWizardIsOrcasOrLater.HasValue)
            {
                System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();

                Debug.Assert(callingAssembly != null && callingAssembly.FullName.StartsWith(TemplateWizardAssemblyName, StringComparison.Ordinal));

                // If for any reason we can't tell what version we're running under, we assume it is pre-Orcas.
                templateWizardIsOrcasOrLater = TemplateWizardIsOrcasOrLater =
                    (callingAssembly != null && (callingAssembly.GetName().Version.Major >= OrcasMajorVersionNumber));
            }

            if (templateWizardIsOrcasOrLater.GetValueOrDefault())
            {
                // The Orcas version of TemplateWizard correctly checks Project.FullName for null / empty string before
                // trying to create a Uri from it. Therefore, this workaround is only needed for pre-Orcas versions.
                return;
            }

            Debug.Assert(runKind == WizardRunKind.AsNewItem);

            if (replacementsDictionary == null)
            {
                // If we don't have a replacements dictionary, we can't do anything anyway, so just bail out.
                return;
            }

            if (!replacementsDictionary.ContainsKey(SuppressOpeningItems))
            {
                // The value that we add doesn't really matter (only the key does),
                // but just in case they start doing anything with it, we'll use "true".
                replacementsDictionary.Add(SuppressOpeningItems, "true");
            }
        }
Beispiel #29
0
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            VersionNo = assembly.GetName().Version.ToString();//获取主版本号


            int day = Resources.GetRes().ExpiredRemainingDays;

            if (day > 99)
            {
                day = 99;
            }

            RemainingDays = string.Format("{0}", day);// : {0}.


            Device = string.Format("{0}", Resources.GetRes().DeviceCount);


            Table = string.Format("{0}", Resources.GetRes().RoomCount);


            //语言
            if (Resources.GetRes().MainLangIndex == 0)
            {
                Admin = Resources.GetRes().AdminModel.AdminName0;
            }
            else if (Resources.GetRes().MainLangIndex == 1)
            {
                Admin = Resources.GetRes().AdminModel.AdminName1;
            }
            else if (Resources.GetRes().MainLangIndex == 2)
            {
                Admin = Resources.GetRes().AdminModel.AdminName2;
            }
            Role = GetModeName(Resources.GetRes().AdminModel.Mode);



            DisableVisibleMode = false;
            InitDisable();
        }
Beispiel #30
0
        private IConfiguration GetConfiguration()
        {
            System.Reflection.Assembly assembly = GetType().Assembly;
            var resource = assembly.GetName().Name + ".Configuration.appsettings.json";
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            if (assembly.GetManifestResourceNames().Contains(resource))
            {
                string result = null;
                using (Stream stream = assembly.GetManifestResourceStream(resource))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }

                configurationBuilder.AddJsonFile(new InMemoryFileProvider(result), resource, false, false);
            }

            return(configurationBuilder.Build());
        }
Beispiel #31
0
        //<summary>Lock level scrolling</summary>
        //private bool bScrollLock;
        //################################################################################################################
        //Constructor
        ///<summary>Top-level contructor for SokobanCompact</summary>
        public formMain()
        {
            FunctionResult uRV;

            InitializeComponent();

            hGameSkin = null;
            uBackBuffer = null;
            bDeadlockMessage = false;
            bHaveUnfinishedPosition = false;
            Cursor.Current = Cursors.WaitCursor;//Waiting cursor - while loading levelset and skin

            //Get handle of assembly
            hExecAssem = System.Reflection.Assembly.GetExecutingAssembly();
            //Get file name of assembly
            string sAppFilePath = hExecAssem.GetModules()[0].FullyQualifiedName;
            //Get path only
            sApplicationDirectory = System.IO.Path.GetDirectoryName(sAppFilePath);
            //Add delimiter at the end
            if (!sApplicationDirectory.EndsWith(@"\"))
                sApplicationDirectory += @"\";

            //Calc paths for folders
            //sSavesDirectory = sApplicationDirectory + @"Saves\";
            sLevelsDirectory = sApplicationDirectory + @"Levels\";
            sSolutionsDirectory = sApplicationDirectory + @"Solutions\";
            sSkinsDirectory = sApplicationDirectory + @"Skins\";
            sBackgroundsDirectory = sApplicationDirectory + @"Backgrounds\";

            //Try to create all required folders, to not bother in future
            try
            {
                //System.IO.Directory.CreateDirectory(sSavesDirectory);
                System.IO.Directory.CreateDirectory(sBackgroundsDirectory);
                System.IO.Directory.CreateDirectory(sSkinsDirectory);
                System.IO.Directory.CreateDirectory(sSolutionsDirectory);
                System.IO.Directory.CreateDirectory(sLevelsDirectory);
            }
            catch (System.IO.IOException)
            {}//Dont know that to do, if creation fails

            //Calc rectangles on statusbar
            int iX = 3;

            int iStatusHeight = pictureStatus.Height;//Height of status bar
            Graphics uGr1 = CreateGraphics();//Get graphics of current form
            SizeF uCounterSizes = uGr1.MeasureString(" 0000", Font);//Measure sample string for get actual font sizes
            int iCounterWidth = (int)uCounterSizes.Width;//Width of counter - with of sample string
            int iCounterY0 = (int)(iStatusHeight-uCounterSizes.Height)/2;//Text positions - valign center
            int iSpace = iCounterWidth/10;//Space between fields - 10% if counter width
            uGr1.Dispose();//Release graphics of form

            uRectIndic = new Rectangle(iX, (iStatusHeight-16)/2, 16, 16);//for solved/not-solved indicator
            iX += uRectIndic.Width + iSpace;
            uRectMoves = new Rectangle(iX, iCounterY0, iCounterWidth, 16);//for counter of moves
            iX += uRectMoves.Width + iSpace;
            uRectPushes = new Rectangle(iX, iCounterY0, iCounterWidth, 16);//for counter of pushes
            iX += uRectPushes.Width + iSpace;
            uRectMessage = new Rectangle(iX, iCounterY0, ClientRectangle.Width - iX, 16); //all rest space - for non-modal message

            //Font f1 = this.Font;
            //f1.me
            //this.gr
            //Graphic .MeasureString

            //bScrollLock = false;
            bResize = true;
            iBottomOfForm = pictureStatus.Top;//this done here for perform recenter of level before any redraws

            //Create and load settings
            uSetting = new Settings();
            if (uSetting.Load(sApplicationDirectory + sConfigFile) != FunctionResult.OK)
            {
                //Settings not loaded - first start or failure of file
                uSetting = new Settings();//reset to default, just in case...
            }
            menuScrollLock.Checked = uSetting.bScrollLock;

            if (uSetting.bLogActions)
            {
                uLog = new LogFile();
                uLog.Start(sApplicationDirectory + sLogFile);
                uLog.LogString(ActionID.Start, "Started SokobanCompact; v" + hExecAssem.GetName().Version);
            }

            //Load level set list
            uLevelSetList = new SokobanLevelSetList(sApplicationDirectory + sLevelSetList, sLevelsDirectory, sSolutionsDirectory);
            uLevelSetList.LoadList();

            iSkinSize = 0;

            //Load skinset
            uSkinSet = new SkinSet();
            //uSkinSet.Load(sSkinsDirectory + "\\" + "oq.sks");//TODO: move skinset name into Settings
            uSkinSet.Load(sSkinsDirectory + uSetting.sSkinSet);

            if (!uSetting.bAutosize)
            {   //No autosize? Load skin now
                uRV = LoadSkin(sSkinsDirectory + uSetting.sSkin);
                if (iSkinSize == 0)
                {
                    LogSimpleLine(ActionID.ShowDialog, "Error; Failed to load skin, null skin created; " + uSetting.sSkin+"; "+uRV.ToString());
                    MessageBox.Show("Failed to load skin '" + uSetting.sSkin + "' \r\nNull skin will be loaded, " + uRV.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    GenNullSkin();
                }
            }

            UpdateBackground();//Create background according to settings

            //Create game
            uGame = new SokobanGame();

            //THREAD
            uBackgroundCalc = new BackgroundThread(BackgroundFinished);//Create thread for background

            iSelectorMode = 0;//Selector initialy in "play" mode
            SetToolBarMode();//Refresh selector

            //Load levelset
            uLevelSet = new SokobanLevelSet();
            uRV = uLevelSetList.LoadLevelSet(uLevelSet, uSetting.sLastLevelSet);
            if (uRV != FunctionResult.OK)
            {   //Something happens with levelset file
                LogSimpleLine(ActionID.ShowDialog, "Error; Failed to load levelset, random will be generated; " + uSetting.sLastLevelSet+"; "+uRV.ToString());
                MessageBox.Show("Unable to load LevelSet '" + uSetting.sLastLevelSet + "', result: " + uRV.ToString() + "\r\nRandom level will be loaded.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                uLevelSetList.GenNullLevelSet(uLevelSet);//Generate levelset with 1 random level
                uSetting.iLastLevelPlayed = 0;//Res
            }

            //Start last played level
            uRV = LoadLevel(uGame, uSetting.iLastLevelPlayed);
            if (uRV == FunctionResult.OK)
            {   //Loaded successfully
                AfterLoadLevel();
            }
            else
            {   //Level not loaded (only variant - FunctionResult.OutOfLevelSet)
                LogSimpleLine(ActionID.ShowDialog, "Error; Failed to load level, random will be choosen; " + uSetting.iLastLevelPlayed.ToString() + "; " + uRV.ToString());
                MessageBox.Show("Unable to load level " + uSetting.iLastLevelPlayed.ToString() + ", result: " + uRV.ToString() + "\r\nRandom level will be selected.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                ActionRandLevel();
            }

            if (iSkinSize < 1)
            {
                LogSimpleLine(ActionID.ShowDialog, "Error; No skin loaded, null skin created");
                MessageBox.Show("Failed to load skin\r\nNull skin will be loaded", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                GenNullSkin();
                RecenterLevel();
            }

            NonModalMessage(uLevelSet.sTitle + ", " + uGame.sTitle);

            Cursor.Current = Cursors.Default;//remove wait cursor
        }
Beispiel #32
0
 private System.Drawing.Icon GetTrayIcon(string iconType)
 {
     lock (this)
     {
         assembly = System.Reflection.Assembly.GetExecutingAssembly();
         string path = assembly.GetName().Name + ".Sources.Images.TrayIcon-" + iconType + ".ico";
         System.IO.Stream stream = assembly.GetManifestResourceStream(path);
         return new System.Drawing.Icon(stream);
     }
 }
        public GetTasksHI(TasksBitField tasklistpassed, TrueCryptFile tcFileHDOld, TrueCryptFile tcFileTravOld, string calledArg)
        {
            InitializeComponent();
            newFileSizeMB.Text = defaultTCFileSize.ToString() + " "; //space to offset numbers
            tasklist1 = tasklistpassed;
            tcFileHDOldLoc = tcFileHDOld;
            tcFileTravOldLoc = tcFileTravOld;
            taskChoice1.Text = "Text";
            assem = System.Reflection.Assembly.GetExecutingAssembly();
            System.Reflection.AssemblyName assemName = assem.GetName();
            //this.Text += " Ver " + assemName.Version.ToString();// used to put version into title
            //radioButton2.Enabled = false;

            #region Get data for decisions on hard drive and traveler drive
            //Build list of usb connected drives first so can test against it in tcfileobject instance
            if (calledArg != "format" || assem.Location.Substring(0, 2) != Environment.GetEnvironmentVariable("HOMEDRIVE"))
            {//ie do this if not being called from start tax-aide drive to do a format on the hard drive
                GetUSBDrives(); //returns travusbdrv which is logical drive name and vol label and a combo string tcfile poss to be set here
            }
            //Analyze hard drive situation
            TrueCryptFilesNew.tcFileHDNewPath = Environment.GetEnvironmentVariable("HOMEDRIVE") + "\\" + tcFilename; //sets up new name will be changed next for vista/w7
            // Find out if hard drive tpdata exists
            if (File.Exists(Environment.GetEnvironmentVariable("HOMEDRIVE") + "\\" + tcFilename))
            {
                tcFileHDOldLoc.FileNamePath = Environment.GetEnvironmentVariable("HOMEDRIVE") + "\\" + tcFilename;
                TrueCryptFilesNew.tcFileHDNewPath = Environment.GetEnvironmentVariable("HOMEDRIVE") + "\\" + tcFilename; //set wrongly for vista/w7 here fixed in next clause
            }
            if (DoTasksObj.osVer == 6)
            {
                TrueCryptFilesNew.tcFileHDNewPath = Environment.GetEnvironmentVariable("PUBLIC") + "\\" + tcFilename;
                if (File.Exists(Environment.GetEnvironmentVariable("PUBLIC") + "\\" + tcFilename))
                {
                    tcFileHDOldLoc.FileNamePath = Environment.GetEnvironmentVariable("PUBLIC") + "\\" + tcFilename;
                    TrueCryptFilesNew.tcFileHDNewPath = Environment.GetEnvironmentVariable("PUBLIC") + "\\" + tcFilename;
                }
            }
            //Now analyze usb drive situation
            //for (int i = 0; i < travUSBDrv.Count; i++)
            foreach (DrvInfo drv in travUSBDrv)
            {
                if (File.Exists(drv.drvName + @"\" + tcFilenamesOldTrav[0]))
                {
                    drv.tcFilePoss = drv.drvName + @"\" + tcFilenamesOldTrav[0];
                    travTcFilePossCount++;
                }
                else if (File.Exists(drv.drvName + @"\" + tcFilenamesOldTrav[1]))
                {
                    drv.tcFilePoss = drv.drvName + @"\" + tcFilenamesOldTrav[1];
                    travTcFilePossCount++;
                }
                else if (File.Exists(drv.drvName + @"\" + tcFilenamesOldTrav[2]))
                {
                    drv.tcFilePoss = drv.drvName + @"\" + tcFilenamesOldTrav[2];
                    travTcFilePossCount++;
                }
            }
            Log.WritSection("Trav TC File poss count = " + travTcFilePossCount.ToString() + ", USB Drives count = " + travUSBDrv.Count.ToString());
            #endregion

            #region Decisions to setup initial form
            //1st priority to see if running from an existing installation, if so only thing can do is format. After that priority to flash keys if they are inserted. button 1 is only one that contains requirements for volume size to be filled out button 2 is strictly for software upgrades except for 2 blank travelers
            //if (assem.Location.Contains("TrueCrypt\\Tax-Aide")||assem.Location.Contains("Tax-Aide_Traveler"))
            if (calledArg == "format")
            {//we are running from an existing install probably called from Start_Tax-Aide_drive.exe
                SetFormatClsStartProcess();
            }
            else if (travTcFilePossCount > 0 | travUSBDrv.Count > 0)
            {
                // Check for Traveler failed migration has to occur after have inof on usb flash drives available
                SetButtons4Traveler();
            }
            else
            {//just go straight to install on c drive
                SetButtons4HD();
                taskChoice3.Visible = false;
            }

            #endregion
        }