コード例 #1
0
        //
        // GET: /QuocGia/
        public ActionResult Index(int? page, string TuNgaySearch, string DenNgaySearch, string tenTaiKhoan)
        {
            int currentPageIndex = page.HasValue ? page.Value : 0;

            const int pageSize = 10;
            IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
            String datetime = TuNgaySearch;
            DateTime tn = new DateTime(1975, 1, 1);

            DateTime dn = DateTime.Now;
            if (TuNgaySearch != null && TuNgaySearch != "")
            {
                tn = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
                //tnStr = tn.ToString("MM/dd/yyyy");
            }
            datetime = DenNgaySearch;
            if (DenNgaySearch != null && DenNgaySearch != "")
            {
                dn = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
                //dnStr = dn.ToString("MM/dd/yyyy");
            }

            var objs = HistoryRes.FindAll(tenTaiKhoan, tn, dn);
            var paginatedAccounts = new PaginatedList<Histories>(objs, currentPageIndex, pageSize);

            return View(paginatedAccounts);
        }
コード例 #2
0
        public string ReturnDayOfWeekOnBulgarian(DateTime date)
        {
            var culture = new System.Globalization.CultureInfo("bg-BG");
            var day = culture.DateTimeFormat.GetDayName(date.DayOfWeek);

            return day;
        }
コード例 #3
0
ファイル: activator.cs プロジェクト: ArildF/masters
        /// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance1"]/*' />
        static public Object CreateInstance(Type type,
                                            BindingFlags bindingAttr,
                                            Binder binder,
                                            Object[] args,
                                            CultureInfo culture,
                                            Object[] activationAttributes)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            if (type is System.Reflection.Emit.TypeBuilder)
                throw new NotSupportedException(Environment.GetResourceString( "NotSupported_CreateInstanceWithTypeBuilder" ));

            // If they didn't specify a lookup, then we will provide the default lookup.
            if ((bindingAttr & (BindingFlags) LookupMask) == 0)
                bindingAttr |= Activator.ConstructorDefault;

            try {
                RuntimeType rt = (RuntimeType) type.UnderlyingSystemType;
                return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes);
            }
            catch (InvalidCastException) {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
            }
        }
コード例 #4
0
ファイル: Display.cs プロジェクト: dbremner/szotar
		public Display() {
			InitializeComponent();

			fontName = GuiConfiguration.ListFontName;
			fontSize = GuiConfiguration.ListFontSize;

			try {
				var culture = new System.Globalization.CultureInfo(GuiConfiguration.UiLanguage).Name;
				if (culture == "en-US")
					englishUS.Checked = true;
				else if (culture == "en-GB")
					englishGB.Checked = true;
				else if (culture == "hu-HU")
					hungarian.Checked = true;
			} catch(ArgumentException) {
				// The UI language isn't any of the supported languages.
			}

			setLanguage = false;

			UpdateListFontButton();
			listFontButton.Click += listFontButton_Click;

			englishUS.Click += LanguageChanged;
			englishGB.Click += LanguageChanged;
			hungarian.Click += LanguageChanged;
		}
コード例 #5
0
ファイル: Program.cs プロジェクト: mic22/NancyDb4o
        public static Person Import(String input)
        {
            var parameters = new Dictionary<string, string>();
            var data = input.Split(';');
            foreach (string item in data)
            {
                var specyficData = item.Split(':');
                parameters[specyficData[0]] = specyficData[1];
            }

            var person = new Person();
            person.NameSurname = parameters["NS"];

            IFormatProvider culture = new System.Globalization.CultureInfo("pl-PL", true);
            if (parameters.ContainsKey("BD"))
            {
                person.Birthdate = DateTime.Parse(parameters["BD"], culture);
            }

            if (parameters.ContainsKey("DD"))
            {
                person.Deathdate = DateTime.Parse(parameters["DD"], culture);
            }

            if (parameters.ContainsKey("S"))
            {
                switch (parameters["S"])
                {
                    case "M": person.Sex = PersonSex.Male; break;
                    case "F": person.Sex = PersonSex.Female; break;
                }
            }

            return person;
        }
コード例 #6
0
        public ActionResult Index(FormCollection request)
        {
            var _usuario = Session.GetData<User>("user") as User;
            IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

            DateTime inicio = Convert.ToDateTime(request["inicio"]);
            DateTime fin = Convert.ToDateTime(request["fin"]);

            var api = new DAL.ApiReports("", "");
            Angle.ModelsResults.RootGetBillingHistoryResult AnalisisGeneral = api.GetBillingHistory(
                _usuario.UserTypeObject.Description,
                _usuario.ClientObject.ClientId,
                inicio.ToString("MM/dd/yyyy"),
                fin.ToString("MM/dd/yyyy"),
                _usuario.CountryObject.CountryId
                );

            Angle.ModelsResults.RootGetBillingHistoryClientDebListResult AnalisisCliente = api.GetBillingHistoryClientDebList(
               _usuario.UserTypeObject.Description,
               _usuario.ClientObject.ClientId,
               new DateTime(2015, 1, 1).ToString("MM/dd/yyyy"),
               DateTime.Now.ToString("MM/dd/yyyy"),
               _usuario.CountryObject.CountryId
               );

            ViewBag.data = AnalisisGeneral.GetBillingHistoryResult.Invoice;
            ViewBag.Clientes = AnalisisCliente.GetBillingHistoryClientDebListResult;

            Session.SetData<object>("ultimoRango", new { StartDate = DateTime.Now, EndDate = DateTime.Now });
            ViewBag.startDate = inicio;
            ViewBag.endDate = fin;

            return View("ResumenGeneral");
        }
コード例 #7
0
ファイル: CustomerController.cs プロジェクト: thuyenvinh/qlvx
 public ActionResult Create(Customer cs, FormCollection collection)
 {
     IFormatProvider iFP = new System.Globalization.CultureInfo("vi-VN", true);
     cs.CreateDate = DateTime.Parse(collection["CreateDate"], iFP);
     var result = CustomerBusiness.Insert(cs);
     return PartialView(cs);
 }
コード例 #8
0
        public ActionResult Index(FormCollection request)
        {
            var _usuario = Session.GetData<User>("user") as User;
            IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

            DateTime inicio = Convert.ToDateTime(request["inicio"]);
            DateTime fin = Convert.ToDateTime(request["fin"]);

            var api = new DAL.ApiReports("", "");
            ModelsResults.RootGetCashedInvoicedResult  AnalisisGeneral = api.GetCashedInvoiced(
                _usuario.UserTypeObject.Description,
                _usuario.ClientObject.ClientId,
                inicio.ToString("MM/dd/yyyy"),
                fin.ToString("MM/dd/yyyy"),
                _usuario.CountryObject.CountryId
                );

            ModelsResults.RootGetCashedInvoicedClientListResult AnalisisDetallado = api.GetCashedInvoicedClientList(
               _usuario.UserTypeObject.Description,
               _usuario.ClientObject.ClientId,
               inicio.ToString("MM/dd/yyyy"),
               fin.ToString("MM/dd/yyyy"),
               _usuario.CountryObject.CountryId
               );

            ViewBag.data = AnalisisGeneral.GetCashedInvoicedResult;
            ViewBag.clientes = AnalisisDetallado.GetCashedInvoicedClientListResult;

            Session.SetData<object>("ultimoRango", new { StartDate = DateTime.Now, EndDate = DateTime.Now });
            return View("ResumenGeneral");
        }
コード例 #9
0
        // funktions som kontrolerar om väder prognonsernas dag
        public string GetDayOfTheWeek(DateTime dateTime, int period)
        {
            var culture = new System.Globalization.CultureInfo("sv-SE");

            if (dateTime.DayOfWeek == DateTime.Now.DayOfWeek && counter != 1)
            {
                //counter = 1; test
                /*
                 if (dateTime.DayOfWeek == DateTime.Now.AddDays(1).DayOfWeek && period == 0)
            {
                return "Imorgon";
            }*/
                counter = 1;
                return "Idag";

            }
            if (dateTime.DayOfWeek == DateTime.Now.AddDays(1).DayOfWeek && period == 0)
            {
                return "Imorgon";
            }
            if (period == 0)
            {

                return culture.DateTimeFormat.GetDayName(dateTime.DayOfWeek).ToString();
            }
            else
            {
                return null;
            }
        }
コード例 #10
0
 public static string ConvertToValidSharePointFieldName(this string source)
 {
     System.Globalization.TextInfo UsaTextInfo = new System.Globalization.CultureInfo("en-US", false).TextInfo;
     string staticName = UsaTextInfo.ToTitleCase(source);
     Regex regex = new Regex(@"\W");
     return regex.Replace(staticName.DoStripDiacritics(), string.Empty);
 }
