public static string GetFriendlyName(this PrintItemWrapper printItemWrapper) { if (printItemWrapper?.Name == null) { return(""); } return(textInfo?.ToTitleCase(printItemWrapper.Name.Replace('_', ' '))); }
/// <summary> /// Converts each word's first letter in the string to Uppercase using the specified culture /// </summary> /// <param name="s"></param> /// <param name="cultureInfo">The culture info to use</param> /// <returns></returns> public static string ToTitleCase(this string s, CultureInfo cultureInfo) { TextInfo textInfo = cultureInfo.TextInfo; return(textInfo.ToTitleCase(s)); }
private void button1_Click(object sender, EventArgs e) { if (contador == 0)//Agarra la money que tenemos en op { HttpClient web3 = new HttpClient(); var info2 = web3.GetStringAsync("https://opskins.com/api/user_api.php?request=GetOP&key=b1f9845c63204b889c198d5de6bc67"); var procesado3 = JObject.Parse(info2.Result); label8.Text = "$ " + Convert.ToString(Convert.ToDecimal((string)procesado3["result"]["op"]) / 100); contador = 1; } decimal average; Dictionary <string, decimal> dicsteam = new Dictionary <string, decimal>(); //Crea el diccinoario de steam string text = System.IO.File.ReadAllText(@"steam.json"); //Importar precio steam var steam = JsonConvert.DeserializeObject <JObject>(text); foreach (var item in steam) { dicsteam.Add(item.Key, Convert.ToDecimal(item.Value.ToString())); } HttpClient web2 = new HttpClient(); dataGridView1.Rows.Clear(); button1.Enabled = false; Dictionary <string, decimal> armas = new Dictionary <string, decimal>(); //Crea el diccinoario armas.Clear(); //Limpia el diccionario int count = 1; //Inicializo el contador para ver si cargo algo el diccionario o si no encontro armas TextInfo ti = CultureInfo.CurrentCulture.TextInfo; Primero procesado = new Primero(); HttpClient web = new HttpClient(); var info = web.GetStringAsync("https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=730&format=json_pretty"); procesado = JsonConvert.DeserializeObject <Primero>(info.Result); var hola = JObject.Parse(info.Result); var HOLA = (JObject)hola["response"]; foreach (var item in HOLA) { string arma = ti.ToTitleCase(textBox1.Text); if (textBox1.Text.Equals("cuchi", StringComparison.OrdinalIgnoreCase))//Busca cuchillo { arma = "\u2605 "; } else { if (arma.StartsWith("\u2605"))//Le saca el \u2605 { arma = arma.Substring(2, arma.Length - 2); } if (checkBox1.Checked == true) { arma = "StatTrak\u2122 " + arma;//Si tiene StatTrak } } if (item.Key.StartsWith(arma, StringComparison.OrdinalIgnoreCase) || item.Key.Contains(arma))//Busca sin importar el Case { armas.Add(item.Key, Convert.ToDecimal(item.Value["price"].ToString())); count = count + 1; } }//Imprime el diccionario int txtb2 = Convert.ToInt32(textBox2.Text); // CheckBox2 valor minimo int txtb3 = Convert.ToInt32(textBox3.Text); // CheckBox3 valor maximo foreach (KeyValuePair <string, decimal> item in armas) { decimal precio = item.Value / 100; if (txtb2 < precio && txtb3 > precio) { foreach (KeyValuePair <string, decimal> item2 in dicsteam) { string string1 = item.Key; string string2 = item2.Key; if (item2.Key.StartsWith("?")) { //Le saca el \u2605 string2 = item2.Key.Substring(1, item2.Key.Length - 1); } if (item.Key.StartsWith("\u2605")) { //Le saca el \u2605 string1 = item.Key.Substring(1, item.Key.Length - 1); } if (string1.StartsWith(string2, StringComparison.OrdinalIgnoreCase)) { decimal venta; average = item2.Value; decimal dolar = Convert.ToDecimal(comboBox1.Text); int argentino = Convert.ToInt32(precio * dolar); int argentinoaverage = Convert.ToInt32(average * 15); decimal profit = (Convert.ToDecimal(textBox4.Text) / 100) + 1; if (radioButton3.Checked == true)// Check Radius { venta = Convert.ToInt32(textBox4.Text); } else { venta = Convert.ToInt32(profit * argentino); } int profit2 = Convert.ToInt32(venta - argentino); string a = item.Key + precio; if (radioButton1.Checked == true)// Check Radius real { profit2 = Convert.ToInt32(textBox4.Text); venta = argentino + profit2; } if (radioButton3.Checked == true)// Check Radius forzar venta { venta = Convert.ToInt32(textBox4.Text); profit2 = Convert.ToInt32(venta - argentino); if (profit2 < 0)// Para que no tire valores negativos { profit2 = 0; } } if (radioButton4.Checked == true)// Check Radius predecir { if (precio <= 1 && precio > 0) { profit2 = 20; } if (precio <= 5 && precio > 1) { profit2 = 40; } if (precio <= 10 && precio > 5) { profit2 = 70; } if (precio <= 15 && precio > 10) { profit2 = 75; } if (precio <= 20 && precio > 15) { profit2 = 90; } if (precio <= 25 && precio > 20) { profit2 = 160; } if (precio <= 30 && precio > 25) { profit2 = 200; } if (precio <= 35 && precio > 30) { profit2 = 225; } if (precio <= 45 && precio > 35) { profit2 = 250; } if (precio <= 55 && precio > 45) { profit2 = 310; } if (precio <= 65 && precio > 55) { profit2 = 350; } if (precio <= 75 && precio > 65) { profit2 = 370; } if (precio <= 85 && precio > 75) { profit2 = 410; } if (precio <= 95 && precio > 85) { profit2 = 450; } if (precio <= 105 && precio > 95) { profit2 = 465; } if (precio <= 105 && precio > 95) { profit2 = 500; } if (precio <= 125 && precio > 105) { profit2 = 550; } if (precio <= 155 && precio > 125) { profit2 = 630; } if (precio <= 175 && precio > 155) { profit2 = 700; } if (precio <= 200 && precio > 175) { profit2 = 770; } if (precio <= 250 && precio > 200) { profit2 = 850; } if (precio <= 300 && precio > 250) { profit2 = 1100; } if (precio <= 350 && precio > 300) { profit2 = 1400; } if (precio <= 400 && precio > 350) { profit2 = 1600; } if (precio <= 450 && precio > 400) { profit2 = 1800; } if (precio <= 500 && precio > 450) { profit2 = 1900; } if (precio <= 550 && precio > 500) { profit2 = 2000; } if (precio <= 600 && precio > 550) { profit2 = 2100; } if (precio <= 700 && precio > 600) { profit2 = 2200; } if (precio <= 800 && precio > 700) { profit2 = 2300; } if (precio > 800) { profit2 = 2500; } venta = argentino + profit2; } int porcent = Convert.ToInt32(100 - (precio * 100 / average)); if (porcent < 1)// Posible error en los precios de steam que da valores negativos { porcent = 0; average = precio; } dataGridView1.Rows.Add(item.Key, precio, average, porcent, argentino, argentinoaverage, venta, profit2, "https://opskins.com/?loc=shop_search&app=730_2&sort=lh&search_item=" + item.Key); } else { average = 0; } } } } if (count == 1)//Si no se encuentra el arma { MessageBox.Show("No se encontro arma"); } button1.Enabled = true; }
public static async Task <Auxiliar> InsertAuxiliarAsync(ResultInstruction instruction, Conexion conexion, Comuna comuna) { string acteco = null; TextInfo ti = CultureInfo.CurrentCulture.TextInfo; string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); string adressTemp = ti.ToTitleCase(instruction.ParticipantDebtor.CommercialAddress.ToLower()); if (instruction.ParticipantDebtor.CommercialAddress.Contains(',')) { int index = instruction.ParticipantDebtor.CommercialAddress.IndexOf(','); adressTemp = instruction.ParticipantDebtor.CommercialAddress.Substring(0, index); } if (adressTemp.Length > 60) { adressTemp = adressTemp.Substring(0, 60); } // Get acteco from CEN if (instruction.ParticipantDebtor.CommercialBusiness != null) { if (instruction.ParticipantDebtor.CommercialBusiness.Length > 60) { acteco = instruction.ParticipantDebtor.CommercialBusiness.Substring(0, 60); } else { acteco = instruction.ParticipantDebtor.CommercialBusiness; } // Insert new Acteco await Acteco.InsertActecoAsync(acteco, conexion); // Production: if (Environment.MachineName == "DEVELOPER") { time = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture); } } try { string rut = string.Format(CultureInfo.CurrentCulture, "{0:N0}", instruction.ParticipantDebtor.Rut).Replace(',', '.'); StringBuilder query = new StringBuilder(); query.Append($"IF (NOT EXISTS(SELECT * FROM softland.cwtauxi WHERE CodAux = '{instruction.ParticipantDebtor.Rut}')) BEGIN "); query.Append("INSERT INTO softland.CWTAUXI (CodAux, NomAux, NoFAux, RutAux, ActAux, GirAux, PaiAux, Comaux, "); query.Append("DirAux, ClaCli, ClaPro, Bloqueado, BloqueadoPro, EsReceptorDTE ,eMailDTE, Usuario, Proceso, Sistema, Region, FechaUlMod) "); query.Append($"VALUES ('{instruction.ParticipantDebtor.Rut}', "); query.Append($"'{instruction.ParticipantDebtor.BusinessName}','{instruction.ParticipantDebtor.Name}', "); query.Append($"'{rut}-{instruction.ParticipantDebtor.VerificationCode}','S',(SELECT TOP 1 GirCod from softland.cwtgiro where GirDes = '{acteco}' ),'CL','{comuna.ComCod}', "); query.Append($"'{adressTemp}','S', 'S','N', 'N', 'S','{instruction.ParticipantDebtor.DteReceptionEmail}' "); query.Append($",'Softland','Centralizador', 'IW',{comuna.Id_Region}, '{time}') END"); conexion.Query = query.ToString(); var res = await Conexion.ExecuteNonQueryAsync(conexion); if ((int)res == 2) { return(new Auxiliar() { DirAux = adressTemp, ComAux = comuna.ComDes }); } } catch (Exception) { throw; } return(null); }
void app_language() { if (Session["New"] != null) { DataTable ste_set = new DataTable(); ste_set = DBCon.Ora_Execute_table("select * from site_settings where ID IN ('1')"); DataTable gt_lng = new DataTable(); gt_lng = DBCon.Ora_Execute_table("select " + Session["site_languaage"].ToString() + " from Ref_language where ID IN ('1460','448','505','484','16','1405','1288','190','1397','1566','513','1464','274','77','1979','1439','1441','1376','1980','1981','1982','1983','61','1985')"); CultureInfo culinfo = Thread.CurrentThread.CurrentCulture; TextInfo txtinfo = culinfo.TextInfo; ps_lbl1.Text = txtinfo.ToTitleCase(gt_lng.Rows[14][0].ToString().ToLower()); ps_lbl2.Text = txtinfo.ToTitleCase(gt_lng.Rows[7][0].ToString().ToLower()); ps_lbl3.Text = txtinfo.ToTitleCase(gt_lng.Rows[14][0].ToString().ToLower()); ps_lbl4.Text = txtinfo.ToTitleCase(gt_lng.Rows[6][0].ToString().ToLower()); ps_lbl5.Text = txtinfo.ToTitleCase(gt_lng.Rows[8][0].ToString().ToLower()); ps_lbl6.Text = txtinfo.ToTitleCase(gt_lng.Rows[1][0].ToString().ToLower()); ps_lbl7.Text = txtinfo.ToTitleCase(gt_lng.Rows[11][0].ToString().ToLower()); ps_lbl8.Text = txtinfo.ToTitleCase(gt_lng.Rows[9][0].ToString().ToLower()); ps_lbl9.Text = txtinfo.ToTitleCase(gt_lng.Rows[3][0].ToString().ToLower()); ps_lbl10.Text = txtinfo.ToTitleCase(gt_lng.Rows[10][0].ToString().ToLower()); ps_lbl11.Text = txtinfo.ToTitleCase(gt_lng.Rows[22][0].ToString().ToLower()); ps_lbl12.Text = txtinfo.ToTitleCase(gt_lng.Rows[5][0].ToString().ToLower()); } else { Response.Redirect("../KSAIMB_Login.aspx"); } }
/// <summary> /// Returns a collection of <see cref="UserAchievement"/>s from the given xml. /// </summary> /// <param name="xml">The XML.</param> /// <param name="closedOnly">If true, get only closed achievements, else get all achievements.</param> /// <returns></returns> private ICollection <UserAchievement> Parse(string xml, bool closedOnly) { XDocument document = XDocument.Parse(xml); // xpath: player/customURL XElement playerElement = document.Descendants("player").FirstOrDefault(); if (playerElement == null) { // game is missing xml achievements return(new List <UserAchievement>()); } XElement customUrlElement = playerElement.Element("customURL"); var achievements = from element in document.Descendants("achievement") let apiname = element.Element("apiname") let iconClosed = element.Element("iconClosed") let description = element.Element("description") let name = element.Element("name") let closed = element.Attribute("closed") let date = element.Element("unlockTimestamp") where apiname != null && iconClosed != null && description != null && name != null && closed != null select new { apiname = apiname.Value, closed = closed.Value == "1", // name is in all caps - fix it name = _textInfo.ToTitleCase(name.Value.ToLower()), description = description.Value, image = iconClosed.Value, date = date == null ? null : date.Value }; if (closedOnly) { achievements = from achievement in achievements where achievement.closed select achievement; } return((from achievement in achievements select new UserAchievement { SteamUserId = customUrlElement.Value, Closed = achievement.closed, Date = achievement.date == null ? DateTime.MinValue : GetDate(Convert.ToInt32(achievement.date)), Achievement = new Achievement { ApiName = achievement.apiname, Name = achievement.name, Description = achievement.description, ImageUrl = new Uri(achievement.image, UriKind.Absolute).ToString() } }).ToList()); }
public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false) { // Stop service (otherwise database is locked) ServiceController sc = new("OVRService"); //bool restartSvc = false; try { if (sc.Status.Equals(ServiceControllerStatus.Running) || sc.Status.Equals(ServiceControllerStatus.StartPending)) { //restartSvc = true; sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); } } catch (Exception e) { CLogger.LogError(e); } List <string> libPaths = new(); Dictionary <ulong, string> exePaths = new(); string db = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), OCULUS_DB); using (RegistryKey key = Registry.CurrentUser.OpenSubKey(OCULUS_LIBS, RegistryKeyPermissionCheck.ReadSubTree)) { if (key != null) { foreach (string lib in key.GetSubKeyNames()) { using RegistryKey key2 = Registry.CurrentUser.OpenSubKey(Path.Combine(OCULUS_LIBS, lib), RegistryKeyPermissionCheck.ReadSubTree); libPaths.Add(GetRegStrVal(key2, OCULUS_LIBPATH)); } } } foreach (string lib in libPaths) { List <string> libFiles = new(); try { string manifestPath = Path.Combine(lib, "Manifests"); libFiles = Directory.GetFiles(manifestPath, "*.json.mini", SearchOption.TopDirectoryOnly).ToList(); CLogger.LogInfo("{0} {1} games found in library {2}", libFiles.Count, _name.ToUpper(), lib); } catch (Exception e) { CLogger.LogError(e, string.Format("{0} directory read error: {1}", _name.ToUpper(), lib)); continue; } foreach (string file in libFiles) { try { var options = new JsonDocumentOptions { AllowTrailingCommas = true }; string strDocumentData = File.ReadAllText(file); if (string.IsNullOrEmpty(strDocumentData)) { CLogger.LogWarn(string.Format("Malformed {0} file: {1}", _name.ToUpper(), file)); } else { using JsonDocument document = JsonDocument.Parse(@strDocumentData, options); string name = GetStringProperty(document.RootElement, "canonicalName"); if (ulong.TryParse(GetStringProperty(document.RootElement, "appId"), out ulong id)) { exePaths.Add(id, Path.Combine(lib, "Software", name, GetStringProperty(document.RootElement, "launchFile"))); } } } catch (Exception e) { CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file)); } } } try { CultureInfo ci = new("en-GB"); TextInfo ti = ci.TextInfo; string userName = CConfig.GetConfigString(CConfig.CFG_OCULUSID); //ulong userId = 0; using var con = new SQLiteConnection($"Data Source={db}"); con.Open(); // Get the user ID to check entitlements for expired trials /* * using (var cmdU = new SQLiteCommand("SELECT hashkey, value FROM Objects WHERE typename = 'User'", con)) * { * using SQLiteDataReader rdrU = cmdU.ExecuteReader(); * while (rdrU.Read()) * { * byte[] valU = new byte[rdrU.GetBytes(1, 0, null, 0, int.MaxValue) - 1]; * rdrU.GetBytes(1, 0, valU, 0, valU.Length); * string strValU = System.Text.Encoding.Default.GetString(valU); * * string alias = ParseBlob(strValU, "alias", "app_entitlements"); * if (string.IsNullOrEmpty(userName)) * { * if (ulong.TryParse(rdrU.GetString(0), out userId)) * { * userName = alias; * break; * } * } * else if (userName.Equals(alias, CDock.IGNORE_CASE)) * { * ulong.TryParse(rdrU.GetString(0), out userId); * break; * } * } * } */ using var cmd = new SQLiteCommand("SELECT hashkey, value FROM Objects WHERE typename = 'Application'", con); using SQLiteDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { string strID = ""; string strTitle = ""; string strLaunch = ""; string strAlias = ""; string strPlatform = GetPlatformString(ENUM); string url = ""; /* * string exePath = "", exePath2d = "", exeParams = "", exeParams2d = ""; * string state = "", time = ""; * bool isInstalled = false; */ bool isInstalled = true; if (ulong.TryParse(rdr.GetString(0), out ulong id)) { strID = "oculus_" + id; } //else // strID = "oculus_" + name; if (id == OCULUS_ENV_RIFT) { continue; } byte[] val = new byte[rdr.GetBytes(1, 0, null, 0, int.MaxValue) - 1]; rdr.GetBytes(1, 0, val, 0, val.Length); string strVal = System.Text.Encoding.Default.GetString(val); _ = ulong.TryParse(ParseBlob(strVal, "ApplicationAssetBundle", "can_access_feature_keys", -1, 0), out ulong assets); //ulong.TryParse(ParseBlob(strVal, "PCBinary", "livestreaming_status", -1, 0), out ulong bin); string name = ParseBlob(strVal, "canonical_name", "category"); strTitle = ParseBlob(strVal, "display_name", "display_short_description"); if (!string.IsNullOrEmpty(name) && string.IsNullOrEmpty(strTitle)) { strTitle = ti.ToTitleCase(name.Replace('-', ' ')); } using (var cmd2 = new SQLiteCommand($"SELECT value FROM Objects WHERE hashkey = '{assets}'", con)) { using SQLiteDataReader rdr2 = cmd2.ExecuteReader(); while (rdr2.Read()) { byte[] val2 = new byte[rdr2.GetBytes(0, 0, null, 0, int.MaxValue) - 1]; rdr2.GetBytes(0, 0, val2, 0, val2.Length); string strVal2 = System.Text.Encoding.Default.GetString(val2); url = ParseBlob(strVal2, "uri", "version_code", strStart1: "size"); } } // The exe's can be gotten from the .json files, which we have to get anyway to figure out the install path /* * using (var cmd3 = new SQLiteCommand($"SELECT value FROM Objects WHERE hashkey = '{bin}'", con)) * { * using SQLiteDataReader rdr3 = cmd3.ExecuteReader(); * while (rdr3.Read()) * { * byte[] val3 = new byte[rdr3.GetBytes(0, 0, null, 0, int.MaxValue) - 1]; * rdr3.GetBytes(0, 0, val3, 0, val3.Length); * string strVal3 = System.Text.Encoding.Default.GetString(val3); * exePath = ParseBlob(strVal3, "launch_file", "launch_file_2d"); * exePath2d = ParseBlob(strVal3, "launch_file_2d", "launch_parameters"); * exeParams = ParseBlob(strVal3, "launch_parameters", "launch_parameters_2d"); * exeParams2d = ParseBlob(strVal3, "launch_parameters_2d", "manifest_signature"); * } * } * * if (userId > 0) * { * // TODO: If this is an expired trial, count it as not-installed * using var cmd5 = new SQLiteCommand($"SELECT value FROM Objects WHERE hashkey = '{userId}:{id}'", con); * using SQLiteDataReader rdr5 = cmd5.ExecuteReader(); * while (rdr5.Read()) * { * byte[] val5 = new byte[rdr5.GetBytes(0, 0, null, 0, int.MaxValue) - 1]; * rdr5.GetBytes(0, 0, val5, 0, val5.Length); * string strVal5 = System.Text.Encoding.Default.GetString(val5); * state = ParseBlob(strVal5, "active_state", "expiration_time"); * if (state.Equals("PERMANENT")) * isInstalled = true; * else * { * time = ParseBlob(strVal5, "expiration_time", "grant_reason"); * CLogger.LogDebug($"expiry: {state} {time}"); * //if (!...expired) * isInstalled = true; * } * } * } * else * isInstalled = true; */ if (exePaths.ContainsKey(id)) { CLogger.LogDebug($"- {strTitle}"); strLaunch = exePaths[id]; strAlias = GetAlias(Path.GetFileNameWithoutExtension(exePaths[id])); if (strAlias.Length > strTitle.Length) { strAlias = GetAlias(strTitle); } if (strAlias.Equals(strTitle, CDock.IGNORE_CASE)) { strAlias = ""; } gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, isInstalled, strPlatform)); } else { CLogger.LogDebug($"- *{strTitle}"); gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform)); if (expensiveIcons && !string.IsNullOrEmpty(url)) { // Download missing icons string imgfile = Path.Combine(CDock.currentPath, CDock.IMAGE_FOLDER_NAME, string.Concat(strTitle.Split(Path.GetInvalidFileNameChars()))); bool iconFound = false; foreach (string ext in CDock.supportedImages) { if (File.Exists(imgfile + "." + ext)) { iconFound = true; break; } } if (iconFound) { continue; } string zipfile = $"tmp_{_name}_{id}.zip"; try { #if DEBUG // Don't re-download if file exists if (!File.Exists(zipfile)) { #endif using var client = new WebClient(); client.DownloadFile(url, zipfile); #if DEBUG } #endif using ZipArchive archive = ZipFile.OpenRead(zipfile); foreach (ZipArchiveEntry entry in archive.Entries) { foreach (string ext in CDock.supportedImages) { if (entry.Name.Equals("cover_square_image." + ext, CDock.IGNORE_CASE)) { entry.ExtractToFile(imgfile + "." + ext); break; } } } //#if !DEBUG File.Delete(zipfile); //#endif } catch (Exception e) { CLogger.LogError(e, string.Format("Malformed {0} zip file!", _name.ToUpper())); } } } } con.Close(); } catch (Exception e) { CLogger.LogError(e, string.Format("Malformed {0} database output!", _name.ToUpper())); } //if (restartSvc) // sc.Start(); CLogger.LogDebug("--------------------"); }
private void doOlxInserir(ImovelDTO imovel, bool Automatico = true) { Thread thread = new Thread(() => { if (Automatico) { this.BeginInvoke((MethodInvoker) delegate { string idTipo = "1000"; StringBuilder js = new StringBuilder(); js.AppendLine("if (document.getElementById('" + idTipo + "')) {"); js.AppendLine(" var cn = document.getElementById('" + idTipo + "').className;"); js.AppendLine(" if (!(cn == 'item item-has-children selected' || cn == 'item item-has-children active'))"); js.AppendLine(" document.getElementById('" + idTipo + "').click();"); js.AppendLine("}"); oBrowser.StringByEvaluatingJavaScriptFromString(js.ToString()); }); Thread.Sleep(3000); //js.Clear(); this.BeginInvoke((MethodInvoker) delegate { string idTipo = null; StringBuilder js = new StringBuilder(); if (string.Compare(_Imovel.Tipo, "Apartamento", true) == 0) { idTipo = "1020"; } else if (string.Compare(_Imovel.Tipo, "Casa", true) == 0) { idTipo = "1040"; } if (idTipo != null) { js.AppendLine("if (document.getElementById('" + idTipo + "')) {"); js.AppendLine(" var cn = document.getElementById('" + idTipo + "').className;"); js.AppendLine(" if (!(cn == 'item item-has-children selected' || cn == 'item item-has-children active'))"); js.AppendLine(" document.getElementById('" + idTipo + "').click();"); js.AppendLine("}"); oBrowser.StringByEvaluatingJavaScriptFromString(js.ToString()); } }); Thread.Sleep(7000); this.BeginInvoke((MethodInvoker) delegate { string idTipo = "1"; StringBuilder js = new StringBuilder(); js.AppendLine("if (document.getElementById('" + idTipo + "')) {"); js.AppendLine(" var cn = document.getElementById('" + idTipo + "').className;"); js.AppendLine(" if (!(cn == 'item item-has-children selected' || cn == 'item item-has-children active'))"); js.AppendLine(" document.getElementById('" + idTipo + "').click();"); js.AppendLine("}"); oBrowser.StringByEvaluatingJavaScriptFromString(js.ToString()); }); Thread.Sleep(3000); } this.BeginInvoke((MethodInvoker) delegate { StringBuilder js = new StringBuilder(); if (imovel.Quartos > 0) { js.AppendLine("if (document.getElementById('rooms'))"); switch (imovel.Quartos) { case 1: js.AppendLine("document.getElementById('rooms').selectedIndex = 1;"); break; case 2: js.AppendLine("document.getElementById('rooms').selectedIndex = 2;"); break; case 3: js.AppendLine("document.getElementById('rooms').selectedIndex = 3;"); break; case 4: js.AppendLine("document.getElementById('rooms').selectedIndex = 4;"); break; default: js.AppendLine("document.getElementById('rooms').selectedIndex = 5;"); break; } } //if (!string.IsNullOrEmpty(GaragensText.Text)) // js.AppendLine("document.getElementById('garage_spaces').value = '" + GaragensText.Text + "';"); //if (!string.IsNullOrEmpty(PrecoText.Text)) // js.AppendLine("document.getElementById('price').value = '" + PrecoText.Text + "';"); if (!string.IsNullOrEmpty(imovel.Titulo)) { string titulo = imovel.Titulo; if (IsAllUpper(titulo)) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; titulo = textInfo.ToTitleCase(titulo.ToLower()); } if (!string.IsNullOrEmpty(imovel.Codigo)) { titulo = titulo + " - " + imovel.Codigo; } js.AppendLine("if (document.getElementById('subject'))"); js.AppendLine("document.getElementById('subject').value = " + JsonConvert.SerializeObject(titulo) + ";"); } if (imovel.AreaUtil > 0) { js.AppendLine("if (document.getElementById('size'))"); js.AppendLine("document.getElementById('size').value = '" + imovel.AreaUtil.ToString() + "';"); } if (imovel.Preco > 0) { js.AppendLine("if (document.getElementById('price'))"); js.AppendLine("document.getElementById('price').value = '" + imovel.Preco.ToString() + "';"); } /* * if (!string.IsNullOrEmpty(EnderecoText.Text)) * { * js.AppendLine("if (document.getElementById('address'))"); * js.AppendLine("document.getElementById('address').value = '" + EnderecoText.Text + "';"); * } */ if (imovel.Garagens > 0) { js.AppendLine("if (document.getElementById('garage_spaces'))"); js.AppendLine("document.getElementById('garage_spaces').value = '" + imovel.Garagens.ToString() + "';"); } if (!string.IsNullOrEmpty(CEPText.Text)) { js.AppendLine("if (document.getElementById('zipcode'))"); js.AppendLine("document.getElementById('zipcode').value = '" + formatarCep(CEPText.Text) + "';"); js.AppendLine("document.getElementById('zipcode').focus();"); js.AppendLine("document.getElementById('zipcode').blur();"); } oBrowser.StringByEvaluatingJavaScriptFromString(js.ToString()); }); if (!string.IsNullOrEmpty(DescricaoText.Text)) { this.BeginInvoke((MethodInvoker) delegate { StringBuilder js = new StringBuilder(); js.AppendLine("if (document.getElementById('body'))"); js.Append("document.getElementById('body').value = " + JsonConvert.SerializeObject(DescricaoText.Text) + ";"); oBrowser.StringByEvaluatingJavaScriptFromString(js.ToString()); }); } _TipoPagina = TipoPaginaEnum.Nenhum; }); thread.Start(); }
public DataLoader() { Race human = new Race(); human.DefName = "Human"; human.Label = "Human"; Genders.Add("Female"); Genders.Add("Male"); human.BodyType.Add("Male"); human.BodyType.Add("Female"); human.BodyType.Add("Average"); human.BodyType.Add("Thin"); human.BodyType.Add("Hulk"); human.BodyType.Add("Fat"); human.HairsByGender["Female"] = new List <Hair>(); human.HairsByGender["Male"] = new List <Hair>(); foreach (var firstType in new string[] { "Average", "Narrow" }) { foreach (var secondType in new string[] { "Normal", "Pointy", "Wide" }) { human.HeadType.Add(new CrownType { CrownFirstType = firstType, CrownSubType = secondType }); } } Quality.Add("Awful"); Quality.Add("Poor"); Quality.Add("Normal"); Quality.Add("Good"); Quality.Add("Excellent"); Quality.Add("Masterwork"); Quality.Add("Legendary"); RaceDictionary[human.DefName] = human; ResourceLoader.Load(); var allXmlFiles = Directory.GetFiles("Mods", "*.xml", SearchOption.AllDirectories); var steamModsDir = GetSteamWorkshopLocation(); if (Directory.Exists(steamModsDir)) { allXmlFiles = allXmlFiles.Concat(Directory.GetFiles(steamModsDir, "*.xml", SearchOption.AllDirectories)).ToArray(); } List <Hair> allHairs = new List <Hair>(); foreach (var xmlFile in allXmlFiles) { var modxmlFile = xmlFile; if (modxmlFile.StartsWith(steamModsDir)) { modxmlFile = xmlFile.Replace(steamModsDir, ""); } string[] pathComponents = modxmlFile.Split('\\'); if (!pathComponents[2].Equals("Defs")) { continue; } using (var fileStream = File.OpenRead(xmlFile)) { var docRoot = XDocument.Load(fileStream).Root; CurrentDocumentPath = xmlFile; var workTypeDefsRoot = docRoot.XPathSelectElements("WorkTypeDef/workTags/.."); if (workTypeDefsRoot.Count() != 0) { var workTypeDefs = from workTypeDef in workTypeDefsRoot select new WorkType { DefName = workTypeDef.Element("defName").GetValue(), FullName = workTypeDef.Element("gerundLabel").GetValue(), WorkTags = workTypeDef.Element("workTags") .Elements("li") .Select(element => element.GetValue()).ToArray() }; WorkTypes.AddRange(workTypeDefs); } foreach (var raceVars in docRoot.Descendants("AlienRace.ThingDef_AlienRace")) { Race race = new Race(); race.DefName = raceVars.Element("defName").GetValue(); race.Label = raceVars.Element("label").GetValue(); var alienraceElement = raceVars.Element("alienrace"); if (alienraceElement == null) { alienraceElement = raceVars.Element("alienRace"); } race.HairsByGender["Female"] = new List <Hair>(); race.HairsByGender["Male"] = new List <Hair>(); foreach (var bodyType in alienraceElement.XPathSelectElements("generalSettings/alienPartGenerator/alienbodytypes/li")) { race.BodyType.Add(bodyType.GetValue()); } foreach (var crownType in alienraceElement.XPathSelectElements("generalSettings/alienPartGenerator/aliencrowntypes/li")) { string[] crownStrings = crownType.GetValue().Split('_'); race.HeadType.Add(new CrownType { CrownFirstType = crownStrings[0], CrownSubType = crownStrings[1] }); } if (race.HeadType.Count == 0) { race.HeadType.Add(new CrownType { CrownFirstType = "Average", CrownSubType = "Normal" }); } var useGenderedHeads = alienraceElement.XPathSelectElement("generalSettings/alienPartGenerator/UseGenderedHeads"); if (useGenderedHeads != null) { race.UseGenderedHeads = Convert.ToBoolean(useGenderedHeads.GetValue()); } foreach (var path in alienraceElement.XPathSelectElement("graphicPaths/li").Elements()) { race.GraphicPaths[path.Name.ToString().ToLower()] = path.GetValue(); } RaceDictionary[race.DefName] = race; } foreach (var hairVars in docRoot.Descendants("HairDef")) { Hair hair = new Hair( hairVars.Element("hairGender").GetValue(), hairVars.Element("label").GetValue(), hairVars.Element("defName").GetValue(), hairVars.XPathSelectElements("hairTags/li")); allHairs.Add(hair); } foreach (var traitDef in docRoot.Descendants("TraitDef")) { var traits = (from trait in traitDef.XPathSelectElements("degreeDatas/li") select new TraitDef { Def = traitDef.Element("defName").Value, Label = textInfo.ToTitleCase(trait.Element("label").Value), Degree = trait.Element("degree") != null ? trait.Element("degree").Value : "0", Description = trait.Element("description").Value }); foreach (var trait in traits) { if (!Traits.ContainsKey(trait.Def + trait.Degree)) { Traits.Add(trait.Def + trait.Degree, trait); } } } foreach (var hediffRoot in docRoot.XPathSelectElements("HediffDef/hediffClass/..")) { var parentClass = hediffRoot.Element("hediffClass").Value; var parentName = hediffRoot.Attribute("Name") != null?hediffRoot.Attribute("Name").Value : "None"; Hediff coreHediff; if (!Hediffs.TryGetValue(parentClass, out coreHediff)) { Hediffs.Add(parentClass, coreHediff = new Hediff(parentClass, parentName)); } var hediffs = (from hediff in docRoot.XPathSelectElements("//HediffDef[boolean(@ParentName) and not(@Abstract)]") .Where(x => x.Attribute("ParentName").Value == parentName) select new HediffDef { ParentClass = parentClass, ParentName = hediff.Attribute("ParentName").Value, Def = hediff.Element("defName").Value, Label = textInfo.ToTitleCase(hediff.Element("label").Value), }); foreach (var hediff in hediffs) { coreHediff.SubDiffs[hediff.Def] = hediff; } } foreach (var def in docRoot.Descendants("AlienRace.BackstoryDef")) { if (def.Attribute("Abstract") == null || def.Attribute("Abstract").Value != "True") { Backstory backstory = new Backstory { Id = (string)def.Element("defName"), Title = (string)def.Element("title"), DisplayTitle = "(AlienRace)" + (string)def.Element("title"), TitleShort = (string)def.Element("titleShort"), Description = (string)def.Element("baseDescription"), Slot = (string)def.Element("slot"), SkillGains = new Dictionary <string, int>(), WorkDisables = new List <string>() }; foreach (var skillGain in def.XPathSelectElements("skillGains/li")) { string defName = (string)skillGain.Element("defName"); int amount = Convert.ToInt32(skillGain.Element("amount").GetValue()); backstory.SkillGains.Add(defName, amount); } foreach (var workDisables in def.XPathSelectElements("workDisables/li")) { backstory.WorkDisables.Add(workDisables.GetValue()); } ResourceLoader.Backstories[backstory.Id] = backstory; if (string.IsNullOrEmpty(backstory.Slot)) { ResourceLoader.ChildhoodStories.Add(backstory); ResourceLoader.AdulthoodStories.Add(backstory); } else if (backstory.Slot == "Childhood") { ResourceLoader.ChildhoodStories.Add(backstory); } else { ResourceLoader.AdulthoodStories.Add(backstory); } } } foreach (var relationDef in docRoot.XPathSelectElements("PawnRelationDef")) { var pawnRelation = new PawnRelationDef(relationDef); PawnRelationDefs.Add(pawnRelation.DefName, pawnRelation); } foreach (var thingDef in docRoot.XPathSelectElements("ThingDef")) { ThingDef def = new ThingDef(thingDef); if (ThingDefs.TryGetValue(def.Name, out ThingDef value)) { value.updateDef(thingDef); } else { ThingDefs.Add(def.Name, def); } } foreach (var bodyDefElement in docRoot.XPathSelectElements("BodyDef")) { BodyDef bodyDef = new BodyDef(bodyDefElement); if (bodyDef.DefName != null) { BodyDefsByDef[bodyDef.DefName] = bodyDef; } } fileStream.Close(); } } Dictionary <string, Race> tempRaceDic = RaceDictionary.Values.ToDictionary(x => x.Label.ToLower(), x => x); foreach (Hair hair in allHairs) { List <Race> races = new List <Race>(); foreach (var hairTags in hair.HairTags) { Race race; if (tempRaceDic.TryGetValue(hairTags, out race)) { races.Add(race); } } if (races.Count == 0) { races.Add(RaceDictionary["Human"]); if (RaceDictionary.TryGetValue("Alien_Orassan", out var race)) { races.Add(race); } } foreach (var race in races) { if (hair.Gender.Equals("Any") || hair.Gender.Contains("Usually")) { foreach (var list in race.HairsByGender.Values.ToList()) { list.Add(hair); } } else { List <Hair> hairListForGender; if (race.HairsByGender.TryGetValue(hair.Gender, out hairListForGender)) { hairListForGender.Add(hair); } } } } foreach (ThingDef thingDef in ThingDefs.Values) { if (thingDef.ParentName != null && ThingDefs.TryGetValue(thingDef.ParentName, out ThingDef value)) { thingDef.Parent = value; } if (thingDef.DefName != null && !ThingDefsByDefName.ContainsKey(thingDef.DefName)) { ThingDefsByDefName.Add(thingDef.DefName, thingDef); } foreach (string stuffPropCat in thingDef.StuffPropsCategories) { if (ThingDefsByStuffCategory.TryGetValue(stuffPropCat, out var list)) { list.Add(thingDef); } else { List <ThingDef> thingDefs = new List <ThingDef>(); thingDefs.Add(thingDef); ThingDefsByStuffCategory.Add(stuffPropCat, thingDefs); } } } ResourceLoader.ChildhoodStories = ResourceLoader.ChildhoodStories.OrderBy(x => x.DisplayTitle).ToList(); ResourceLoader.AdulthoodStories = ResourceLoader.AdulthoodStories.OrderBy(x => x.DisplayTitle).ToList(); }
public static string ToTitleCase(this string text) { TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; return(textInfo.ToTitleCase(text)); }
public async Task <dynamic> GetAnswersAsync(string inputQuestion, bool isLuisCallRequired = true) { //@TODO Need to make changes as per AI's are trained.. dynamic answerObject = null; string bestAnswer = "Sorry, not able to get you. Please explain your problem in detail."; string[] input = inputQuestion.Split("|"); if (!isLuisCallRequired) { //dynamic luisResponse = await luisProxy.GetIntents(question); //IntentWithScore luisTopIntents = luisBusinessLogic.ParseLuisIntent(luisResponse); //if (luisTopIntents != null && luisBusinessLogic.IsIntentAccurate(luisTopIntents)) //{ // question = luisTopIntents.TopScoringIntent; //} } string question = input[0]; var requestContent = JsonConvert.SerializeObject(new { question }); using (var request = new HttpRequestMessage()) { // set request data. request.Method = HttpMethod.Post; request.RequestUri = new Uri(string.Format(CultureInfo.InvariantCulture, qnAMakerSettings.Endpoint.OriginalString, qnAMakerSettings.KnowledgeId)); request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json"); request.Headers.Add("Authorization", "EndpointKey " + qnAMakerSettings.AuthorizationKey); var response = await httpClientService.SendAsync(request); if (response.IsSuccessStatusCode) { string qnaResponse = response.Content.ReadAsStringAsync().Result; var qnAMakers = JsonConvert.DeserializeObject <QnAMakerResult>(qnaResponse); if (qnAMakers.Answers.LastOrDefault().Score > 0) { bestAnswer = qnAMakers.Answers.OrderBy(answer => answer.Score).LastOrDefault().Answer; } } //if (bestAnswer.Contains("{") && bestAnswer.Contains("}")) if (bestAnswer.Contains("|")) { string[] keyword = bestAnswer.Split("|"); CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; Location location = new Location { State = input[1] }; var topics = await topicsResourcesBusinessLogic.GetTopicsAsync(textInfo.ToTitleCase(keyword[1]), location); if (topics != null && topics.Count > 0) { string topicId = topics[0].id; answerObject = new JObject { { "description", bestAnswer }, { "topic", "topics/" + topicId } }; } else { bestAnswer = "We couldn't find internal resources, please try our web search"; answerObject = new JObject { { "description", bestAnswer } }; } //answerObject = JsonConvert.DeserializeObject(bestAnswer); } else { answerObject = new JObject { { "description", bestAnswer } }; } return(answerObject.ToString()); } }
private void cargarCabecera() { int col = 1; int row = 0; diasTieneElMes = DateTime.DaysInMonth(AñoSeleccionado, MesSeleccionado); DockPanel dock = new DockPanel(); Button btna = new Button(); Button btnb = new Button(); TextBlock txt = new TextBlock(); btna.Content = "<"; btna.Width = 20; btna.Height = 30; btna.Name = "btnAtras"; btna.Margin = new Thickness(10, 0, 0, 0); btna.Click += mesAtras; btnb.Content = ">"; btnb.Width = 20; btnb.Height = 30; btnb.Name = "btnAdelante"; btnb.Margin = new Thickness(0, 0, 10, 0); btnb.Click += mesAdelante; txt.Name = "txtMes"; txt.Text = inf.ToTitleCase(formatDate.GetMonthName(MesSeleccionado)) + " " + AñoSeleccionado.ToString(); txt.HorizontalAlignment = HorizontalAlignment.Center; txt.VerticalAlignment = VerticalAlignment.Center; dock.LastChildFill = true; dock.Background = Brushes.DodgerBlue; DockPanel.SetDock(btna, Dock.Left); DockPanel.SetDock(btnb, Dock.Right); dock.Children.Add(btna); dock.Children.Add(btnb); dock.Children.Add(txt); Grid.SetColumn(dock, 0); Grid.SetRow(dock, 0); lagrid.Children.Add(dock); for (int i = 1; i <= diasTieneElMes; i++) { StackPanel st = new StackPanel(); TextBlock txtNum = new TextBlock(); TextBlock txtDia = new TextBlock(); txtNum.Text = i.ToString(); txtNum.HorizontalAlignment = HorizontalAlignment.Center; txtNum.VerticalAlignment = VerticalAlignment.Center; txtDia.Text = cargarCabeceraDiasSemana(i); txtDia.HorizontalAlignment = HorizontalAlignment.Center; txtDia.VerticalAlignment = VerticalAlignment.Center; st.Children.Add(txtNum); st.Children.Add(txtDia); st.HorizontalAlignment = HorizontalAlignment.Stretch; st.VerticalAlignment = VerticalAlignment.Stretch; st.Background = Brushes.DodgerBlue; Grid.SetColumn(st, col); Grid.SetRow(st, row); lagrid.Children.Add(st); col++; } }
void app_language() { if (Session["New"] != null) { assgn_roles(); DataTable ste_set = new DataTable(); ste_set = DBCon.Ora_Execute_table("select * from site_settings where ID IN ('1')"); DataTable gt_lng = new DataTable(); gt_lng = DBCon.Ora_Execute_table("select " + Session["site_languaage"].ToString() + " from Ref_language where ID IN ('116','1052','1072','1073','64','65','117','13','14','15','1074')"); CultureInfo culinfo = Thread.CurrentThread.CurrentCulture; TextInfo txtinfo = culinfo.TextInfo; ps_lbl1.Text = txtinfo.ToTitleCase(gt_lng.Rows[2][0].ToString().ToLower()); ps_lbl2.Text = txtinfo.ToTitleCase(gt_lng.Rows[7][0].ToString().ToLower()); ps_lbl3.Text = txtinfo.ToTitleCase(gt_lng.Rows[9][0].ToString().ToLower()); ps_lbl4.Text = txtinfo.ToTitleCase(gt_lng.Rows[8][0].ToString().ToLower()); ps_lbl5.Text = txtinfo.ToTitleCase(gt_lng.Rows[1][0].ToString().ToLower()); ps_lbl6.Text = txtinfo.ToTitleCase(gt_lng.Rows[3][0].ToString().ToLower()); ps_lbl7.Text = txtinfo.ToTitleCase(gt_lng.Rows[4][0].ToString().ToLower()); ps_lbl8.Text = txtinfo.ToTitleCase(gt_lng.Rows[5][0].ToString().ToLower()); Button1.Text = txtinfo.ToTitleCase(gt_lng.Rows[6][0].ToString().ToLower()); Button3.Text = txtinfo.ToTitleCase(gt_lng.Rows[0][0].ToString().ToLower()); ps_lbl11.Text = txtinfo.ToTitleCase(gt_lng.Rows[10][0].ToString().ToLower()); } else { Response.Redirect("../KSAIMB_Login.aspx"); } }
/// <summary> /// Clean up the specified string and return it in title case /// </summary> /// <param name="value"></param> /// <returns></returns> protected string ToTitleCase(string value) { return(_textInfo.ToTitleCase(value.CleanString())); }
private List <ExcelDataItem> ReadExcelData() { List <ExcelDataItem> excelDataItems = new List <ExcelDataItem>(); if (excelFile != "") { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(excelFile, false)) { WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; IEnumerable <Sheet> sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild <SheetData>(); IEnumerable <Row> rows = sheetData.Descendants <Row>(); int rowNumber = 1; int recsAdded = 0; int previousCol = -1; int currentCol = 0; string lastRegName = ""; bool eof = false; foreach (Row excelDataRow in rows) { bool ok = true; ExcelDataItem item = new ExcelDataItem(); if (rowNumber == 1) { //Column Headings } if (rowNumber > 1 && !eof) { item.RowNumber = rowNumber; //Getting Competitor Data (31 cols) foreach (Cell cell in excelDataRow.Descendants <Cell>()) { int tempInt = -1; string tempRegNo = ""; if (eof) { ok = false; break; } currentCol = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference)); switch (currentCol) { case 0: string showName = GetCellValue(spreadsheetDocument, cell).ToString(); item.Show_Name = showName; break; case 1: int.TryParse(GetCellValue(spreadsheetDocument, cell), out tempInt); if (tempInt > 0) { item.Owner_ID = tempInt; } else { item.Owner_ID = 0; //Utils.LogToFile(string.Format("Owner ID was not numeric for record number {0}", rowNumber)); } break; case 2: item.Owner_Title = GetCellValue(spreadsheetDocument, cell); break; case 3: item.Owner_First_Name = CleanFirstName(GetCellValue(spreadsheetDocument, cell).ToLowerInvariant().Trim()); break; case 4: item.Owner_Last_Name = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 5: item.Owner_Address_1 = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 6: item.Owner_Address_2 = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 7: item.Owner_Town = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 8: item.Owner_County = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 9: item.Owner_Postcode = GetCellValue(spreadsheetDocument, cell).ToUpperInvariant(); break; case 10: item.Owner_Country = GetCellValue(spreadsheetDocument, cell); break; case 11: item.Owner_Phone = GetCellValue(spreadsheetDocument, cell); break; case 12: item.Owner_Email = GetCellValue(spreadsheetDocument, cell); break; case 13: item.Owner_Registered_Name = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); break; case 14: item.Vehicle_Registration = GetCellValue(spreadsheetDocument, cell); break; case 15: item.Registered_Name = CleanDogName(GetCellValue(spreadsheetDocument, cell).ToLowerInvariant().Trim()); break; case 16: tempRegNo = GetCellValue(spreadsheetDocument, cell).ToUpperInvariant(); item.Registered_Number = FixKCName(tempRegNo, item.Registered_Name != lastRegName); lastRegName = item.Registered_Name; break; case 17: item.Breed = textInfo.ToTitleCase(GetCellValue(spreadsheetDocument, cell)); if (string.IsNullOrWhiteSpace(item.Breed)) { Utils.LogToFile(string.Format("Dog Breed not specified for record number {0}", rowNumber)); item.Breed = "Not Specified"; } break; case 18: item.Sex = GetCellValue(spreadsheetDocument, cell); break; case 19: int.TryParse(GetCellValue(spreadsheetDocument, cell), out tempInt); if (tempInt > 0) { if (tempInt > 3000) { item.Date_Of_Birth = Utils.FromExcelSerialDate(tempInt); item.Year_Of_Birth = (short)item.Date_Of_Birth.Year; } else { item.Year_Of_Birth = (short)tempInt; } } else if (tempInt == 0) { item.Date_Of_Birth = new DateTime(); } else { Utils.LogToFile(string.Format("Invalid date of birth for record number {0}", rowNumber)); } break; //case 19: // item.Breeder = GetCellValue(spreadsheetDocument, cell); // break; //case 20: // item.Sire = GetCellValue(spreadsheetDocument, cell); // break; //case 21: // item.Dam = GetCellValue(spreadsheetDocument, cell); // break; case 20: int.TryParse(GetCellValue(spreadsheetDocument, cell), out tempInt); if (tempInt > -1) { item.Merit_Points = tempInt; } else { Utils.LogToFile(string.Format("Merit Points was not numeric for record number {0}", rowNumber)); ok = false; } break; case 21: int.TryParse(GetCellValue(spreadsheetDocument, cell), out tempInt); if (tempInt > -1) { item.Entered_Class = tempInt; } else { Utils.LogToFile(string.Format("Entered Class was not numeric for record number {0}", rowNumber)); ok = false; } break; case 22: item.Preferred_Judge = GetCellValue(spreadsheetDocument, cell); break; case 23: item.Extras = GetCellValue(spreadsheetDocument, cell); break; case 24: item.Confirmed_Acceptance_Of_Declaration = GetCellValue(spreadsheetDocument, cell) == "Yes"; break; case 25: item.Withdraw_All_Entries_If_Balloted_Out_Of_Championship_C = GetCellValue(spreadsheetDocument, cell) == "Yes"; break; case 26: item.Show_Address_In_Catalogue = GetCellValue(spreadsheetDocument, cell) == "Yes"; break; case 27: item.Notes_To_Organiser = GetCellValue(spreadsheetDocument, cell); break; case 28: var DoE = GetCellValue(spreadsheetDocument, cell); if (DoE.ToString() == "WyD") { int yr = DateTime.Now.Year; item.Date_Of_Entry = new DateTime(yr, 04, 01); break; } int.TryParse(DoE, out tempInt); if (tempInt > 0) { item.Date_Of_Entry = Utils.FromExcelSerialDate(tempInt); } else { item.Date_Of_Entry = null; Utils.LogToFile(string.Format("Invalid date of entry for record number {0}", rowNumber)); } break; case 29: item.ImportRecord = GetCellValue(spreadsheetDocument, cell) == "Y"; break; case 30: int.TryParse(GetCellValue(spreadsheetDocument, cell), out tempInt); if (tempInt > 0) { item.RunningOrder = (short)tempInt; } break; } previousCol = currentCol; } if (item.Show_Name == null || item.Show_Name.Length == 0) { eof = true; break; } if (ok) { excelDataItems.Add(item); recsAdded++; } } previousCol = -1; rowNumber++; } Utils.LogToFile(string.Format("{0} records retrieved from the spreadsheet", recsAdded)); } } return(excelDataItems); }
public MemoryStream GeneratePdfTemplate(SalesInvoiceViewModel viewModel, int clientTimeZoneOffset) { const int MARGIN = 15; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font Title_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Document document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region customViewModel double result = 0; double totalTax = 0; double totalPay = 0; var currencyLocal = ""; currencyLocal = "Rupiah"; //if (viewModel.Currency.Symbol == "Rp") //{ // currencyLocal = "Rupiah"; //} //else if (viewModel.Currency.Symbol == "$") //{ // currencyLocal = "Dollar"; //} //else //{ // currencyLocal = viewModel.Currency.Symbol; //} #endregion #region Header PdfPTable headerTable = new PdfPTable(2); PdfPTable headerTable1 = new PdfPTable(1); PdfPTable headerTable2 = new PdfPTable(1); PdfPTable headerTable3 = new PdfPTable(2); PdfPTable headerTable4 = new PdfPTable(2); headerTable.SetWidths(new float[] { 10f, 10f }); headerTable.WidthPercentage = 100; headerTable3.SetWidths(new float[] { 20f, 40f }); headerTable3.WidthPercentage = 80; headerTable4.SetWidths(new float[] { 10f, 40f }); headerTable4.WidthPercentage = 100; PdfPCell cellHeader1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader3 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader4 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderCS2 = new PdfPCell() { Border = Rectangle.NO_BORDER, Colspan = 2, HorizontalAlignment = Element.ALIGN_CENTER }; cellHeaderBody.Phrase = new Phrase("PT. DAN LIRIS", Title_bold_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Head Office : Jl. Merapi No. 23 Banaran, Grogol", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Sukoharjo, 57552 Central Java, Indonesia", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Telp :(+62 271) 740888, 714400", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Fax :(+62 271) 740777, 735222", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("PO BOX 116 Solo, 57100", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Web: www.danliris.com", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeader1.AddElement(headerTable1); headerTable.AddCell(cellHeader1); cellHeaderBody2.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody2.Phrase = new Phrase("FM-PJ-00-03-007", bold_font); headerTable2.AddCell(cellHeaderBody2); cellHeaderBody2.Phrase = new Phrase("Sukoharjo, " + viewModel.SalesInvoiceDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); headerTable2.AddCell(cellHeaderBody2); cellHeaderBody2.Phrase = new Phrase("" + viewModel.Buyer.Name, normal_font); headerTable2.AddCell(cellHeaderBody2); cellHeaderBody2.Phrase = new Phrase("" + viewModel.Buyer.Address, normal_font); headerTable2.AddCell(cellHeaderBody2); cellHeader2.AddElement(headerTable2); headerTable.AddCell(cellHeader2); cellHeaderCS2.Phrase = new Phrase("FAKTUR PENJUALAN", header_font); headerTable.AddCell(cellHeaderCS2); cellHeaderCS2.Phrase = new Phrase($"No. {viewModel.SalesInvoiceType}{viewModel.AutoIncreament.ToString().PadLeft(6, '0')}", bold_font); headerTable.AddCell(cellHeaderCS2); cellHeaderCS2.Phrase = new Phrase("", normal_font); headerTable.AddCell(cellHeaderCS2); cellHeaderBody.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody.Phrase = new Phrase("NPWP ", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": 01.139.907.8.532.000", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("NPPKP ", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": 01.139.907.8.532.000", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("No Index Debitur ", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.Buyer.Code, normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable3.AddCell(cellHeaderBody); cellHeader3.AddElement(headerTable3); headerTable.AddCell(cellHeader3); cellHeaderBody.Phrase = new Phrase("NIK", normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.Buyer.NIK, normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("NPWP Buyer", normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.Buyer.NPWP, normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable4.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font); headerTable4.AddCell(cellHeaderBody); cellHeader4.AddElement(headerTable4); headerTable.AddCell(cellHeader4); cellHeaderCS2.Phrase = new Phrase("", normal_font); headerTable.AddCell(cellHeaderCS2); document.Add(headerTable); #endregion Header #region Body PdfPTable bodyTable = new PdfPTable(7); PdfPCell bodyCell = new PdfPCell(); float[] widthsBody = new float[] { 6f, 22f, 6f, 6f, 10f, 8f, 10f }; bodyTable.SetWidths(widthsBody); bodyTable.WidthPercentage = 100; bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase("Kode", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("Nama Barang", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("Banyak", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("Jumlah", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("Satuan", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("Harga", bold_font); bodyTable.AddCell(bodyCell); bodyCell.Phrase = new Phrase("QuantityItem", bold_font); bodyTable.AddCell(bodyCell); double price = 0; double amount = 0; foreach (var detail in viewModel.SalesInvoiceDetails) { foreach (var item in detail.SalesInvoiceItems) { price = item.Price.GetValueOrDefault() * viewModel.Currency.Rate.GetValueOrDefault(); amount = item.Amount.GetValueOrDefault() * viewModel.Currency.Rate.GetValueOrDefault(); bodyCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyCell.Phrase = new Phrase(item.ProductCode, normal_font); bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyCell.Phrase = new Phrase(item.ProductName, normal_font); bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase(item.QuantityPacking + " " + item.PackingUom, normal_font); bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase(item.QuantityItem.GetValueOrDefault().ToString("N2"), normal_font); bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase(item.ItemUom, normal_font); bodyTable.AddCell(bodyCell); //bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; //bodyCell.Phrase = new Phrase(item.Price.GetValueOrDefault().ToString("N2"), normal_font); //bodyTable.AddCell(bodyCell); //bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; //bodyCell.Phrase = new Phrase(item.Amount.GetValueOrDefault().ToString("N2"), normal_font); //bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase(price.ToString("N2"), normal_font); bodyTable.AddCell(bodyCell); bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell.Phrase = new Phrase(amount.ToString("N2"), normal_font); bodyTable.AddCell(bodyCell); } } foreach (var item in viewModel.SalesInvoiceDetails) { foreach (var totalAmount in item.SalesInvoiceItems) { result += totalAmount.Amount.GetValueOrDefault() * viewModel.Currency.Rate.GetValueOrDefault(); } } totalTax = result * 0.1; totalPay = totalTax + result; document.Add(bodyTable); #endregion Body #region Footer var dueDate = viewModel.DueDate.Value.Date; var salesInvoiceDate = viewModel.SalesInvoiceDate.Value.Date; var tempo = (dueDate - salesInvoiceDate).ToString("dd"); CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; string TotalPayWithVat = textInfo.ToTitleCase(NumberToTextIDN.terbilang(totalPay)); string TotalPayWithoutVat = textInfo.ToTitleCase(NumberToTextIDN.terbilang(result)); //string TotalPayWithVat = NumberToTextIDN.terbilang(totalPay); //string TotalPayWithoutVat = NumberToTextIDN.terbilang(result); PdfPTable footerTable = new PdfPTable(2); PdfPTable footerTable1 = new PdfPTable(1); PdfPTable footerTable2 = new PdfPTable(2); PdfPTable footerTable3 = new PdfPTable(2); footerTable.SetWidths(new float[] { 10f, 10f }); footerTable.WidthPercentage = 100; footerTable1.WidthPercentage = 100; footerTable2.SetWidths(new float[] { 10f, 50f }); footerTable2.WidthPercentage = 100; footerTable3.SetWidths(new float[] { 30f, 50f }); footerTable3.WidthPercentage = 100; PdfPCell cellFooterLeft1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellFooterLeft2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellFooterLeft3 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderFooter = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellHeaderFooter.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Tempo", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + tempo + " Hari", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Jth. Tempo", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + viewModel.DueDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("SJ No.", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + viewModel.DeliveryOrderNo, normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable2.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable2.AddCell(cellHeaderFooter); cellFooterLeft2.AddElement(footerTable2); footerTable.AddCell(cellFooterLeft2); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Dasar pengenaan pajak", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + result.ToString("N2"), normal_font); footerTable3.AddCell(cellHeaderFooter); if (viewModel.VatType.Equals("PPN Umum")) { cellHeaderFooter.Phrase = new Phrase("PPN 10%", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalTax.ToString("N2"), normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Jumlah", bold_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalPay.ToString("N2"), bold_font); footerTable3.AddCell(cellHeaderFooter); } else if (viewModel.VatType.Equals("PPN Kawasan Berikat")) { cellHeaderFooter.Phrase = new Phrase("PPN", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": Tarif PPN 0% (Berfasilitas)", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Jumlah", bold_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalPay.ToString("N2"), bold_font); footerTable3.AddCell(cellHeaderFooter); } else if (viewModel.VatType.Equals("PPN BUMN")) { cellHeaderFooter.Phrase = new Phrase("PPN 10%", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalTax.ToString("N2") + " (Dibayar terpisah)", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Jumlah", bold_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + result.ToString("N2"), bold_font); footerTable3.AddCell(cellHeaderFooter); } else if (viewModel.VatType.Equals("PPN Retail")) { cellHeaderFooter.Phrase = new Phrase("PPN 10%", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalTax.ToString("N2"), normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("Jumlah", bold_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + totalPay.ToString("N2"), bold_font); footerTable3.AddCell(cellHeaderFooter); } else { cellHeaderFooter.Phrase = new Phrase("Jumlah", bold_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase(": " + "Rp. " + " " + result.ToString("N2"), bold_font); footerTable3.AddCell(cellHeaderFooter); } cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable3.AddCell(cellHeaderFooter); cellHeaderFooter.Phrase = new Phrase("", normal_font); footerTable3.AddCell(cellHeaderFooter); cellFooterLeft3.AddElement(footerTable3); footerTable.AddCell(cellFooterLeft3); document.Add(footerTable); cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); if (viewModel.VatType.Equals("PPN Umum")) { cellFooterLeft1.Phrase = new Phrase("Terbilang : " + TotalPayWithVat + " " + currencyLocal, normal_font); footerTable1.AddCell(cellFooterLeft1); } else if (viewModel.VatType.Equals("PPN Kawasan Berikat")) { cellFooterLeft1.Phrase = new Phrase("Terbilang : " + TotalPayWithVat + " " + currencyLocal, normal_font); footerTable1.AddCell(cellFooterLeft1); } else if (viewModel.VatType.Equals("PPN BUMN")) { cellFooterLeft1.Phrase = new Phrase("Terbilang : " + TotalPayWithoutVat + " " + currencyLocal, normal_font); footerTable1.AddCell(cellFooterLeft1); } else if (viewModel.VatType.Equals("PPN Retail")) { cellFooterLeft1.Phrase = new Phrase("Terbilang : " + TotalPayWithVat + " " + currencyLocal, normal_font); footerTable1.AddCell(cellFooterLeft1); } //else //{ // cellFooterLeft1.Phrase = new Phrase("Terbilang : " + TotalPayWithoutVat + " " + currencyLocal, normal_font); // footerTable1.AddCell(cellFooterLeft1); //} cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); cellFooterLeft1.Phrase = new Phrase("Catatan : " + viewModel.Remark, bold_font); footerTable1.AddCell(cellFooterLeft1); cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); PdfPTable signatureTable = new PdfPTable(4); PdfPCell signatureCell = new PdfPCell() { HorizontalAlignment = Element.ALIGN_CENTER }; float[] widthsSignature = new float[] { 6f, 6f, 6f, 6f }; signatureTable.SetWidths(widthsSignature); signatureTable.WidthPercentage = 30; signatureCell.Phrase = new Phrase("Tanda terima :", normal_font); signatureTable.AddCell(signatureCell); signatureCell.Phrase = new Phrase("Dibuat oleh :", normal_font); signatureTable.AddCell(signatureCell); signatureCell.Phrase = new Phrase("Diperiksa oleh :", normal_font); signatureTable.AddCell(signatureCell); signatureCell.Phrase = new Phrase("Disetujui oleh :", normal_font); signatureTable.AddCell(signatureCell); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------------", normal_font), FixedHeight = 40, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------------", normal_font), FixedHeight = 40, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------------", normal_font), FixedHeight = 40, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------------", normal_font), FixedHeight = 40, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); footerTable1.AddCell(new PdfPCell(signatureTable)); cellFooterLeft1.Phrase = new Phrase("", normal_font); footerTable1.AddCell(cellFooterLeft1); document.Add(footerTable1); #endregion Footer document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
static void Main(string[] args) { try { // Get some basic details for this run string runBy = WindowsIdentity.GetCurrent().Name; // Get the name of the user executing this program bool isSystem = WindowsIdentity.GetCurrent().IsSystem; DateTime now = DateTime.Now; ReturnCode = 0; // Initialise return code to success // Get access to the ASCOM Profile store and retireve the trace logger configuration RegistryAccess profile = new RegistryAccess(); string traceFileName = ""; string traceBasePath = ""; if (isSystem) // If we are running as user SYSTEM, create our own trace file name so that all scheduled job trace files end up in the same directory { // Get the configured trace file directory and make sure that it exists traceBasePath = profile.GetProfile(GlobalItems.ASTROMETRY_SUBKEY, GlobalItems.DOWNLOAD_TASK_TRACE_PATH_VALUE_NAME, string.Format(GlobalItems.DOWNLOAD_TASK_TRACE_DEFAULT_PATH_FORMAT, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) ).TrimEnd('\\'); Directory.CreateDirectory(traceBasePath); // Now make the full trace file name from the path above and the file name format template traceFileName = string.Format(GlobalItems.DOWNLOAD_TASK_TRACE_FILE_NAME_FORMAT, traceBasePath, now.Year, now.Month, now.Day, now.Hour.ToString("00"), now.Minute.ToString("00"), now.Second.ToString("00")); } // Get the trace state from the Profile string DownloadTaskTraceEnabledString = profile.GetProfile(GlobalItems.ASTROMETRY_SUBKEY, GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_VALUE_NAME, GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_DEFAULT.ToString()); if (!Boolean.TryParse(DownloadTaskTraceEnabledString, out bool DownloadTaskTraceEnabledValue)) //' String parsed OK so nofurther action { //'Returned string doesn't represent a boolean so use the default DownloadTaskTraceEnabledValue = GlobalItems.DOWNLOAD_TASK_TRACE_ENABLED_DEFAULT; } // Create the trace logger with either the supplied fully qualified name if running as SYSTEM or an automatic file name if running as a normal user TL = new TraceLogger(traceFileName, GlobalItems.DOWNLOAD_TASK_TRACE_LOG_FILETYPE); TL.Enabled = DownloadTaskTraceEnabledValue; // Set the trace state TL.IdentifierWidth = GlobalItems.DOWNLOAD_TASK_TRACE_LOGGER_IDENTIFIER_FIELD_WIDTH; invariantCulture = new CultureInfo(""); invariantCulture.Calendar.TwoDigitYearMax = 2117; // Specify that two digit years will be converted to the range 2018-2117 - Likely to outlast ASCOM Platform and me! monthAbbrev = invariantCulture.DateTimeFormat.AbbreviatedMonthNames; // Get the 12 three letter abbrviated month names of the year invariantTextInfo = invariantCulture.TextInfo; TL.LogMessage("EarthRotationUpdate", string.Format("InstalledUICulture: {0}, CurrentUICulture: {1}, CurrentCulture: {2}", CultureInfo.InstalledUICulture.Name, CultureInfo.CurrentUICulture, CultureInfo.CurrentCulture)); parameters = new EarthRotationParameters(TL); // Get configuration from the Profile store string runDate = now.ToString(GlobalItems.DOWNLOAD_TASK_TIME_FORMAT, CultureInfo.CurrentUICulture); // Get today's date and time in a locally readable format hostURIString = parameters.DownloadTaskDataSource; // Initialise the data source URI if (args.Length > 0) { foreach (string arg in args) { TL.LogMessage("EarthRotationUpdate", string.Format("Received parameter: {0}", arg)); } } // If we have been provided with an "Initialise" paramter then stop here after having set up all the default profile values by creating the EarthRotationParameters object if (args.Length == 1) { if (args[0].Trim(' ', '-', '\\', '/').Equals("INITIALISE", StringComparison.OrdinalIgnoreCase)) // Test for the presence of and act on the initialise argument ignoring everything else { TL.LogMessage("EarthRotationUpdate", string.Format("Earth rotation parameter initialisation run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem)); LogEvent(string.Format("Earth rotation parameter initialisation run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem), EventLogEntryType.Information); TL.LogMessage("EarthRotationUpdate", string.Format("Calling ManageScheduledTask")); parameters.ManageScheduledTask(); TL.LogMessage("EarthRotationUpdate", string.Format("Completed ManageScheduledTask")); Environment.Exit(0); } } // If we have been provided with a "DataSource" override paramter then apply the new URI otherwise read it from the Profile if (args.Length == 2) { if (args[0].Trim(' ', '-', '\\', '/').Equals("DATASOURCE", StringComparison.OrdinalIgnoreCase)) // Test for the presence of and act on the data source argument ignoring everything else { TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter provided: {0}", args[1])); string overrideDataSource = args[1].Trim(' ', '"'); bool UriValid = false; // Set the valid flag false, then set to true if the download source starts with a supported URI prefix if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_HTTP, StringComparison.OrdinalIgnoreCase)) { UriValid = true; } if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_HTTPS, StringComparison.OrdinalIgnoreCase)) { UriValid = true; } if (overrideDataSource.StartsWith(GlobalItems.URI_PREFIX_FTP, StringComparison.OrdinalIgnoreCase)) { UriValid = true; } if (UriValid) { hostURIString = overrideDataSource; TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter is valid and will be used: {0}", hostURIString)); } else { TL.LogMessage("EarthRotationUpdate", string.Format("Data source override parameter {0} is not valid and the Profile data source will be used instead: {1}", overrideDataSource, hostURIString)); } } } // Ensure that the host URI string, wherever it has come from, ends with a single backslash otherwise the URI will be incorrect when the file name is formed hostURIString = hostURIString.TrimEnd(' ', '-', '\\', '/') + "/"; LogEvent(string.Format("Run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem), EventLogEntryType.Information); TL.LogMessage("EarthRotationUpdate", string.Format("Run on {0} by {1}, IsSystem: {2}", runDate, runBy, isSystem)); TL.BlankLine(); LogEvent(string.Format("Log file: {0}, Trace state: {1}, Log file path: {2}", TL.LogFileName, parameters.DownloadTaskTraceEnabled, TL.LogFilePath), EventLogEntryType.Information); TL.LogMessage("EarthRotationUpdate", string.Format("Log file: {0}, Trace state: {1}, Log file path: {2}", TL.LogFileName, parameters.DownloadTaskTraceEnabled, TL.LogFilePath)); TL.LogMessage("EarthRotationUpdate", string.Format("Earth rotation data last updated: {0}", parameters.EarthRotationDataLastUpdatedString)); TL.LogMessage("EarthRotationUpdate", string.Format("Data source: {0}", hostURIString)); DownloadTimeout = parameters.DownloadTaskTimeOut; WebClient client = new WebClient(); client.DownloadProgressChanged += Client_DownloadProgressChanged; client.DownloadFileCompleted += Client_DownloadFileCompleted; Uri hostURI = new Uri(hostURIString); if (WebRequest.DefaultWebProxy.GetProxy(hostURI) == hostURI) { TL.LogMessage("EarthRotationUpdate", "No proxy server detected, going directly to Internet"); // No proxy is in use so go straight out } else // Proxy is in use so set it and apply credentials { TL.LogMessage("EarthRotationUpdate", "Setting default proxy"); client.Proxy = WebRequest.DefaultWebProxy; TL.LogMessage("EarthRotationUpdate", "Setting default credentials"); client.Proxy.Credentials = CredentialCache.DefaultCredentials; TL.LogMessage("EarthRotationUpdate", "Using proxy server: " + WebRequest.DefaultWebProxy.GetProxy(hostURI).ToString()); } client.Headers.Add("user-agent", GlobalItems.DOWNLOAD_TASK_USER_AGENT); client.Headers.Add("Accept", "text/plain"); client.Encoding = Encoding.ASCII; client.BaseAddress = hostURIString; NetworkCredential credentials = new NetworkCredential("anonymous", "guest"); // Apply some standard credentials for FTP sites client.Credentials = credentials; TL.BlankLine(); // Get the latest delta UT1 values try { string dUT1fileName = DownloadFile("DeltaUT1", GlobalItems.DELTAUT1_FILE, client, TL); // Download the latest delta UT1 values and receive the filename holding the data FileInfo info = new FileInfo(dUT1fileName); // Find out if we have any data if (info.Length > 0) // We actually received some data so process it { // List the data postion parameters that wil be used to extract the delta UT1 data from the file TL.LogMessage("DeltaUT1", string.Format("Expected file format for the {0} file", GlobalItems.DELTAUT1_FILE)); TL.LogMessage("DeltaUT1", string.Format("Year string start position: {0}, Year string length: {1}", GlobalItems.DELTAUT1_YEAR_START, GlobalItems.DELTAUT1_YEAR_LENGTH)); TL.LogMessage("DeltaUT1", string.Format("Month string start position: {0}, Month string length: {1}", GlobalItems.DELTAUT1_MONTH_START, GlobalItems.DELTAUT1_MONTH_LENGTH)); TL.LogMessage("DeltaUT1", string.Format("Day string start position: {0}, Day string length: {1}", GlobalItems.DELTAUT1_DAY_START, GlobalItems.DELTAUT1_DAY_LENGTH)); TL.LogMessage("DeltaUT1", string.Format("Julian date start position: {0}, Julian date string length: {1}", GlobalItems.DELTAUT1_JULIAN_DATE_START, GlobalItems.DELTAUT1_JULIAN_DATE_LENGTH)); TL.LogMessage("DeltaUT1", string.Format("Delta UT1 start position: {0}, Delta UT1 string length: {1}", GlobalItems.DELTAUT1_START, GlobalItems.DELTAUT1_LENGTH)); TL.BlankLine(); profile.DeleteKey(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME); // Clear out old delta UT1 values profile.CreateKey(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME); // Process the data file using (var filestream = new FileStream(dUT1fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var file = new StreamReader(filestream, Encoding.ASCII, true, 4096)) { string lineOfText; DateTime date; while ((lineOfText = file.ReadLine()) != null) // Get lines of text one at a time and parse them { try { // Extract string values for data items string yearString = lineOfText.Substring(GlobalItems.DELTAUT1_YEAR_START, GlobalItems.DELTAUT1_YEAR_LENGTH); string monthString = lineOfText.Substring(GlobalItems.DELTAUT1_MONTH_START, GlobalItems.DELTAUT1_MONTH_LENGTH); string dayString = lineOfText.Substring(GlobalItems.DELTAUT1_DAY_START, GlobalItems.DELTAUT1_DAY_LENGTH); string julianDateString = lineOfText.Substring(GlobalItems.DELTAUT1_JULIAN_DATE_START, GlobalItems.DELTAUT1_JULIAN_DATE_LENGTH); string dUT1String = lineOfText.Substring(GlobalItems.DELTAUT1_START, GlobalItems.DELTAUT1_LENGTH); // Validate that the data items are parseable bool yearOK = int.TryParse(yearString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int year); bool monthOK = int.TryParse(monthString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int month); bool dayOK = int.TryParse(dayString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int day); bool julianDateOK = double.TryParse(julianDateString, NumberStyles.Float, CultureInfo.InvariantCulture, out double julianDate); bool dut1OK = double.TryParse(dUT1String, NumberStyles.Float, CultureInfo.InvariantCulture, out double dUT1); if (yearOK & monthOK & dayOK & julianDateOK & dut1OK) // We have good values for all data items so save these to the Profile { year = invariantCulture.Calendar.ToFourDigitYear(year); // Convert the two digit year to a four digit year date = new DateTime(year, month, day); // Only save the item if it is from a few days back or is a future prediction if (date.Date >= DateTime.Now.Date.Subtract(new TimeSpan(GlobalItems.DOWNLOAD_TASK_NUMBER_OF_BACK_DAYS_OF_DELTAUT1_DATA_TO_LOAD, 0, 0, 0))) { string deltaUT1ValueName = string.Format(GlobalItems.DELTAUT1_VALUE_NAME_FORMAT, date.Year.ToString(GlobalItems.DELTAUT1_VALUE_NAME_YEAR_FORMAT), date.Month.ToString(GlobalItems.DELTAUT1_VALUE_NAME_MONTH_FORMAT), date.Day.ToString(GlobalItems.DELTAUT1_VALUE_NAME_DAY_FORMAT)); TL.LogMessage("DeltaUT1", string.Format("Setting {0}, JD = {1} - DUT1 = {2} with key: {3}", date.ToLongDateString(), julianDate, dUT1, deltaUT1ValueName)); profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_DELTAUT1_SUBKEY_NAME, deltaUT1ValueName, dUT1.ToString("0.000", CultureInfo.InvariantCulture)); } } else { TL.LogMessage("DeltaUT1", string.Format("Unable to parse Delta UT1 values from the line below - Year: {0}, Month: {1}, Day: {2}, Julian Day: {3},Delta UT1: {4}", yearString, monthString, dayString, julianDateString, dUT1String)); TL.LogMessage("DeltaUT1", string.Format("Corrupt line: {0}", lineOfText)); } } catch (Exception ex) { TL.LogMessageCrLf("DeltaUT1", string.Format("Unexpected exception: {0}, parsing line: ", ex.Message, lineOfText)); TL.LogMessageCrLf("DeltaUT1", ex.ToString()); } } } } } else { TL.LogMessage("DeltaUT1", string.Format("Downloaded file size was zero so nothing to process!")); } File.Delete(dUT1fileName); TL.BlankLine(); } catch (WebException ex) // An issue occured with receiving the leap second file over the network { TL.LogMessageCrLf("DeltaUT1", string.Format("Error: {0} - delta UT1 data not updated", ex.Message)); ReturnCode = 1; } catch (Exception ex) { TL.LogMessageCrLf("DeltaUT1", ex.ToString()); ReturnCode = 2; } // Get the latest leap second values try { string leapSecondsfileName = DownloadFile("LeapSeconds", GlobalItems.LEAP_SECONDS_FILE, client, TL); // Download the latest leap second values and receive the filename holding the data FileInfo info = new FileInfo(leapSecondsfileName); // Find out if we have any data if (info.Length > 0) // We actually received some data so process it { // List the data postion parameters that wil be used to extract the delta UT1 data from the file TL.LogMessage("LeapSeconds", string.Format("Expected file format for the {0} file", GlobalItems.DELTAUT1_FILE)); TL.LogMessage("LeapSeconds", string.Format("Year string start position: {0}, Year string length: {1}", GlobalItems.LEAP_SECONDS_YEAR_START, GlobalItems.LEAP_SECONDS_YEAR_LENGTH)); TL.LogMessage("LeapSeconds", string.Format("Month string start position: {0}, Month string length: {1}", GlobalItems.LEAP_SECONDS_MONTH_START, GlobalItems.LEAP_SECONDS_MONTH_LENGTH)); TL.LogMessage("LeapSeconds", string.Format("Day string start position: {0}, Day string length: {1}", GlobalItems.LEAP_SECONDS_DAY_START, GlobalItems.LEAP_SECONDS_DAY_LENGTH)); TL.LogMessage("LeapSeconds", string.Format("Julian date start position: {0}, Julian date string length: {1}", GlobalItems.LEAP_SECONDS_JULIAN_DATE_START, GlobalItems.LEAP_SECONDS_JULIAN_DATE_LENGTH)); TL.LogMessage("LeapSeconds", string.Format("Leap seconds start position: {0}, Leap seconds string length: {1}", GlobalItems.LEAP_SECONDS_LEAPSECONDS_START, GlobalItems.LEAP_SECONDS_LEAPSECONDS_LENGTH)); TL.BlankLine(); profile.DeleteKey(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME);; // Clear out old leap second values profile.CreateKey(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME); // Include a value that is in the SOFA library defaults but is not in the USNO files. It predates the start of UTC but I am assuming that IAU is correct on this occasion profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME, double.Parse("2436934.5", CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture), double.Parse("1.4178180", CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture)); // Process the data file using (var filestream = new FileStream(leapSecondsfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { double currentLeapSeconds = 0.0; double nextLeapSeconds = 0.0; DateTime leapSecondDate = DateTime.MinValue;; DateTime nextleapSecondsDate = DateTime.MinValue; using (var file = new StreamReader(filestream, Encoding.ASCII, true, 4096)) { string lineOfText; DateTime latestLeapSecondDate = DateTime.MinValue; while ((lineOfText = file.ReadLine()) != null) // Get lines of text one at a time and parse them { try { // Read values from the file as strings based on their position within the file string yearString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_YEAR_START, GlobalItems.LEAP_SECONDS_YEAR_LENGTH); string monthString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_MONTH_START, GlobalItems.LEAP_SECONDS_MONTH_LENGTH); string dayString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_DAY_START, GlobalItems.LEAP_SECONDS_DAY_LENGTH); string julianDateString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_JULIAN_DATE_START, GlobalItems.LEAP_SECONDS_JULIAN_DATE_LENGTH); string leapSecondsString = lineOfText.Substring(GlobalItems.LEAP_SECONDS_LEAPSECONDS_START, GlobalItems.LEAP_SECONDS_LEAPSECONDS_LENGTH); // Validate that the data items are parseable bool yearOK = int.TryParse(yearString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int year); bool dayOK = int.TryParse(dayString, NumberStyles.Integer, CultureInfo.InvariantCulture, out int day); bool julianDateOK = double.TryParse(julianDateString, NumberStyles.Float, CultureInfo.InvariantCulture, out double julianDate); bool leapSecondsOK = double.TryParse(leapSecondsString, NumberStyles.Float, CultureInfo.InvariantCulture, out double leapSeconds); // Get the month number by triming the month string, converting to lower case then titlecase then looking up the index in the abbreviated months array int month = Array.IndexOf(monthAbbrev, invariantTextInfo.ToTitleCase(monthString.Trim(' ').ToLower(CultureInfo.InvariantCulture))) + 1; // If IndexOf fails, it returns -1 so the resultant month number will be zero and this is checked below if (yearOK & (month > 0) & dayOK & julianDateOK & leapSecondsOK) // We have good values for all data items so save these to the Profile { double modifiedJulianDate = julianDate - GlobalItems.MODIFIED_JULIAN_DAY_OFFSET; leapSecondDate = new DateTime(year, month, day); // Write all leap second values and julian dates that they become effective to the leap second history subkey profile.WriteProfile(GlobalItems.AUTOMATIC_UPDATE_LEAP_SECOND_HISTORY_SUBKEY_NAME, julianDate.ToString(CultureInfo.InvariantCulture), leapSeconds.ToString(CultureInfo.InvariantCulture)); if ((leapSecondDate.Date >= latestLeapSecondDate) & (leapSecondDate.Date <= DateTime.UtcNow.Date.Subtract(new TimeSpan(GlobalItems.TEST_HISTORIC_DAYS_OFFSET, 0, 0, 0)))) { currentLeapSeconds = leapSeconds; } if ((leapSecondDate.Date > DateTime.UtcNow.Date.Subtract(new TimeSpan(GlobalItems.TEST_HISTORIC_DAYS_OFFSET, 0, 0, 0))) & (nextleapSecondsDate == DateTime.MinValue)) // Record the next leap seconds value in the file { nextLeapSeconds = leapSeconds; nextleapSecondsDate = leapSecondDate; } TL.LogMessage("LeapSeconds", string.Format("Leap second takes effect on: {0}, Modified JD = {1} - Current Leap Seconds = {2}, Latest Leap Seconds: {3}, Next Leap Seconds: {4} on {5}", leapSecondDate.ToLongDateString(), modifiedJulianDate, leapSeconds, currentLeapSeconds, nextLeapSeconds, nextleapSecondsDate.ToLongDateString())); } else { TL.LogMessage("LeapSeconds", string.Format("Unable to parse leap second values from the line below - Year: {0}, Month: {1}, Day: {2}, Julian Day: {3},Leap seconds: {4}", yearString, monthString, dayString, julianDateString, leapSecondsString)); TL.LogMessage("LeapSeconds", string.Format("Corrupt line: {0}", lineOfText)); } } catch (Exception ex) { TL.LogMessageCrLf("LeapSeconds", ex.ToString()); } } } TL.BlankLine(); parameters.AutomaticLeapSecondsString = currentLeapSeconds.ToString(CultureInfo.InvariantCulture); // Persist the new leap second value to the Profile // Persist the next leap second value and its implementation date if these have been announced if (nextleapSecondsDate == DateTime.MinValue) // No annoucement has been made { parameters.NextLeapSecondsString = GlobalItems.DOWNLOAD_TASK_NEXT_LEAP_SECONDS_NOT_PUBLISHED_MESSAGE; parameters.NextLeapSecondsDateString = GlobalItems.DOWNLOAD_TASK_NEXT_LEAP_SECONDS_NOT_PUBLISHED_MESSAGE; } else // A future leap second has been announced { parameters.NextLeapSecondsString = nextLeapSeconds.ToString(CultureInfo.InvariantCulture); parameters.NextLeapSecondsDateString = nextleapSecondsDate.ToString(GlobalItems.DOWNLOAD_TASK_TIME_FORMAT, CultureInfo.InvariantCulture); } TL.BlankLine(); TL.LogMessage("LeapSeconds", string.Format("Current Leap Seconds = {0}, Next Leap Seconds: {1} on {2}", currentLeapSeconds, nextLeapSeconds, nextleapSecondsDate.ToLongDateString())); } } else { TL.LogMessage("LeapSeconds", string.Format("Downloaded file size was zero so nothing to process!")); } parameters.EarthRotationDataLastUpdatedString = runDate; // Save a new last run time to the Profile TL.BlankLine(); TL.LogMessage("LeapSeconds", string.Format("Task completed.")); File.Delete(leapSecondsfileName); parameters.Dispose(); parameters = null; } catch (WebException ex) // An issue occured with receiving the leap second file over the network { TL.LogMessageCrLf("LeapSeconds", string.Format("Error: {0} - leap second data not updated.", ex.Message)); ReturnCode = 3; } catch (Exception ex) { TL.LogMessageCrLf("LeapSeconds", ex.ToString()); ReturnCode = 4; } TL.Enabled = false; TL.Dispose(); TL = null; } catch (Exception ex) { try { TL.LogMessageCrLf("EarthRotationUpdate", ex.ToString()); } catch { } EventLogCode.LogEvent("EarthRotationUpdate", string.Format("EarthRotationUpdate - Unexpected exception: {0}", ex.Message), EventLogEntryType.Error, GlobalConstants.EventLogErrors.EarthRotationUpdate, ex.ToString()); ReturnCode = 5; } Environment.Exit(ReturnCode); }
/// <summary> /// Convert to title case. /// </summary> /// <param name="str">Convert string.</param> /// <returns>Converted string.</returns> public static string ToTitle(string str) { TextInfo ti = CultureInfo.CurrentCulture.TextInfo; return(ti.ToTitleCase(str)); }
private void UpdateData() { foreach (InviteInfo data in Client.InviteData.Select(info => info.Value)) { InviteInfo data2 = data; Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { ChatListView.Items.Clear(); var notification = new InvitesNotification(); InviteInfo data1 = data2; notification.Accept.Click += (s, e) => { Client.SwitchPage(new TeamQueuePage(data1.stats.InvitationId)); Client.PVPNet.Accept(data1.stats.InvitationId); Client.InviteData.Remove(data1.stats.InvitationId); }; notification.Decline.Click += (s, e) => { Client.PVPNet.Decline(data2.stats.InvitationId); Client.InviteData.Remove(data2.stats.InvitationId); }; notification.TitleLabel.Content = "Game Invite"; notification.BodyTextbox.Text = data2.stats.Inviter + " has invited you to a game"; var m = JsonConvert.DeserializeObject <invitationRequest>(data2.stats.GameMetaData); string mapName; CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; string gameModeLower = textInfo.ToTitleCase(string.Format(m.gameMode.ToLower())); string gameTypeLower = textInfo.ToTitleCase(string.Format(m.gameType.ToLower())); //Why do I have to do this Riot? string gameTypeRemove = gameTypeLower.Replace("_game", ""); string removeAllUnder = gameTypeRemove.Replace("_", " "); notification.BodyTextbox.Text += "Mode: " + gameModeLower; switch (m.mapId) { case 1: mapName = "Summoners Rift"; break; case 10: mapName = "The Twisted Treeline"; break; case 12: mapName = "Howling Abyss"; break; case 8: mapName = "The Crystal Scar"; break; default: mapName = "Unknown Map"; break; } notification.BodyTextbox.Text += "Map: " + mapName; notification.BodyTextbox.Text += "Type: " + removeAllUnder; ChatListView.Items.Add(notification); })); } }
public static string FoodToString(Food _food) { string result = Regex.Replace(_food.ToString(), "([a-z])([A-Z])", (Match _match) => _match.Groups[1] + " " + _match.Groups[2]); return(TI.ToTitleCase(result)); }
void app_language() { if (Session["New"] != null) { DataTable ste_set = new DataTable(); ste_set = dbcon.Ora_Execute_table("select * from site_settings where ID IN ('1')"); DataTable gt_lng = new DataTable(); gt_lng = dbcon.Ora_Execute_table("select " + Session["site_languaage"].ToString() + " from Ref_language where ID IN ('478','448','1674','505','484','77','1565','513','1675','497','1288','190','176','1676','1677','1678','16','46','17','27','45','1141','1679','1680','1681','61','44','1682','1683','1684','34','1685','51','1686','1687','1688','1273','1264','15','133','1141','915','27') order by ID ASC"); CultureInfo culinfo = Thread.CurrentThread.CurrentUICulture; TextInfo txtinfo = culinfo.TextInfo; h1_tag.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[15][0].ToString().ToLower()); bb1_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[14][0].ToString().ToLower()); bb2_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[26][0].ToString().ToLower()); h3_tag.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[18][0].ToString().ToLower()); h3_tag2.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[12][0].ToString().ToLower()); h3_tag3.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[28][0].ToString().ToLower()); h3_tag4.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[29][0].ToString().ToLower()); pt1.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[12][0].ToString().ToLower()); pt2.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[28][0].ToString().ToLower()); pt3.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[29][0].ToString().ToLower()); lbl1_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[16][0].ToString().ToLower()); lbl2_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[25][0].ToString().ToLower()); lbl3_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[19][0].ToString().ToLower()); lbl4_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[27][0].ToString().ToLower()); lbl5_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[17][0].ToString().ToLower()); lbl6_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[24][0].ToString().ToLower()); lbl7_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[13][0].ToString().ToLower()); lbl8_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[30][0].ToString().ToLower()); lbl9_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[1][0].ToString().ToLower()); lbl10_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[7][0].ToString().ToLower()); lbl11_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[2][0].ToString().ToLower()); lbl12_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[3][0].ToString().ToLower()); lbl13_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[6][0].ToString().ToLower()); lbl14_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[21][0].ToString().ToLower()); lbl15_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[31][0].ToString().ToLower()); lbl16_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[32][0].ToString().ToLower()); lbl17_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[33][0].ToString().ToLower()); Rdbwar.Text = txtinfo.ToTitleCase(gt_lng.Rows[23][0].ToString().ToLower()); RdbBwar.Text = txtinfo.ToTitleCase(gt_lng.Rows[22][0].ToString().ToLower()); RadioButton6.Text = txtinfo.ToTitleCase(gt_lng.Rows[23][0].ToString().ToLower()); RadioButton9.Text = txtinfo.ToTitleCase(gt_lng.Rows[22][0].ToString().ToLower()); Button2.Text = txtinfo.ToTitleCase(gt_lng.Rows[9][0].ToString().ToLower()); Button1.Text = txtinfo.ToTitleCase(gt_lng.Rows[10][0].ToString().ToLower()); lbl18_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[30][0].ToString().ToLower()); lbl19_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[1][0].ToString().ToLower()); lbl20_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[7][0].ToString().ToLower()); lbl21_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[6][0].ToString().ToLower()); lbl22_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[2][0].ToString().ToLower()); lbl23_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[5][0].ToString().ToLower()); lbl24_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[31][0].ToString().ToLower()); lbl25_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[4][0].ToString().ToLower()); lbl26_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[37][0].ToString().ToLower()); lbl27_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[8][0].ToString().ToLower()); lbl28_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[40][0].ToString().ToLower()); lbl29_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[33][0].ToString().ToLower()); RadioButton7.Text = txtinfo.ToTitleCase(gt_lng.Rows[23][0].ToString().ToLower()); RadioButton8.Text = txtinfo.ToTitleCase(gt_lng.Rows[22][0].ToString().ToLower()); RadioButton10.Text = txtinfo.ToTitleCase(gt_lng.Rows[23][0].ToString().ToLower()); RadioButton11.Text = txtinfo.ToTitleCase(gt_lng.Rows[22][0].ToString().ToLower()); RadioButton1.Text = txtinfo.ToTitleCase(gt_lng.Rows[34][0].ToString().ToLower()); RadioButton2.Text = txtinfo.ToTitleCase(gt_lng.Rows[35][0].ToString().ToLower()); RadioButton3.Text = txtinfo.ToTitleCase(gt_lng.Rows[36][0].ToString().ToLower()); RadioButton4.Text = txtinfo.ToTitleCase(gt_lng.Rows[38][0].ToString().ToLower()); RadioButton5.Text = txtinfo.ToTitleCase(gt_lng.Rows[39][0].ToString().ToLower()); Button5.Text = txtinfo.ToTitleCase(gt_lng.Rows[9][0].ToString().ToLower()); Button8.Text = txtinfo.ToTitleCase(gt_lng.Rows[0][0].ToString().ToLower()); Button7.Text = txtinfo.ToTitleCase(gt_lng.Rows[11][0].ToString().ToLower()); lbl30_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[1][0].ToString().ToLower()); lbl31_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[21][0].ToString().ToLower() + " (R/P) "); lbl32_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[4][0].ToString().ToLower()); lbl33_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[20][0].ToString().ToLower()); lbl34_text.InnerText = txtinfo.ToTitleCase(gt_lng.Rows[3][0].ToString().ToLower()); Button3.Text = txtinfo.ToTitleCase(gt_lng.Rows[9][0].ToString().ToLower()); } else { Response.Redirect("../KSAIMB_Login.aspx"); } }
/// <summary> /// 将指定中文字符串转换为拼音形式 /// </summary> /// <param name="chs">要转换的中文字符串</param> /// <param name="separator">连接拼音之间的分隔符</param> /// <param name="initialCap">指定是否将首字母大写</param> /// <returns>包含中文字符串的拼音的字符串</returns> public static string CHSToPhoneticize(string chs, string separator, bool initialCap) { if (string.IsNullOrEmpty(chs)) { return(""); } if (string.IsNullOrEmpty(separator)) { separator = ""; } // 例外词组 chs = CHSPhraseSpecial.Cast <DictionaryEntry>().Aggregate(chs, (current, de) => current.Replace(de.Key.ToString(), String.Format("\r\r\r{0}\r\r\r", de.Value.ToString().Replace(" ", separator)))); string returnstr = ""; bool b = false, d = false; char[] nowchar = chs.ToCharArray(); CultureInfo ci = Thread.CurrentThread.CurrentCulture; TextInfo ti = ci.TextInfo; for (int j = 0; j < nowchar.Length; j++) { byte[] array = Encoding.Default.GetBytes(nowchar[j].ToString()); string s = nowchar[j].ToString(); if (array.Length == 1) { b = true; returnstr += s; } else { int i1 = (array[0]); int i2 = (array[1]); int chrasc = i1 * 256 + i2 - 65536; for (int i = (_phoneticizeValues.Length - 1); i >= 0; i--) { if (_phoneticizeValues[i] <= chrasc) { d = true; s = _phoneticizeNames[i]; if (initialCap) { s = ti.ToTitleCase(s); } if (returnstr == "" || b) { returnstr += s; } else { returnstr += separator + s; } break; } d = false; } if (d == false) { returnstr += s; } b = false; } } returnstr = returnstr.Replace("\r\r\r", separator); return(returnstr); }
private void btnActualizarDocente_Click(object sender, EventArgs e) { try { string sexo = ""; DialogResult boton; boton = MessageBox.Show("Esta seguro que desea actualizar la informacion del docente...?", "ADVERTENCIA", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (boton == System.Windows.Forms.DialogResult.Yes) { // UPDATE Docente if (validarCamposObligatoriosDocente()) { string[] numeros = txtCelularDocente.Text.Split('-'); string numero = ""; for (int i = 0; i < numeros.Length; i++) { numero += numeros[i]; } SqlCommand cmd = new SqlCommand("Update Docente set apPaterno = @apPaterno, apMaterno = @apMaterno, nombre = @nombre, sexo = @sexo, telefono = @telefono, celular = @celular, dni = @dni, direccion = @direccion, profesion = @profesion, gradoAcademico = @gradoAcademico where codDocente = @codDoc", conex); cmd.Parameters.Add("@codDoc", SqlDbType.Int).Value = cod; cmd.Parameters.Add("@apPaterno", SqlDbType.VarChar, 50).Value = (info.ToTitleCase(txtPaternoDocente.Text.ToLower())); cmd.Parameters.Add("@apMaterno", SqlDbType.VarChar, 50).Value = info.ToTitleCase(txtMaternoDocente.Text.ToLower()); cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 100).Value = info.ToTitleCase(txtNombreDocente.Text.ToLower()); if (rbtnMasculinoEst.Checked) { sexo = "M"; } else { sexo = "F"; } cmd.Parameters.Add("@sexo", SqlDbType.Char, 1).Value = sexo; cmd.Parameters.Add("@telefono", SqlDbType.Char, 9).Value = txtTelefonoDocente.Text; cmd.Parameters.Add("@celular", SqlDbType.Char, 9).Value = numero; cmd.Parameters.Add("@dni", SqlDbType.Char, 8).Value = txtDNIDocente.Text; cmd.Parameters.Add("@direccion", SqlDbType.VarChar, 100).Value = info.ToTitleCase(txtDireccionDocente.Text.ToLower()); cmd.Parameters.Add("@profesion", SqlDbType.VarChar, 100).Value = info.ToTitleCase(txtProfesionDocente.Text.ToLower()); cmd.Parameters.Add("@gradoAcademico", SqlDbType.VarChar, 100).Value = info.ToTitleCase(txtGradoAcademico.Text.ToLower()); conex.Open(); int resp = cmd.ExecuteNonQuery(); conex.Close(); if (resp == 1) { controles_usuario.CustomDialog.ShowDialog("ACTUALIZACION DE INFORMACION DE DOCENTE EXITOSA !!!"); } else { MessageBox.Show("ERROR AL INTENTAR ACTULIZAR INFORMACION DE DOCENTE!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Close(); } else { MessageBox.Show("Existen datos obligatorios!! \n Datos incompletos...!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static bool DoRefine(Dictionary <string, string> options) { string outputPath = null; string outputFormat = null; string oldOriginPath = null; string oldTranslationPath = null; string oldOriginFormat = null; string oldTranslationFormat = null; if (!options.TryGetValue("output-path", out outputPath)) { throw new ArgumentException("Missing output-path."); } if (!options.TryGetValue("output-format", out outputFormat)) { throw new ArgumentException("Missing output-format."); } if (!options.TryGetValue("old-original-path", out oldOriginPath)) { throw new ArgumentException("Missing old-original-path."); } if (!options.TryGetValue("old-original-format", out oldOriginFormat)) { throw new ArgumentException("Missing old-original-format."); } if (!options.TryGetValue("old-translation-path", out oldTranslationPath)) { throw new ArgumentException("Missing old-translation-path."); } if (!options.TryGetValue("old-translation-format", out oldTranslationFormat)) { throw new ArgumentException("Missing old-translation-format."); } // all dummy english for now.. SingleLanguageDB oldEng = new SingleLanguageDB("english"); SingleLanguageDB oldTranslate = new SingleLanguageDB("english"); Localization.BatchImportToSingleLanguageDB(oldEng, oldOriginPath, oldOriginFormat); Localization.BatchImportToSingleLanguageDB(oldTranslate, oldTranslationPath, oldTranslationFormat); Dictionary <string, string> dict1 = new Dictionary <string, string>(); Dictionary <string, string> dict2 = new Dictionary <string, string>(); foreach (var kv in oldEng) { string tag = kv.Key; if ((tag.Length > 2 && tag[1] == '_') || tag.StartsWith("PROV")) { continue; } string value = kv.Value.Last().Value; if (tag.ToLowerInvariant().Replace("_", "").Contains(value.ToLowerInvariant().Replace(" ", ""))) { dict1[tag] = value; } else { TextInfo ti = CultureInfo.CurrentCulture.TextInfo; if (value == ti.ToTitleCase(value)) { dict2[tag] = value; } } } YMLSafeFile dict1file = new YMLSafeFile(); YMLSafeFile dict2file = new YMLSafeFile(); dict1file.AppendLine(null, -1, "l_english:", null); dict2file.AppendLine(null, -1, "l_english:", null); foreach (var entry in dict1) { dict1file.AppendLine(null, -1, "# Potential Term, origin: " + entry.Value, null); string trans = oldTranslate.LookupLatestText(entry.Key)?.Item2; dict1file.AppendLine(entry.Key, 0, trans != null? trans : entry.Value, null); } foreach (var entry in dict2) { dict2file.AppendLine(null, -1, "# Potential Term, origin: " + entry.Value, null); string trans = oldTranslate.LookupLatestText(entry.Key)?.Item2; dict2file.AppendLine(entry.Key, 0, trans != null ? trans : entry.Value, null); } dict1file.Write(outputPath + "\\dict1." + dict1file.DefaultExtension()); dict2file.Write(outputPath + "\\dict2." + dict1file.DefaultExtension()); return(true); }
public async Task <int> UpdateAuxiliarAsync(ResultInstruction instruction, Conexion conexion, Comuna comuna) { string name; string acteco = null; CultureInfo cultureInfo = CultureInfo.GetCultureInfo("es-CL"); TextInfo ti = CultureInfo.CurrentCulture.TextInfo; string time = string.Format(cultureInfo, "{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now); string adressTemp = ti.ToTitleCase(instruction.ParticipantDebtor.CommercialAddress.ToLower()); if (instruction.ParticipantDebtor.CommercialAddress.Contains(',')) { int index = instruction.ParticipantDebtor.CommercialAddress.IndexOf(','); adressTemp = instruction.ParticipantDebtor.CommercialAddress.Substring(0, index); } if (adressTemp.Length > 60) { adressTemp = adressTemp.Substring(0, 60); } // Address if (instruction.ParticipantDebtor.BusinessName.Length > 60) { name = instruction.ParticipantDebtor.BusinessName.Substring(0, 60); } else { name = instruction.ParticipantDebtor.BusinessName; } // Get acteco from CEN if (true) { } if (instruction.ParticipantDebtor.CommercialBusiness != null) { if (instruction.ParticipantDebtor.CommercialBusiness.Length > 60) { acteco = instruction.ParticipantDebtor.CommercialBusiness.Substring(0, 60); } else { acteco = instruction.ParticipantDebtor.CommercialBusiness; } // Insert new Acteco await Acteco.InsertActecoAsync(acteco, conexion); } // Production: if (Environment.MachineName == "DEVELOPER") { time = string.Format(cultureInfo, "{0:g}", DateTime.Now); } try { StringBuilder query = new StringBuilder(); string rut = string.Format(CultureInfo.CurrentCulture, "{0:N0}", instruction.ParticipantDebtor.Rut).Replace(',', '.'); query.Append($"UPDATE softland.cwtauxi SET NomAux='{name}', NoFAux='{instruction.ParticipantDebtor.Name}', ClaCli = 'S', ClaPro = 'S', Bloqueado = 'N', "); query.Append($"Comaux = '{comuna.ComCod}', GirAux = (SELECT TOP 1 GirCod from softland.cwtgiro where GirDes = '{acteco}' ), EsReceptorDTE = 'S', PaiAux='CL', ActAux='S', "); query.Append($"Usuario='Softland', Proceso='Centralizador', Sistema='IW', RutAux='{rut}-{instruction.ParticipantDebtor.VerificationCode}', FechaUlMod ='{time}', "); query.Append($"DirAux = '{adressTemp}', "); query.Append($"eMailDTE='{instruction.ParticipantDebtor.DteReceptionEmail}' WHERE CodAux='{instruction.ParticipantDebtor.Rut}'"); conexion.Query = query.ToString(); var res = await Conexion.ExecuteNonQueryAsync(conexion); return((int)res); } catch (Exception) { throw; } }
/// <summary> /// Show list of Output to user by OutputParameter and value /// </summary> /// <param name="outputPlace">div of output</param> /// <param name="sciprtPlaceHolde"> div of script if need </param> /// <param name="outputParam"> list of output Prameter </param> /// <param name="listOutput"> list of Output Object (name, list value) </param> /// <param name="page"> Main page </param> static public void ShowOutput(PlaceHolder outputPlace, PlaceHolder sciprtPlaceHolde, List <AMLParam> outputParam, List <OutputObject> listOutput, Page page) { outputPlace.Controls.Clear(); if (listOutput == null) { return; } Dictionary <string, double> listOutputNumber = new Dictionary <string, double>(); outputPlace.Controls.Add(new LiteralControl("<p class=\"titleresult\">Result</p>")); int count = 0; outputPlace.Controls.Add(new LiteralControl("<table class=\"table table-hover table-bordered\">")); outputPlace.Controls.Add(new LiteralControl("<tr class=\"info\"><th>Label</th><th>Value</th></tr>")); foreach (OutputObject outputObj in listOutput) { var listXmlOutput = outputParam.Where(x => (x.Group == outputObj.Name)).ToList(); if (outputObj.Values.Count == 0) { count += listXmlOutput.Count; continue; } bool showOutputLabel = false; for (int i = 0; i < outputObj.Values.Count; i++) { if (outputParam[count + i].Enable) { showOutputLabel = true; break; } } if (showOutputLabel) { outputPlace.Controls.Add(new LiteralControl("<tr><td colspan=\"2\" style=\"background-color: azure\">" + outputObj.Name + "</td></tr>")); } for (int i = 0; i < outputObj.Values.Count; i++) { AMLParam param = outputParam[count++]; //AMLParam param = new AMLParam(); // Check value, if empty, skip this field, don't show on output region if (param.Enable) { //if (string.IsNullOrEmpty(outputObj.Values[i])) continue; // Show image from output if (param.Name.Contains("R Output JSON")) { outputPlace.Controls.Add(new LiteralControl("<tr>")); outputPlace.Controls.Add(new LiteralControl(string.Format("<td class=\"textresult\">{0}</td>", textInfo.ToTitleCase(param.Name)))); if (!string.IsNullOrEmpty(outputObj.Values[i])) { outputPlace.Controls.Add(new LiteralControl(string.Format("<td>{0}</td>", "Please check Image"))); } else { outputPlace.Controls.Add(new LiteralControl(string.Format("<td></td>"))); } outputPlace.Controls.Add(new LiteralControl("</tr>")); if (!string.IsNullOrEmpty(outputObj.Values[i])) { Image img = new Image(); img.ImageUrl = @"data:image/png;base64," + getImageData(outputObj.Values[i]); img.Style["width"] = "100%"; img.Style["max-width"] = "480px"; // add picture outsite of table (script path) sciprtPlaceHolde.Controls.Add(new LiteralControl("<div style=\"text-align:center\">")); sciprtPlaceHolde.Controls.Add(img); sciprtPlaceHolde.Controls.Add(new LiteralControl("</div>")); } } else if (param.Name.Equals("Graphics")) { outputPlace.Controls.Add(new LiteralControl("<tr>")); outputPlace.Controls.Add(new LiteralControl(string.Format("<td class=\"textresult\">{0}</td>", textInfo.ToTitleCase(param.Name)))); if (!string.IsNullOrEmpty(outputObj.Values[i])) { outputPlace.Controls.Add(new LiteralControl(string.Format("<td>{0}</td>", "Please check Image"))); } else { outputPlace.Controls.Add(new LiteralControl(string.Format("<td></td>"))); } outputPlace.Controls.Add(new LiteralControl("</tr>")); if (!string.IsNullOrEmpty(outputObj.Values[i])) { Image img = new Image(); img.ImageUrl = @"data:image/png;base64," + outputObj.Values[i]; img.Style["width"] = "100%"; img.Style["max-width"] = "480px"; // add picture outsite of table (script path) sciprtPlaceHolde.Controls.Add(new LiteralControl("<div style=\"text-align:center\">")); sciprtPlaceHolde.Controls.Add(img); sciprtPlaceHolde.Controls.Add(new LiteralControl("</div>")); } } else { outputPlace.Controls.Add(new LiteralControl("<tr>")); outputPlace.Controls.Add(new LiteralControl(string.Format("<td class=\"textresult\">{0}</td>", string.IsNullOrEmpty(param.Alias) ? textInfo.ToTitleCase(param.Name) : param.Alias))); outputPlace.Controls.Add(new LiteralControl(string.Format("<td style=\"word-break: break-all;\">{0}</td>", outputObj.Values[i].Trim('\"')))); if (param.Type == "number") { double tmp = 0; try { tmp = Math.Round(Convert.ToDouble(outputObj.Values[i].Trim('\"')), 2); listOutputNumber.Add(!string.IsNullOrEmpty(param.Alias) ? param.Alias : param.Name, tmp); } catch (Exception) { }; } outputPlace.Controls.Add(new LiteralControl("</tr>")); } } //count++; } } outputPlace.Controls.Add(new LiteralControl("</table>")); //if (listOutputNumber.Count == 1) // ScriptManager.RegisterStartupScript(page, page.GetType(), "script", "loadPercentage(" + listOutputNumber.First().Value + ");", true); //else if (listOutputNumber.Count > 1) sciprtPlaceHolde.Controls.Add(GenerateScriptBarGraph(listOutputNumber)); }
private void TxtPatientID_TextChanged(object sender, EventArgs e) { txtPatientID.Text = textInfo.ToTitleCase(txtPatientID.Text); }
private void SendEmail() { /* Vérifie si email valide et non vide */ string emailToSend = utils.RemoveDiacritics(emailAgence.ToLower().Trim()); if (utils.IsEmailValid(emailToSend) == true && emailToSend.Length > 3) { try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(); TextInfo ti = CultureInfo.CurrentCulture.TextInfo; /* Vérifie si "vu avec " */ if (contact.Trim().Length > 0) { ligContact = "Vu avec " + ti.ToTitleCase(contact.ToLower()) + "\n\n"; } /* Message */ if (remarque.Length > 0) { ligRemarque = "Remarque : \n" + remarque + "\n\n"; } /* Vérifie si client ou stock */ if (stock == true) { ligClient = "Pour stock magasin \n\n"; } else { ligClient = "Client : " + client + "\n\n"; } /* Bonne journée/aprem/soirée */ if (DateTime.Now.Hour > 4 && DateTime.Now.Hour <= 17) { ligBonneJournee = "Bonne journée."; } if (DateTime.Now.Hour > 17 && DateTime.Now.Hour <= 22) { ligBonneJournee = "Bonne soirée."; } if (DateTime.Now.Hour > 22 && DateTime.Now.Hour <= 4) { ligBonneJournee = "Bonne nuit."; } mail.From = new MailAddress(utils.ReadSetting("emailAgence"), "Hifi International"); mail.To.Add(emailToSend); //mail.To.Add("*****@*****.**"); mail.CC.Add(utils.ReadSetting("emailAgence")); // Copie à l'agence mail.Subject = "Demande de transfert"; string bodyEmail = "Bonjour,\n\n" + "Merci de tranférer le ou les articles suivants : \n\n" + "--------------------------\n\n" + articles + "\n\n" + "--------------------------\n\n" + ligContact + ligRemarque + ligClient + "Merci !\n" + ligBonneJournee + "\n\n" + ti.ToTitleCase(vendeur.ToLower()) + "\n\n" + utils.ReadSetting("nomAgence") + "\n" + utils.ReadSetting("adresse1Agence") + "\n" + utils.ReadSetting("adresse2Agence") + "\n" + utils.ReadSetting("cpAgence") + " " + utils.ReadSetting("villeAgence") + "\n" + "Tél. : " + utils.ReadSetting("telAgence") + "\n" + "Fax. : " + utils.ReadSetting("faxAgence") + "\n" + "Email : " + utils.ReadSetting("emailAgence") + "\n"; mail.Body = bodyEmail; SmtpServer.Port = int.Parse(utils.ReadSetting("emailPort")); SmtpServer.Host = utils.ReadSetting("emailSmtp"); //SmtpServer.UseDefaultCredentials = true; SmtpServer.Credentials = new NetworkCredential(utils.ReadSetting("emailUser"), utils.ReadSetting("emailPassword")); SmtpServer.EnableSsl = true; /* Envoi du mail dans un thread séparé */ Thread T1 = new Thread(delegate() { SmtpServer.Send(mail); mail.Dispose(); SmtpServer.Dispose(); }); T1.Start(); MessageBox.Show("La demande de transfert a été envoyée avec succès par e-mail.", "Demande expédiée", MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); } catch (Exception ex) { /*Console.WriteLine( * "Exception caught in CreateTestMessage1(): {0}", * ex.ToString());*/ } } else { /* Email non valide */ MessageBox.Show("L'adresse email n'est pas valide !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo; return(textInfo.ToTitleCase(value.ToString())); }
/// <summary> /// Converts each word's first letter in the string to Uppercase (Invarient Culture) /// </summary> /// <param name="s">the input string</param> /// <returns></returns> public static string ToTitleCase(this string s) { TextInfo textInfo = CultureInfo.InvariantCulture.TextInfo; return(textInfo.ToTitleCase(s)); }