コード例 #11
0
		// @Override
		public override void  RunBare()
		{
			// Do the test with the default Locale (default)
			try
			{
				locale = defaultLocale;
				base.RunBare();
			}
			catch (System.Exception e)
			{
                System.Console.Out.WriteLine("Test failure of '" + Lucene.Net.TestCase.GetName() + "' occurred with the default Locale " + locale); 
				throw e;
			}

            if (testWithDifferentLocales == null || testWithDifferentLocales.Contains(Lucene.Net.TestCase.GetName())) 
			{
				// Do the test again under different Locales
				System.Globalization.CultureInfo[] systemLocales = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.InstalledWin32Cultures);
				for (int i = 0; i < systemLocales.Length; i++)
				{
					try
					{
						locale = systemLocales[i];
						base.RunBare();
					}
					catch (System.Exception e)
					{
                        System.Console.Out.WriteLine("Test failure of '" + Lucene.Net.TestCase.GetName() + "' occurred under a different Locale " + locale); // {{Aroush-2.9}} String junit.framework.TestCase.getName()
						throw e;
					}
				}
			}
		}
コード例 #12
0
		public System.Globalization.CultureInfo GetCurrentCultureInfo ()
		{
			var netLanguage = "en";
			var prefLanguageOnly = "en";
			if (NSLocale.PreferredLanguages.Length > 0) {
				var pref = NSLocale.PreferredLanguages [0];

				// HACK: Apple treats portuguese fallbacks in a strange way
				// https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/LocalizingYourApp/LocalizingYourApp.html
				// "For example, use pt as the language ID for Portuguese as it is used in Brazil and pt-PT as the language ID for Portuguese as it is used in Portugal"
				prefLanguageOnly = pref.Substring(0,2);
				if (prefLanguageOnly == "pt")
				{
					if (pref == "pt")
						pref = "pt-BR"; // get the correct Brazilian language strings from the PCL RESX (note the local iOS folder is still "pt")
					else
						pref = "pt-PT"; // Portugal
				}
				netLanguage = pref.Replace ("_", "-");
				Console.WriteLine ("preferred language:" + netLanguage);
			}

			// this gets called a lot - try/catch can be expensive so consider caching or something
			System.Globalization.CultureInfo ci = null;
			try {
				ci = new System.Globalization.CultureInfo(netLanguage);
			} catch {
				// iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
				// fallback to first characters, in this case "en"
				ci = new System.Globalization.CultureInfo(prefLanguageOnly);
			}
				
			return ci;
		}
コード例 #13
0
ファイル: NifParser.cs プロジェクト: Merec/DAoC-MapCreator
 public NifParser()
 {
     // Language settings
     System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
     System.Threading.Thread.CurrentThread.CurrentCulture = ci;
     System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
 }
コード例 #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-ES");

            spanFecha.InnerText = "Garage Nadia - " + DateTime.Now.ToString("dd/MM/yyyy hh:mm");

            string tipo = Request.QueryString["tipo"];

            if (tipo == "mensual")
            {
                string mes = Request.QueryString["mes"];
                string ano = Request.QueryString["ano"];
                string texto = Request.QueryString["texto"];
                string detalle = Request.QueryString["detalle"];

                spanFiltros.InnerText = "Mes: "+texto+" - Año: "+ano;

                divCode.InnerHtml = CONTROLADORA.ControladoraReporteHTML.ReporteGananciasMensual(mes, ano, detalle);
            }

            if (tipo == "periodo")
            {
                string desde = Request.QueryString["desde"];
                string hasta = Request.QueryString["hasta"];
                string detalle = Request.QueryString["detalle"];

                spanFiltros.InnerText = "Reporte Desde: " + desde + " - Hasta: " + hasta;


                divCode.InnerHtml = CONTROLADORA.ControladoraReporteHTML.ReporteGananciasPeriodo(desde, hasta, detalle);
            }


        }
コード例 #15
0
        static void Main(string[] args)
        {
            // Set up the crash dump handler.
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(unhandledException);

            cultureInfo = new System.Globalization.CultureInfo("en-GB");
            settingsManager = new SettingsManager();
            cloudFlareAPI = new CloudFlareAPI();

            if (args.Length > 0)
            {
                if (args[0] == "/service")
                {
                    runService();
                    return;
                }

                if (args[0] == "/install")
                {
                    if(!isAdmin)
                    {
                        AttachConsole( -1 /*ATTACH_PARENT_PROCESS*/ );
                        Console.WriteLine("Need to be running from an elevated (Administrator) command prompt.");
                        FreeConsole();
                        return;
                    }

                    TransactedInstaller ti = new TransactedInstaller();
                    ti.Installers.Add(new ServiceInstaller());
                    ti.Context = new InstallContext("", null);
                    ti.Context.Parameters["assemblypath"] = "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" /service";
                    ti.Install(new System.Collections.Hashtable());
                    ti.Dispose();
                    return;
                }

                if (args[0] == "/uninstall")
                {
                    if (!isAdmin)
                    {
                        AttachConsole(-1 /*ATTACH_PARENT_PROCESS*/ );
                        Console.WriteLine("Need to be running from an elevated (Administrator) command prompt.");
                        FreeConsole();
                        return;
                    }

                    TransactedInstaller ti = new TransactedInstaller();
                    ti.Installers.Add(new ServiceInstaller());
                    ti.Context = new System.Configuration.Install.InstallContext("", null);
                    ti.Context.Parameters["assemblypath"] = "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" /service";
                    ti.Uninstall(null);
                    ti.Dispose();
                    return;
                }
            }

            runGUI();
            return;

        }//end Main()
コード例 #16
0
        /// <summary>
        /// 导出文件为txt
        /// </summary>
        /// <param name="isdelete">是否删除数据</param>
        protected void ExportTxt(bool isdelete)
        {

            Page.Response.Clear();
            Page.Response.Buffer = true;
            Page.Response.Charset = "GB2312";
            Page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename=sys_EventLog{0}.csv",DateTime.Now.ToShortDateString()));
            Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            Response.ContentType = "text/plain";//设置输出文件类型为txt文件。 
            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("EventID,E_U_LoginName,E_UserID,E_DateTime,E_ApplicationID,E_A_AppName,E_M_Name,E_M_PageCode,E_From,E_Type,E_IP,E_Record");
            sb.Append("\n");
            int rCount = 0;
            ArrayList lst = BusinessFacade.sys_EventList(new QueryParam(1, int.MaxValue),out rCount);
            foreach (sys_EventTable var in lst)
            {
                sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},\"{11}\"\n", var.EventID,
                var.E_U_LoginName,var.E_UserID,var.E_DateTime,var.E_ApplicationID,
                var.E_A_AppName,var.E_M_Name,var.E_M_PageCode,var.E_From,
                var.E_Type,var.E_IP,var.E_Record
                );
            }

            Page.Response.Write(sb.ToString());
            if (isdelete)
            {
                ClearData();
            }
            EventMessage.EventWriteDB(2, "导出操作日志!");
            Page.Response.End();
        }
コード例 #17
0
ファイル: OrbitsNet.cs プロジェクト: neur0nid/OrbitsNet
        public OrbitsNet()
        {
            InitializeComponent();
            this.recursos = new System.Resources.ResourceManager("OrbitsNet.Properties.Resources", this.GetType().Assembly);
            this.cultura = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToUpper());
            this.configureLanguage();
            this.fillHash();
            this.selectedFilesForDownload = new List<string>();
            this.loadedFiles = new List<string>();

            this.loadedTles = new List<FileAndTle>();
            this.selectedTles = new List<Tle>();
            this.processedTles = new List<OrbitsElement>();

            this.resetCartChart();
            this.resetPolarchart();
            this.resetMapChart();

            this.loadWorker = new BackgroundWorker();
            this.loadWorker.WorkerSupportsCancellation = true;
            this.loadWorker.WorkerReportsProgress = true;
            this.loadWorker.DoWork += loadWorker_DoWork;
            this.loadWorker.ProgressChanged += loadWorker_ProgressChanged;
            this.loadWorker.RunWorkerCompleted += loadWorker_RunWorkerCompleted;

            this.plotWorker = new BackgroundWorker();
            this.plotWorker.WorkerSupportsCancellation = true;
            this.plotWorker.WorkerReportsProgress = true;
            this.plotWorker.DoWork += plotWorker_DoWork;
            this.plotWorker.ProgressChanged += plotWorker_ProgressChanged;
            this.plotWorker.RunWorkerCompleted += plotWorker_RunWorkerCompleted;

            this.configureDefault();
        }
コード例 #18
0
ファイル: TestNLS.cs プロジェクト: kstenson/NHibernate.Search
		public virtual void  TestMissingMessage()
		{
			System.Globalization.CultureInfo locale = new System.Globalization.CultureInfo("en");
			System.String message = NLS.GetLocalizedMessage(MessagesTestBundle.Q0005E_MESSAGE_NOT_IN_BUNDLE, locale);
			
			Assert.AreEqual("Message with key:Q0005E_MESSAGE_NOT_IN_BUNDLE and locale: " + locale.ToString() + " not found.", message);
		}
コード例 #19
0
ファイル: Program.cs プロジェクト: oblivious/Oblivious
        static void Main(string[] args)
        {
            while (true)
            {
                var j = LanguageConfig.Languages.Keys;
                List<string> k = j.ToList();
                foreach (var i in j)
                {
                    Console.WriteLine(i + ", " + LanguageConfig.Languages[i]);
                }
                foreach (var l in k)
                {
                    Console.WriteLine(l);
                }
                Console.WriteLine(ConfigurationManager.AppSettings["defaultTheme"]);
                Console.ReadLine();
                ConfigurationManager.RefreshSection("appSettings");

                ResourceManager rm = new ResourceManager("ConsoleApplication10.Resources", Assembly.GetExecutingAssembly());
                System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es");
                Console.WriteLine(rm.GetString("name", ci));
                Console.WriteLine(rm.GetString("name", new System.Globalization.CultureInfo("en")));
                Console.WriteLine(rm.GetString("name"));
                Console.ReadLine();
            }
        }
コード例 #20
0
ファイル: Geocoder.cs プロジェクト: macrodepy/Geocoder
 public Geocoder()
 {
     cultureInfo = new System.Globalization.CultureInfo("tr-TR");
     addressLevel = new AddressLevel();
     geocoderService = new GeocoderService();
     hierarchy = new string[7, 2];
 }
コード例 #21
0
ファイル: ReportUtil.cs プロジェクト: popotans/hjnlib
        public static void OutPutExcelByGridView(GridView grvExcel, string excelName, string encodingName, System.Globalization.CultureInfo ci)
        {
            //定义文档类型、字符编码
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = encodingName;
            //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
            //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(excelName));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(encodingName);
            //Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            grvExcel.EnableViewState = false;
            if (ci == null) ci = new System.Globalization.CultureInfo("zh-CN", true);
            System.Globalization.CultureInfo myCultureInfo = ci;

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCultureInfo);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            oHtmlTextWriter.Write("<html><head><meta http-equiv=\"content-type\" content=\"text/html;charset=gb2312\"></head>");

            grvExcel.Visible = true;
            grvExcel.RenderControl(oHtmlTextWriter);
            //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
            HttpContext.Current.Response.Write(oStringWriter.ToString());
            HttpContext.Current.Response.End();
        }
コード例 #22
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            dat = new DataHandler();
            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            GoogleAnalytics.EasyTracker.GetTracker().SendView("MainPanaroma");

            App.ViewModel.Items.Clear();
            txt_REG.Text = (string) dat.getReg();
            if (txt_REG.Text == "" || dat.getDob().Equals(""))
            {
                newUser = true;
            }
            else {
                DateTime dater;
                IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR");
                String date = (dat.getDob().Insert(2, "/")).Insert(5,"/");
                dater = DateTime.Parse(date, culture);
                datePicker.Value = dater;
                if (dat.isVellore())
                    chk_Vellore.IsChecked = true;
                else
                    chk_Chennai.IsChecked = true;
                //App.ViewModel.isCache = true;
                //App.ViewModel.LoadData();
            }
            
        }
コード例 #23
0
ファイル: Assembly.cs プロジェクト: elasota/clarity
        public Assembly GetSatelliteAssembly(CultureInfo culture)
        {
            if (culture == null)
            {
                throw new ArgumentNullException("culture");
            }

            Assembly assm = null;
            string baseName = this.FullName;
            string cultureName;

            while (assm == null && (cultureName = culture.Name) != "")
            {
                string assmName = baseName + "." + cultureName;

                assm = Assembly.Load(assmName, false);

                culture = culture.Parent;
            }

            if (assm == null)
            {
                throw new ArgumentException();
                // FIXME -- throw new FileNotFoundException();
            }

            return assm;
        }
コード例 #24
0
        static string GetJQueryDateFormatFor(string language)
        {
            var culture = new System.Globalization.CultureInfo(language);
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;

            return DateFormatter.CurrentJQuery;
        }
コード例 #25
0
ファイル: Utility.cs プロジェクト: SDRC-India/sdrcdevinfo
        internal static string GetDataValueRangeFilderString(DataValueFilter dataValueFilter)
        {
            string WhereClause = " WHERE NOT (";
            string CurrentThreadDecimalChar = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            string InvariantCultureDecimalChar = new System.Globalization.CultureInfo("en-US").NumberFormat.NumberDecimalSeparator;
            switch (dataValueFilter.OpertorType)
            {
                case OpertorType.EqualTo:
                    WhereClause += " VAL([" + Data.DataValue + "]) = " + dataValueFilter.FromDataValue.ToString().Replace(CurrentThreadDecimalChar, InvariantCultureDecimalChar);
                    break;
                case OpertorType.Between:
                    //Inclusive of min & max values as per ANSI SQL
                    WhereClause += "(VAL([" + Data.DataValue + "]) >= " + dataValueFilter.FromDataValue.ToString().Replace(CurrentThreadDecimalChar, InvariantCultureDecimalChar) + " AND VAL([" + Data.DataValue + "]) <= " + dataValueFilter.ToDataValue.ToString().Replace(CurrentThreadDecimalChar, InvariantCultureDecimalChar) + ")";
                    break;
                case OpertorType.GreaterThan:
                    WhereClause += "(VAL([" + Data.DataValue + "]) > " + dataValueFilter.FromDataValue.ToString().Replace(CurrentThreadDecimalChar, InvariantCultureDecimalChar) + ")";
                    break;
                case OpertorType.LessThan:
                    WhereClause += "(VAL([" + Data.DataValue + "]) < " + dataValueFilter.ToDataValue.ToString().Replace(CurrentThreadDecimalChar, InvariantCultureDecimalChar) + ")";
                    break;
            }

            WhereClause += " )";

            return WhereClause;
        }
コード例 #26
0
 /// <summary>
 /// Remove all photos not referenced by any album
 /// David
 /// </summary>
 /// <returns>Number of photos removed</returns>
 public static int cleanUpPhotos()
 {
     int totalRemoved = 0;
     System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
     List<AllImagesInfo> _allImageInfo = getAllImageInfo();
     foreach(string photoPath in Directory.GetFiles(Directory.GetCurrentDirectory() + "\\Photos","*.*",SearchOption.AllDirectories).Where(s=>s.EndsWith(".jpg",true,ci) || s.EndsWith(".png",true,ci) || s.EndsWith(".jpeg",true,ci) || s.EndsWith(".gif",true,ci) || s.EndsWith(".bmp",true,ci)))
     {
         if (!_allImageInfo.Exists(x => x.path == photoPath))
         {
             try
             {
                 if (File.Exists(photoPath))
                 {
                     File.Delete(photoPath);
                     totalRemoved++;
                 }
                 else
                 {
                     throw new Exception("File path does not exist!!");
                 }
             }catch(Exception e){
                 System.Windows.Forms.MessageBox.Show("An error has occurred trying to remove photos. " + e.Message,"Error",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Error);
             }
         }
     }
     return totalRemoved;
 }
コード例 #27
0
		//�Private�Methods�(4)�

        

        private void menuAccept_Click(object sender, EventArgs e)
        {
            IFormatProvider format = new System.Globalization.CultureInfo(1033);
            ClientSettings.UseGPS = chkGPS.Checked;
            ClientSettings.CheckVersion = chkVersion.Checked;
            ClientSettings.AutoTranslate = chkTranslate.Checked;
            ClientSettings.UseSkweezer = chkSkweezer.Checked;
            
            if (ClientSettings.UpdateMinutes != int.Parse(txtUpdate.Text, format))
            {
                MessageBox.Show("You will need to restart PockeTwit for the update interval to change.", "PockeTwit");
                ClientSettings.UpdateMinutes = int.Parse(txtUpdate.Text, format);
            }
            if (ClientSettings.CacheDir != txtCaheDir.Text)
            {
                try
                {
                    if (!System.IO.Directory.Exists(txtCaheDir.Text))
                    {
                        System.IO.Directory.CreateDirectory(txtCaheDir.Text);
                    }
                    ClientSettings.CacheDir = txtCaheDir.Text;
                }
                catch
                {
                    MessageBox.Show("Unable to use that folder as a cache directory");
                }
            }
            ClientSettings.SaveSettings();
            
            this.DialogResult = DialogResult.OK;
            this.Close();

        }
コード例 #28
0
 public static string RoundFloatToString(float floatToRound)
 {
     System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US");
     cultureInfo.NumberFormat.CurrencyDecimalDigits = 2;
     cultureInfo.NumberFormat.CurrencyDecimalSeparator = ".";
     return floatToRound.ToString("F", cultureInfo);
 }
コード例 #29
0
 public static SpeechRecognitionEngine getEngine(String lang)
 {
     if(init)
         recEngine.Dispose();
     Console.WriteLine("Kastat current engine");
     culture = new System.Globalization.CultureInfo(lang);
     choices = new Choices();
     grammarBuilder = new GrammarBuilder();
     VoiceCommands.Init(lang);
     choices.Add(VoiceCommands.GetAllCommands());
     grammarBuilder.Culture = culture;
     grammarBuilder.Append(choices);
     grammar = new Grammar(grammarBuilder);
     Console.WriteLine("Initialiserat svenskt grammar");
     try
     {
         recEngine = new SpeechRecognitionEngine(culture);
         recEngine.LoadGrammarAsync(grammar);
         Console.WriteLine("Laddat enginen med " + lang);
     }
     catch (UnauthorizedAccessException e)
     {
         Console.WriteLine("Error: UnauthorizedAccessException");
         Console.WriteLine(e.ToString());
     } 
     init = true;
     recEngine.SetInputToDefaultAudioDevice();
     return recEngine;
 }
コード例 #30
0
		protected override System.Globalization.CultureInfo getSystemCultureInfo()
		{
			var netLanguage = "en";
			var prefLanguageOnly = "en";
			if (NSLocale.PreferredLanguages.Length > 0)
			{
				var pref = NSLocale.PreferredLanguages[0];
				prefLanguageOnly = pref.Substring(0, 2);
				if (prefLanguageOnly == "pt")
				{
					if (pref == "pt")
						pref = "pt-BR"; // get the correct Brazilian language strings from the PCL RESX (note the local iOS folder is still "pt")
					else
						pref = "pt-PT"; // Portugal
				}
				netLanguage = pref.Replace("_", "-");
				Console.WriteLine("preferred language:" + netLanguage);
			}
			System.Globalization.CultureInfo ci = null;
			try
			{
				ci = new System.Globalization.CultureInfo(netLanguage);
			}
			catch
			{
				// iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
				// fallback to first characters, in this case "en"
				ci = new System.Globalization.CultureInfo(prefLanguageOnly);
			}
			return ci;
		}
コード例 #31
0
 public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
 {
     throw new Exception("The method or operation is not implemented.");
 }
コード例 #32
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     throw new NotImplementedException();
 }
        public CaseInsensitiveComparer(System.Globalization.CultureInfo !culture)
        {
            CodeContract.Requires(culture != null);

            return(default(CaseInsensitiveComparer));
        }
コード例 #34
0
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            ASObject aso = value as ASObject;

            object instance = Activator.CreateInstance(destinationType);

            if (instance != null)
            {
                foreach (string memberName in aso.Keys)
                {
                    object val = aso[memberName];
                    //MemberInfo mi = ReflectionUtils.GetMember(destinationType, key, MemberTypes.Field | MemberTypes.Property);
                    //if (mi != null)
                    //    ReflectionUtils.SetMemberValue(mi, result, aso[key]);

                    PropertyInfo propertyInfo = null;
                    try
                    {
                        propertyInfo = destinationType.GetProperty(memberName);
                    }
                    catch (AmbiguousMatchException)
                    {
                        //To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.
                        propertyInfo = destinationType.GetProperty(memberName, BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
                    }
                    if (propertyInfo != null)
                    {
                        try
                        {
                            val = Convert.ChangeType(val, propertyInfo.PropertyType);
                            if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
                            {
                                if (propertyInfo.GetIndexParameters() == null || propertyInfo.GetIndexParameters().Length == 0)
                                {
                                    propertyInfo.SetValue(instance, val, null);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                    else
                    {
                        FieldInfo fi = destinationType.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
                        try
                        {
                            if (fi != null)
                            {
                                val = Convert.ChangeType(val, fi.FieldType);
                                fi.SetValue(instance, val);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }
            }
            return(instance);
        }
コード例 #35
0
		public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture )
		{
			Debug.Assert( values != null && values.Length == 9, "EdgeRouteToPathConverter should have 9 parameters: pos (1,2), size (3,4) of source; pos (5,6), size (7,8) of target; routeInformation (9)." );

			#region Get the inputs
			//get the position of the source
			Point sourcePos = new Point()
			                  	{
			                  		X = ( values[0] != DependencyProperty.UnsetValue ? (double)values[0] : 0.0 ),
			                  		Y = ( values[1] != DependencyProperty.UnsetValue ? (double)values[1] : 0.0 )
			                  	};
			//get the size of the source
			Size sourceSize = new Size()
			                  	{
			                  		Width = ( values[2] != DependencyProperty.UnsetValue ? (double)values[2] : 0.0 ),
			                  		Height = ( values[3] != DependencyProperty.UnsetValue ? (double)values[3] : 0.0 )
			                  	};
			//get the position of the target
			Point targetPos = new Point()
			                  	{
			                  		X = ( values[4] != DependencyProperty.UnsetValue ? (double)values[4] : 0.0 ),
			                  		Y = ( values[5] != DependencyProperty.UnsetValue ? (double)values[5] : 0.0 )
			                  	};
			//get the size of the target
			Size targetSize = new Size()
			                  	{
			                  		Width = ( values[6] != DependencyProperty.UnsetValue ? (double)values[6] : 0.0 ),
			                  		Height = ( values[7] != DependencyProperty.UnsetValue ? (double)values[7] : 0.0 )
			                  	};

			//get the route informations
			Point[] routeInformation = ( values[8] != DependencyProperty.UnsetValue ? (Point[])values[8] : null );
			#endregion
			bool hasRouteInfo = routeInformation != null && routeInformation.Length > 0;

			//
			// Create the path
			//
			Point p1 = GraphConverterHelper.CalculateAttachPoint( sourcePos, sourceSize, ( hasRouteInfo ? routeInformation[0] : targetPos ) );
			Point p2 = GraphConverterHelper.CalculateAttachPoint( targetPos, targetSize, ( hasRouteInfo ? routeInformation[routeInformation.Length - 1] : sourcePos ) );


			PathSegment[] segments = new PathSegment[1 + ( hasRouteInfo ? routeInformation.Length : 0 )];
			if ( hasRouteInfo )
				//append route points
				for ( int i = 0; i < routeInformation.Length; i++ )
					segments[i] = new LineSegment( routeInformation[i], true );

			Point pLast = ( hasRouteInfo ? routeInformation[routeInformation.Length - 1] : p1 );
			Vector v = pLast - p2;
			v = v / v.Length * 5;
			Vector n = new Vector( -v.Y, v.X ) * 0.3;

			segments[segments.Length - 1] = new LineSegment( p2 + v, true );

			PathFigureCollection pfc = new PathFigureCollection( 2 );
			pfc.Add( new PathFigure( p1, segments, false ) );
			pfc.Add( new PathFigure( p2,
			                         new PathSegment[] {
			                                           	new LineSegment(p2 + v - n, true),
			                                           	new LineSegment(p2 + v + n, true)}, true ) );
			
			return pfc;
		}
コード例 #36
0
 public object Convert(object value, Type targetType, object parameter,
                       System.Globalization.CultureInfo culture)
 => value.Equals(parameter);
コード例 #37
0
 public object ConvertBack(object value, Type targetType, object parameter,
                           System.Globalization.CultureInfo culture)
 => value.Equals(true) ? parameter : Binding.DoNothing;
コード例 #38
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(value as string == "auto" ? "0" : value);
 }
コード例 #39
0
        public override string GetProperty(string strPropertyName, string strFormat, System.Globalization.CultureInfo formatProvider, DotNetNuke.Entities.Users.UserInfo accessingUser, DotNetNuke.Services.Tokens.Scope accessLevel, ref bool propertyNotFound)
        {
            switch (strPropertyName.ToLower())
            {
            case "title":     // NVarChar
                if (Title == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(Title, strFormat));

            case "conferenceid":     // Int
                return(ConferenceId.ToString(strFormat, formatProvider));

            case "sessiondateandtime":     // DateTime
                if (SessionDateAndTime == null)
                {
                    return("");
                }
                ;
                return(((DateTime)SessionDateAndTime).ToString(strFormat, formatProvider));

            case "sessionend":     // DateTime
                if (SessionEnd == null)
                {
                    return("");
                }
                ;
                return(((DateTime)SessionEnd).ToString(strFormat, formatProvider));

            case "displayname":     // NVarChar
                return(PropertyAccess.FormatString(DisplayName, strFormat));

            case "email":     // NVarChar
                if (Email == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(Email, strFormat));

            case "company":     // NVarChar
                if (Company == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(Company, strFormat));

            case "attcode":     // NVarChar
                if (AttCode == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(AttCode, strFormat));

            case "sessionattendeename":     // NVarChar
                return(PropertyAccess.FormatString(SessionAttendeeName, strFormat));

            case "reviewstars": // Int
                return(ReviewStars.ToString(strFormat, formatProvider));

            case "createdbyuser":     // NVarChar
                if (CreatedByUser == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(CreatedByUser, strFormat));

            case "lastmodifiedbyuser":     // NVarChar
                if (LastModifiedByUser == null)
                {
                    return("");
                }
                ;
                return(PropertyAccess.FormatString(LastModifiedByUser, strFormat));

            default:
                return(base.GetProperty(strPropertyName, strFormat, formatProvider, accessingUser, accessLevel, ref propertyNotFound));
            }
        }
コード例 #40
0
        public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
        {
            Thickness thickness = (Thickness)value;

            return(thickness.Left);
        }
コード例 #41
0
 /// <summary>
 /// Converts the <paramref name="value"/> to a formatted string using the
 /// format specified in the constructor.
 /// </summary>
 /// <param name="value">The value to format.</param>
 /// <param name="targetType">The target output type (ignored).</param>
 /// <param name="parameter">Optional parameter (ignored).</param>
 /// <param name="culture">The culture to use in the format operation.</param>
 /// <returns>The formatted string</returns>
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(string.Format(System.Globalization.CultureInfo.CurrentUICulture, this.formatString, value));
 }
コード例 #42
0
        // convert height and width inside settings to "auto" if its 0 or lower. Just calculate this size by using the dimensions of the real image
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var val = value.ToString();

            return(val == null || int.Parse(val) < 1 ? "auto" : value);
        }
コード例 #43
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool val = value != null;

            return(val ? TrueValue : FalseValue);
        }
コード例 #44
0
 public void SetCulture(System.Globalization.CultureInfo culture)
 {
     settings.culture = culture;
 }
コード例 #45
0
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return(vmPing.Classes.ApplicationOptions.FontSize_Scanner);
            }

            switch ((vmPing.Classes.ProbeType)value)
            {
            case vmPing.Classes.ProbeType.Ping:
                return(vmPing.Classes.ApplicationOptions.FontSize_Probe);

            default:
                return(vmPing.Classes.ApplicationOptions.FontSize_Scanner);
            }
        }
コード例 #46
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(TrueValue.Equals(value) ? 1 : 0);
 }
コード例 #47
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(null);
 }
コード例 #48
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(new SettingValue <bool>(!(bool)(value ?? false)));
 }
コード例 #49
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return((TheEnum)Enum.Parse(typeof(TheEnum), value.ToString(), true));
 }
コード例 #50
0
ファイル: BooleanConverter.cs プロジェクト: sanlonezhang/ql
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(ToDescription(value));
 }
コード例 #51
0
        //This runs as an independant thread and uploads the STATUS generated from the hcAttack
        //This thread is run on a dynamic timer based on the size of the queue and will range from a base 2500ms down to 200ms
        //There is very little discruption to the attack as a very quick lock/unlock is performed on the packet list to pop the job off the queue
        public void threadPeriodicUpdate(ref List <Packets> uploadPackets, ref object objPacketlock)
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator    = ".";
            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };                                              //Initis the json class
            solveProps    sProps        = new solveProps(); //Init the properties to build our json string
            List <string> receivedZaps  = new List <string> {
            };                                              //List to store incoming zaps for writing
            string        ret           = "";               //Return string from json post
            string        jsonString    = "";
            string        zapfilePath   = zapPath + hashlistID.ToString();
            long          zapCount      = 0;
            List <string> batchList     = new List <string> {
            };
            double         chunkPercent = 0;
            double         chunkStart   = 0;
            Boolean        run          = true;
            List <Packets> singlePacket = new List <Packets> {
            };
            int  sleepTime = 2500;
            long ulQueue   = 0;

            hcClass.debugFlag = debugFlag;
            Boolean firstRun = true;

            string oPath = Path.Combine(tasksPath, taskID + "_" + chunkNo + ".txt"); // Path to write th -o file

            while (run)
            {
                Thread.Sleep(sleepTime); //Delay this thread for 2.5 seconds, if this falls behind it will batch the jobs
                lock (objPacketlock)
                {
                    if (uploadPackets.Count > 0)
                    {
                        singlePacket.Add(uploadPackets[0]);
                        ulQueue = uploadPackets.Count;
                        uploadPackets.RemoveAt(0);
                        if (uploadPackets.Count > 3)
                        {
                            sleepTime = 200; //Decrese the time we process the queue
                        }
                    }
                    else
                    {
                        sleepTime = 5000; //Decrese the time we process the queue
                    }
                    firstRun = false;
                }

                if (firstRun == true) //This is a work around to send a server a dummy stat to prevent timeouts on the initial start
                {
                    sProps.token            = client.tokenID;
                    sProps.chunkId          = chunkNo;
                    sProps.keyspaceProgress = skip;

                    sProps.relativeProgress = 0;

                    sProps.speed  = 0;
                    sProps.state  = 3; //Can't find the status code list lets try 3
                    sProps.cracks = new List <string>();

                    jsonString = jsC.toJson(sProps);
                    ret        = jsC.jsonSend(jsonString);

                    if (!jsC.isJsonSuccess(ret)) //If we received error, eg task was removed just break
                    {
                        break;
                    }
                }

                if (singlePacket.Count == 0)
                {
                    firstRun = false;
                    continue;
                }

                try
                {
                    {
                        //Special override as there is a possible race condition in HC, where STATUS4 doesn't give 100%
                        if (singlePacket[0].statusPackets["STATUS"] == 4 + offset)
                        {
                            singlePacket[0].statusPackets["PROGRESS1"] = singlePacket[0].statusPackets["PROGRESS2"];
                        }

                        sProps.token            = client.tokenID;
                        sProps.chunkId          = chunkNo;
                        sProps.keyspaceProgress = singlePacket[0].statusPackets["CURKU"];


                        chunkStart   = Math.Floor(singlePacket[0].statusPackets["PROGRESS2"]) / (skip + length) * skip;
                        chunkPercent = Math.Round((Convert.ToDouble(singlePacket[0].statusPackets["PROGRESS1"]) - chunkStart) / Convert.ToDouble(singlePacket[0].statusPackets["PROGRESS2"] - chunkStart), 4) * 10000;

                        sProps.relativeProgress = chunkPercent;

                        //sProps.total = singlePacket[0].statusPackets["PROGRESS2"];
                        sProps.speed = singlePacket[0].statusPackets["SPEED_TOTAL"];
                        sProps.state = singlePacket[0].statusPackets["STATUS"] - offset; //Client-side workaround for old STATUS on server

                        if (singlePacket[0].crackedPackets.Count > 200)
                        {
                            int max = 200;

                            //Process the requests in batches of 1000
                            while (singlePacket[0].crackedPackets.Count != 0)
                            {
                                List <string> subChunk = new List <string>(singlePacket[0].crackedPackets.GetRange(0, max));
                                singlePacket[0].crackedPackets.RemoveRange(0, max);
                                if (singlePacket[0].crackedPackets.Count < max)
                                {
                                    max = singlePacket[0].crackedPackets.Count;
                                }

                                if (stipPath == true)
                                {
                                    for (int i = 0; i <= subChunk.Count - 1; i++)
                                    {
                                        subChunk[i] = subChunk[i].Replace(actualHLpath + ":", "");
                                    }
                                }

                                sProps.cracks = subChunk;
                                jsonString    = jsC.toJson(sProps);
                                ret           = jsC.jsonSend(jsonString);

                                if (!jsC.isJsonSuccess(ret)) //If we received error, eg task was removed just break
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (stipPath == true)
                            {
                                for (int i = 0; i <= singlePacket[0].crackedPackets.Count - 1; i++)
                                {
                                    singlePacket[0].crackedPackets[i] = singlePacket[0].crackedPackets[i].Replace(actualHLpath + ":", "");
                                }
                            }
                            sProps.cracks = singlePacket[0].crackedPackets;

                            jsonString = jsC.toJson(sProps);
                            ret        = jsC.jsonSend(jsonString);
                        }
                    }


                    if (jsC.isJsonSuccess(ret))
                    {
                        if (jsC.getRetVar(ret, "agent") == "stop") //Special command sent by server, possibly undocumented
                        {
                            hcClass.hcProc.CancelOutputRead();
                            hcClass.hcProc.CancelErrorRead();
                            hcClass.hcProc.Kill();
                            run = false;
                            Console.WriteLine("Server has instructed the client terminate the task via stop");
                        }


                        chunkPercent = chunkPercent / 100;          //We already calculated with * 10000 earlier

                        receivedZaps = jsC.getRetList(ret, "zaps"); //Check whether the server sent out hashes to zap
                        if (receivedZaps.Count > 0)
                        {
                            zapCount++;
                            File.WriteAllLines(Path.Combine(zapfilePath, zapCount.ToString()), receivedZaps); //Write hashes for zapping
                        }
                        Console.WriteLine("Progress:{0,7} | Speed:{1,-4} | Cracks:{2,-4} | Accepted:{3,-4} | Zapped:{4,-4} | Queue:{5,-2}", chunkPercent.ToString("F") + "%", speedCalc(singlePacket[0].statusPackets["SPEED_TOTAL"]), singlePacket[0].crackedPackets.Count, jsC.getRetVar(ret, "cracked"), receivedZaps.Count, ulQueue);
                        receivedZaps.Clear();
                    }


                    else //We received an error from the server, terminate the run
                    {
                        string writeCracked = Path.Combine(hashpath, Path.GetFileName(hashlistID.ToString())) + ".cracked";
                        Console.WriteLine("Writing any cracks in queue to file " + writeCracked);
                        File.AppendAllLines(writeCracked, singlePacket[0].crackedPackets);
                        lock (objPacketlock)
                        {
                            if (uploadPackets.Count > 0)
                            {
                                for (int i = 0; i < uploadPackets.Count; i++)
                                {
                                    if (uploadPackets[i].crackedPackets.Count > 0)
                                    {
                                        File.AppendAllLines(writeCracked, uploadPackets[i].crackedPackets);
                                    }
                                }
                            }
                        }

                        run = false; //Potentially we can change this so keep submitting the rest of the cracked queue instead of terminating

                        if (!hcClass.hcProc.HasExited)
                        {
                            hcClass.hcProc.CancelOutputRead();
                            hcClass.hcProc.CancelErrorRead();
                            hcClass.hcProc.Kill();
                            //The server would need to accept the chunk but return an error
                        }
                        break;
                    }


                    {
                        if (singlePacket[0].statusPackets["STATUS"] >= 4 + offset) //We are the last upload task
                        //if (singlePacket[0].statusPackets["STATUS"] >= 5) //Uncomment this line, and comment above line for upcoming HC > 3.6
                        {
                            Console.WriteLine("Finished processing chunk");
                            singlePacket.Clear();
                            run = false;
                        }
                        else
                        {
                            singlePacket.RemoveAt(0);
                        }
                    }
                }


                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Error processing packet for upload");
                }
            }
        }
コード例 #52
0
        protected override string Convert(int value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var ts = TimeSpan.FromSeconds(value);

            return(string.Format("{0}", ts.ToString(@"mm\:ss")));
        }
コード例 #53
0
 protected virtual void ValidateMember(System.Globalization.CultureInfo culture, string memberName, System.Collections.Generic.IList <CodeFluent.Runtime.CodeFluentValidationException> results)
 {
 }
コード例 #54
0
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(value.ToString());
 }
コード例 #55
0
        string CodeFluent.Runtime.ICodeFluentValidator.Validate(System.Globalization.CultureInfo culture)
        {
            string localValidate = this.Validate(culture);

            return(localValidate);
        }
コード例 #56
0
        /// <summary>Renders all default HUD elements</summary>
        /// <param name="Element">The HUD element these are to be rendererd onto</param>
        /// <param name="TimeElapsed">The time elapsed</param>
        private static void RenderHUDElement(HUD.Element Element, double TimeElapsed)
        {
            TrainManager.TrainDoorState      LeftDoors  = TrainManager.GetDoorsState(TrainManager.PlayerTrain, true, false);
            TrainManager.TrainDoorState      RightDoors = TrainManager.GetDoorsState(TrainManager.PlayerTrain, false, true);
            System.Globalization.CultureInfo Culture    = System.Globalization.CultureInfo.InvariantCulture;
            string Command = Element.Subject.ToLowerInvariant();
            // default
            double w, h;

            if (Element.CenterMiddle.BackgroundTexture != null)
            {
                if (Program.CurrentHost.LoadTexture(Element.CenterMiddle.BackgroundTexture, OpenGlTextureWrapMode.ClampClamp))
                {
                    w = (double)Element.CenterMiddle.BackgroundTexture.Width;
                    h = (double)Element.CenterMiddle.BackgroundTexture.Height;
                }
                else
                {
                    w = 0.0; h = 0.0;
                }
            }
            else
            {
                w = 0.0; h = 0.0;
            }
            double x = Element.Alignment.X < 0 ? 0.0 : Element.Alignment.X == 0 ? 0.5 * (LibRender.Screen.Width - w) : LibRender.Screen.Width - w;
            double y = Element.Alignment.Y < 0 ? 0.0 : Element.Alignment.Y == 0 ? 0.5 * (LibRender.Screen.Height - h) : LibRender.Screen.Height - h;

            x += Element.Position.X;
            y += Element.Position.Y;
            // command
            const double speed = 1.0;
            MessageColor sc    = MessageColor.None;
            string       t;

            switch (Command)
            {
            case "reverser":
                if (TrainManager.PlayerTrain.Handles.Reverser.Driver < 0)
                {
                    sc = MessageColor.Orange;
                    if (TrainManager.PlayerTrain.ReverserDescriptions != null && TrainManager.PlayerTrain.ReverserDescriptions.Length > 2)
                    {
                        t = TrainManager.PlayerTrain.ReverserDescriptions[2];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleBackward;
                    }
                }
                else if (TrainManager.PlayerTrain.Handles.Reverser.Driver > 0)
                {
                    sc = MessageColor.Blue;
                    if (TrainManager.PlayerTrain.ReverserDescriptions != null && TrainManager.PlayerTrain.ReverserDescriptions.Length > 0)
                    {
                        t = TrainManager.PlayerTrain.ReverserDescriptions[0];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleForward;
                    }
                }
                else
                {
                    sc = MessageColor.Gray;
                    if (TrainManager.PlayerTrain.ReverserDescriptions != null && TrainManager.PlayerTrain.ReverserDescriptions.Length > 1)
                    {
                        t = TrainManager.PlayerTrain.ReverserDescriptions[1];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleNeutral;
                    }
                }
                Element.TransitionState = 0.0;
                break;

            case "power":
                if (TrainManager.PlayerTrain.Handles.SingleHandle)
                {
                    return;
                }
                if (TrainManager.PlayerTrain.Handles.Power.Driver == 0)
                {
                    sc = MessageColor.Gray;
                    if (TrainManager.PlayerTrain.PowerNotchDescriptions != null && TrainManager.PlayerTrain.PowerNotchDescriptions.Length > 0)
                    {
                        t = TrainManager.PlayerTrain.PowerNotchDescriptions[0];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandlePowerNull;
                    }
                }
                else
                {
                    sc = MessageColor.Blue;
                    if (TrainManager.PlayerTrain.PowerNotchDescriptions != null && TrainManager.PlayerTrain.Handles.Power.Driver < TrainManager.PlayerTrain.PowerNotchDescriptions.Length)
                    {
                        t = TrainManager.PlayerTrain.PowerNotchDescriptions[TrainManager.PlayerTrain.Handles.Power.Driver];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandlePower + TrainManager.PlayerTrain.Handles.Power.Driver.ToString(Culture);
                    }
                }
                Element.TransitionState = 0.0;
                break;

            case "brake":
                if (TrainManager.PlayerTrain.Handles.SingleHandle)
                {
                    return;
                }
                if (TrainManager.PlayerTrain.Handles.Brake is TrainManager.AirBrakeHandle)
                {
                    if (TrainManager.PlayerTrain.Handles.EmergencyBrake.Driver)
                    {
                        sc = MessageColor.Red;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 0)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[0];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleEmergency;
                        }
                    }
                    else if (TrainManager.PlayerTrain.Handles.Brake.Driver == (int)TrainManager.AirBrakeHandleState.Release)
                    {
                        sc = MessageColor.Gray;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 1)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[1];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleRelease;
                        }
                    }
                    else if (TrainManager.PlayerTrain.Handles.Brake.Driver == (int)TrainManager.AirBrakeHandleState.Lap)
                    {
                        sc = MessageColor.Blue;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 2)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[2];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleLap;
                        }
                    }
                    else
                    {
                        sc = MessageColor.Orange;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 3)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[3];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleService;
                        }
                    }
                }
                else
                {
                    if (TrainManager.PlayerTrain.Handles.EmergencyBrake.Driver)
                    {
                        sc = MessageColor.Red;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 0)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[0];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleEmergency;
                        }
                    }
                    else if (TrainManager.PlayerTrain.Handles.HoldBrake.Driver)
                    {
                        sc = MessageColor.Green;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 2)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[2];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleHoldBrake;
                        }
                    }
                    else if (TrainManager.PlayerTrain.Handles.Brake.Driver == 0)
                    {
                        sc = MessageColor.Gray;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 1)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[1];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleBrakeNull;
                        }
                    }
                    else
                    {
                        sc = MessageColor.Orange;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && ((TrainManager.PlayerTrain.Handles.HasHoldBrake && TrainManager.PlayerTrain.Handles.Brake.Driver + 2 < TrainManager.PlayerTrain.BrakeNotchDescriptions.Length) || (!TrainManager.PlayerTrain.Handles.HasHoldBrake && TrainManager.PlayerTrain.Handles.Brake.Driver + 1 < TrainManager.PlayerTrain.BrakeNotchDescriptions.Length)))
                        {
                            t = TrainManager.PlayerTrain.Handles.HasHoldBrake ? TrainManager.PlayerTrain.BrakeNotchDescriptions[TrainManager.PlayerTrain.Handles.Brake.Driver + 2] : TrainManager.PlayerTrain.BrakeNotchDescriptions[TrainManager.PlayerTrain.Handles.Brake.Driver + 1];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleBrake + TrainManager.PlayerTrain.Handles.Brake.Driver.ToString(Culture);
                        }
                    }
                }
                Element.TransitionState = 0.0;
                break;

            case "locobrake":
                if (!TrainManager.PlayerTrain.Handles.HasLocoBrake)
                {
                    return;
                }

                if (TrainManager.PlayerTrain.Handles.LocoBrake is TrainManager.LocoAirBrakeHandle)
                {
                    if (TrainManager.PlayerTrain.Handles.LocoBrake.Driver == (int)TrainManager.AirBrakeHandleState.Release)
                    {
                        sc = MessageColor.Gray;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 1)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[1];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleRelease;
                        }
                    }
                    else if (TrainManager.PlayerTrain.Handles.LocoBrake.Driver == (int)TrainManager.AirBrakeHandleState.Lap)
                    {
                        sc = MessageColor.Blue;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 2)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[2];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleLap;
                        }
                    }
                    else
                    {
                        sc = MessageColor.Orange;
                        if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 3)
                        {
                            t = TrainManager.PlayerTrain.BrakeNotchDescriptions[3];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleService;
                        }
                    }
                }
                else
                {
                    if (TrainManager.PlayerTrain.Handles.LocoBrake.Driver == 0)
                    {
                        sc = MessageColor.Gray;
                        if (TrainManager.PlayerTrain.LocoBrakeNotchDescriptions != null && TrainManager.PlayerTrain.LocoBrakeNotchDescriptions.Length > 1)
                        {
                            t = TrainManager.PlayerTrain.LocoBrakeNotchDescriptions[1];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleBrakeNull;
                        }
                    }
                    else
                    {
                        sc = MessageColor.Orange;
                        if (TrainManager.PlayerTrain.LocoBrakeNotchDescriptions != null && TrainManager.PlayerTrain.Handles.LocoBrake.Driver < TrainManager.PlayerTrain.LocoBrakeNotchDescriptions.Length)
                        {
                            t = TrainManager.PlayerTrain.LocoBrakeNotchDescriptions[TrainManager.PlayerTrain.Handles.LocoBrake.Driver];
                        }
                        else
                        {
                            t = Translations.QuickReferences.HandleLocoBrake + TrainManager.PlayerTrain.Handles.LocoBrake.Driver.ToString(Culture);
                        }
                    }
                }
                Element.TransitionState = 0.0;
                break;

            case "single":
                if (!TrainManager.PlayerTrain.Handles.SingleHandle)
                {
                    return;
                }
                if (TrainManager.PlayerTrain.Handles.EmergencyBrake.Driver)
                {
                    sc = MessageColor.Red;
                    if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 0)
                    {
                        t = TrainManager.PlayerTrain.BrakeNotchDescriptions[0];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleEmergency;
                    }
                }
                else if (TrainManager.PlayerTrain.Handles.HoldBrake.Driver)
                {
                    sc = MessageColor.Green;
                    if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.BrakeNotchDescriptions.Length > 1)
                    {
                        t = TrainManager.PlayerTrain.BrakeNotchDescriptions[1];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleHoldBrake;
                    }
                }
                else if (TrainManager.PlayerTrain.Handles.Brake.Driver > 0)
                {
                    sc = MessageColor.Orange;
                    if (TrainManager.PlayerTrain.BrakeNotchDescriptions != null && TrainManager.PlayerTrain.Handles.Brake.Driver + 3 < TrainManager.PlayerTrain.BrakeNotchDescriptions.Length)
                    {
                        t = TrainManager.PlayerTrain.BrakeNotchDescriptions[TrainManager.PlayerTrain.Handles.Brake.Driver + 3];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandleBrake + TrainManager.PlayerTrain.Handles.Brake.Driver.ToString(Culture);
                    }
                }
                else if (TrainManager.PlayerTrain.Handles.Power.Driver > 0)
                {
                    sc = MessageColor.Blue;
                    if (TrainManager.PlayerTrain.PowerNotchDescriptions != null && TrainManager.PlayerTrain.Handles.Power.Driver < TrainManager.PlayerTrain.PowerNotchDescriptions.Length)
                    {
                        t = TrainManager.PlayerTrain.PowerNotchDescriptions[TrainManager.PlayerTrain.Handles.Power.Driver];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandlePower + TrainManager.PlayerTrain.Handles.Power.Driver.ToString(Culture);
                    }
                }
                else
                {
                    sc = MessageColor.Gray;
                    if (TrainManager.PlayerTrain.PowerNotchDescriptions != null && TrainManager.PlayerTrain.PowerNotchDescriptions.Length > 0)
                    {
                        t = TrainManager.PlayerTrain.PowerNotchDescriptions[0];
                    }
                    else
                    {
                        t = Translations.QuickReferences.HandlePowerNull;
                    }
                }
                Element.TransitionState = 0.0;
                break;

            case "doorsleft":
            case "doorsright":
            {
                if ((LeftDoors & TrainManager.TrainDoorState.AllClosed) == 0 | (RightDoors & TrainManager.TrainDoorState.AllClosed) == 0)
                {
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                }
                TrainManager.TrainDoorState Doors = Command == "doorsleft" ? LeftDoors : RightDoors;
                if ((Doors & TrainManager.TrainDoorState.Mixed) != 0)
                {
                    sc = MessageColor.Orange;
                }
                else if ((Doors & TrainManager.TrainDoorState.AllClosed) != 0)
                {
                    sc = MessageColor.Gray;
                }
                else if (TrainManager.PlayerTrain.Specs.DoorCloseMode == TrainManager.DoorMode.Manual)
                {
                    sc = MessageColor.Green;
                }
                else
                {
                    sc = MessageColor.Blue;
                }
                t = Command == "doorsleft" ? Translations.QuickReferences.DoorsLeft : Translations.QuickReferences.DoorsRight;
            } break;

            case "stopleft":
            case "stopright":
            case "stopnone":
            {
                int s = TrainManager.PlayerTrain.Station;
                if (s >= 0 && Game.Stations[s].PlayerStops() && Interface.CurrentOptions.GameMode != Interface.GameMode.Expert)
                {
                    bool cond;
                    if (Command == "stopleft")
                    {
                        cond = Game.Stations[s].OpenLeftDoors;
                    }
                    else if (Command == "stopright")
                    {
                        cond = Game.Stations[s].OpenRightDoors;
                    }
                    else
                    {
                        cond = !Game.Stations[s].OpenLeftDoors & !Game.Stations[s].OpenRightDoors;
                    }
                    if (TrainManager.PlayerTrain.StationState == TrainManager.TrainStopState.Pending & cond)
                    {
                        Element.TransitionState -= speed * TimeElapsed;
                        if (Element.TransitionState < 0.0)
                        {
                            Element.TransitionState = 0.0;
                        }
                    }
                    else
                    {
                        Element.TransitionState += speed * TimeElapsed;
                        if (Element.TransitionState > 1.0)
                        {
                            Element.TransitionState = 1.0;
                        }
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                }
                t = Element.Text;
            } break;

            case "stoplefttick":
            case "stoprighttick":
            case "stopnonetick":
            {
                int s = TrainManager.PlayerTrain.Station;
                if (s >= 0 && Game.Stations[s].PlayerStops() && Interface.CurrentOptions.GameMode != Interface.GameMode.Expert)
                {
                    int c = Game.Stations[s].GetStopIndex(TrainManager.PlayerTrain.Cars.Length);
                    if (c >= 0)
                    {
                        bool cond;
                        if (Command == "stoplefttick")
                        {
                            cond = Game.Stations[s].OpenLeftDoors;
                        }
                        else if (Command == "stoprighttick")
                        {
                            cond = Game.Stations[s].OpenRightDoors;
                        }
                        else
                        {
                            cond = !Game.Stations[s].OpenLeftDoors & !Game.Stations[s].OpenRightDoors;
                        }
                        if (TrainManager.PlayerTrain.StationState == TrainManager.TrainStopState.Pending & cond)
                        {
                            Element.TransitionState -= speed * TimeElapsed;
                            if (Element.TransitionState < 0.0)
                            {
                                Element.TransitionState = 0.0;
                            }
                        }
                        else
                        {
                            Element.TransitionState += speed * TimeElapsed;
                            if (Element.TransitionState > 1.0)
                            {
                                Element.TransitionState = 1.0;
                            }
                        }
                        double d = TrainManager.PlayerTrain.StationDistanceToStopPoint;
                        double r;
                        if (d > 0.0)
                        {
                            r = d / Game.Stations[s].Stops[c].BackwardTolerance;
                        }
                        else
                        {
                            r = d / Game.Stations[s].Stops[c].ForwardTolerance;
                        }
                        if (r < -1.0)
                        {
                            r = -1.0;
                        }
                        if (r > 1.0)
                        {
                            r = 1.0;
                        }
                        y -= r * (double)Element.Value1;
                    }
                    else
                    {
                        Element.TransitionState += speed * TimeElapsed;
                        if (Element.TransitionState > 1.0)
                        {
                            Element.TransitionState = 1.0;
                        }
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                }
                t = Element.Text;
            } break;

            case "clock":
            {
                int hours   = (int)Math.Floor(Game.SecondsSinceMidnight);
                int seconds = hours % 60; hours /= 60;
                int minutes = hours % 60; hours /= 60;
                hours %= 24;
                t      = hours.ToString(Culture).PadLeft(2, '0') + ":" + minutes.ToString(Culture).PadLeft(2, '0') + ":" + seconds.ToString(Culture).PadLeft(2, '0');
                if (OptionClock)
                {
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                }
            } break;

            case "gradient":
                if (OptionGradient == GradientDisplayMode.Percentage)
                {
                    if (World.CameraTrackFollower.Pitch != 0)
                    {
                        double pc = World.CameraTrackFollower.Pitch;
                        t = Math.Abs(pc).ToString("0.00", Culture) + "%" + (Math.Abs(pc) == pc ? " ↗" : " ↘");
                    }
                    else
                    {
                        t = "Level";
                    }
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else if (OptionGradient == GradientDisplayMode.UnitOfChange)
                {
                    if (World.CameraTrackFollower.Pitch != 0)
                    {
                        double gr = 1000 / World.CameraTrackFollower.Pitch;
                        t = "1 in " + Math.Abs(gr).ToString("0", Culture) + (Math.Abs(gr) == gr ? " ↗" : " ↘");
                    }
                    else
                    {
                        t = "Level";
                    }
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else if (OptionGradient == GradientDisplayMode.Permil)
                {
                    if (World.CameraTrackFollower.Pitch != 0)
                    {
                        double pm = World.CameraTrackFollower.Pitch;
                        t = Math.Abs(pm).ToString("0.00", Culture) + "‰" + (Math.Abs(pm) == pm ? " ↗" : " ↘");
                    }
                    else
                    {
                        t = "Level";
                    }
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    if (World.CameraTrackFollower.Pitch != 0)
                    {
                        double gr = 1000 / World.CameraTrackFollower.Pitch;
                        t = "1 in " + Math.Abs(gr).ToString("0", Culture) + (Math.Abs(gr) == gr ? " ↗" : " ↘");
                    }
                    else
                    {
                        t = "Level";
                    }
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                } break;

            case "speed":
                if (OptionSpeed == SpeedDisplayMode.Kmph)
                {
                    double kmph = Math.Abs(TrainManager.PlayerTrain.CurrentSpeed) * 3.6;
                    t = kmph.ToString("0.00", Culture) + " km/h";
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else if (OptionSpeed == SpeedDisplayMode.Mph)
                {
                    double mph = Math.Abs(TrainManager.PlayerTrain.CurrentSpeed) * 2.2369362920544;
                    t = mph.ToString("0.00", Culture) + " mph";
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    double mph = Math.Abs(TrainManager.PlayerTrain.CurrentSpeed) * 2.2369362920544;
                    t = mph.ToString("0.00", Culture) + " mph";
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                } break;

            case "dist_next_station":
                int i;
                if (TrainManager.PlayerTrain.Station >= 0 && TrainManager.PlayerTrain.StationState != TrainManager.TrainStopState.Completed)
                {
                    i = TrainManager.PlayerTrain.LastStation;
                }
                else
                {
                    i = TrainManager.PlayerTrain.LastStation + 1;
                }
                if (i > Game.Stations.Length - 1)
                {
                    i = TrainManager.PlayerTrain.LastStation;
                }
                int    n  = Game.Stations[i].GetStopIndex(TrainManager.PlayerTrain.Cars.Length);
                double p0 = TrainManager.PlayerTrain.FrontCarTrackPosition();
                double p1;
                if (Game.Stations[i].Stops.Length > 0)
                {
                    p1 = Game.Stations[i].Stops[n].TrackPosition;
                }
                else
                {
                    p1 = Game.Stations[i].DefaultTrackPosition;
                }
                double m = p1 - p0;
                if (OptionDistanceToNextStation == DistanceToNextStationDisplayMode.Km)
                {
                    if (Game.Stations[i].PlayerStops())
                    {
                        t = "Stop: ";
                        if (Math.Abs(m) <= 10.0)
                        {
                            t += m.ToString("0.00", Culture) + " m";
                        }
                        else
                        {
                            m /= 1000.0;
                            t += m.ToString("0.000", Culture) + " km";
                        }
                    }
                    else
                    {
                        m /= 1000.0;
                        t  = "Pass: "******"0.000", Culture) + " km";
                    }
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else if (OptionDistanceToNextStation == DistanceToNextStationDisplayMode.Mile)
                {
                    m /= 1609.34;
                    if (Game.Stations[i].PlayerStops())
                    {
                        t = "Stop: ";
                    }
                    else
                    {
                        t = "Pass: "******"0.0000", Culture) + " miles";
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    m /= 1609.34;
                    if (Game.Stations[i].PlayerStops())
                    {
                        t = "Stop: ";
                    }
                    else
                    {
                        t = "Pass: "******"0.0000", Culture) + " miles";
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                } break;

            case "fps":
                int fps = (int)Math.Round(LibRender.Renderer.FrameRate);
                t = fps.ToString(Culture) + " fps";
                if (OptionFrameRates)
                {
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                } break;

            case "ai":
                t = "A.I.";
                if (TrainManager.PlayerTrain.AI != null)
                {
                    Element.TransitionState -= speed * TimeElapsed;
                    if (Element.TransitionState < 0.0)
                    {
                        Element.TransitionState = 0.0;
                    }
                }
                else
                {
                    Element.TransitionState += speed * TimeElapsed;
                    if (Element.TransitionState > 1.0)
                    {
                        Element.TransitionState = 1.0;
                    }
                } break;

            case "score":
                if (Interface.CurrentOptions.GameMode == Interface.GameMode.Arcade)
                {
                    t = Game.CurrentScore.CurrentValue.ToString(Culture) + " / " + Game.CurrentScore.Maximum.ToString(Culture);
                    if (Game.CurrentScore.CurrentValue < 0)
                    {
                        sc = MessageColor.Red;
                    }
                    else if (Game.CurrentScore.CurrentValue > 0)
                    {
                        sc = MessageColor.Green;
                    }
                    else
                    {
                        sc = MessageColor.Gray;
                    }
                    Element.TransitionState = 0.0;
                }
                else
                {
                    Element.TransitionState = 1.0;
                    t = "";
                } break;

            default:
                t = Element.Text;
                break;
            }
            // transitions
            float alpha = 1.0f;

            if ((Element.Transition & HUD.Transition.Move) != 0)
            {
                double s = Element.TransitionState;
                x += Element.TransitionVector.X * s * s;
                y += Element.TransitionVector.Y * s * s;
            }
            if ((Element.Transition & HUD.Transition.Fade) != 0)
            {
                alpha = (float)(1.0 - Element.TransitionState);
            }
            else if (Element.Transition == HUD.Transition.None)
            {
                alpha = (float)(1.0 - Element.TransitionState);
            }
            // render
            if (alpha != 0.0f)
            {
                // background
                if (Element.Subject == "reverser")
                {
                    w = Math.Max(w, TrainManager.PlayerTrain.MaxReverserWidth);
                    //X-Pos doesn't need to be changed
                }
                if (Element.Subject == "power")
                {
                    w = Math.Max(w, TrainManager.PlayerTrain.MaxPowerNotchWidth);
                    if (TrainManager.PlayerTrain.MaxReverserWidth > 48)
                    {
                        x += (TrainManager.PlayerTrain.MaxReverserWidth - 48);
                    }
                }
                if (Element.Subject == "brake")
                {
                    w = Math.Max(w, TrainManager.PlayerTrain.MaxBrakeNotchWidth);
                    if (TrainManager.PlayerTrain.MaxReverserWidth > 48)
                    {
                        x += (TrainManager.PlayerTrain.MaxReverserWidth - 48);
                    }
                    if (TrainManager.PlayerTrain.MaxPowerNotchWidth > 48)
                    {
                        x += (TrainManager.PlayerTrain.MaxPowerNotchWidth - 48);
                    }
                }
                if (Element.Subject == "single")
                {
                    w = Math.Max(Math.Max(w, TrainManager.PlayerTrain.MaxPowerNotchWidth), TrainManager.PlayerTrain.MaxBrakeNotchWidth);
                    if (TrainManager.PlayerTrain.MaxReverserWidth > 48)
                    {
                        x += (TrainManager.PlayerTrain.MaxReverserWidth - 48);
                    }
                }
                if (Element.CenterMiddle.BackgroundTexture != null)
                {
                    if (Program.CurrentHost.LoadTexture(Element.CenterMiddle.BackgroundTexture, OpenGlTextureWrapMode.ClampClamp))
                    {
                        Color128 c = Element.BackgroundColor.CreateBackColor(sc, alpha);
                        GL.Color4(c.R, c.G, c.B, c.A);
                        LibRender.Renderer.RenderOverlayTexture(Element.CenterMiddle.BackgroundTexture, x, y, x + w, y + h);
                    }
                }
                {                 // text
                    System.Drawing.Size size = Element.Font.MeasureString(t);
                    float  u = size.Width;
                    float  v = size.Height;
                    double p = Math.Round(Element.TextAlignment.X < 0 ? x : Element.TextAlignment.X == 0 ? x + 0.5 * (w - u) : x + w - u);
                    double q = Math.Round(Element.TextAlignment.Y < 0 ? y : Element.TextAlignment.Y == 0 ? y + 0.5 * (h - v) : y + h - v);
                    p += Element.TextPosition.X;
                    q += Element.TextPosition.Y;
                    Color128 c = Element.TextColor.CreateTextColor(sc, alpha);
                    LibRender.Renderer.DrawString(Element.Font, t, new System.Drawing.Point((int)p, (int)q), TextAlignment.TopLeft, c, Element.TextShadow);
                }
                // overlay
                if (Element.CenterMiddle.OverlayTexture != null)
                {
                    if (Program.CurrentHost.LoadTexture(Element.CenterMiddle.OverlayTexture, OpenGlTextureWrapMode.ClampClamp))
                    {
                        Color128 c = Element.OverlayColor.CreateBackColor(sc, alpha);
                        GL.Color4(c.R, c.G, c.B, c.A);
                        LibRender.Renderer.RenderOverlayTexture(Element.CenterMiddle.OverlayTexture, x, y, x + w, y + h);
                    }
                }
            }
        }
コード例 #57
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return(value is global::Android.Views.ViewStates && (global::Android.Views.ViewStates)value == global::Android.Views.ViewStates.Gone);
 }
コード例 #58
0
 void CodeFluent.Runtime.ICodeFluentMemberValidator.Validate(System.Globalization.CultureInfo culture, string memberName, System.Collections.Generic.IList <CodeFluent.Runtime.CodeFluentValidationException> results)
 {
     this.ValidateMember(culture, memberName, results);
 }
コード例 #59
0
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     return((value is bool && (bool)value) ? global::Android.Views.ViewStates.Gone : global::Android.Views.ViewStates.Visible);
 }
コード例 #60
0
 public virtual string Validate(System.Globalization.CultureInfo culture)
 {
     return(CodeFluentPersistence.Validate(culture, this, null));
 }