string TestEmail(Settings settings) { string email = settings.Email; string smtpServer = settings.SmtpServer; string smtpServerPort = settings.SmtpServerPort.ToString(); string smtpUserName = settings.SmtpUserName; string smtpPassword = settings.SmtpPassword; string enableSsl = settings.EnableSsl.ToString(); var mail = new MailMessage { From = new MailAddress(email, smtpUserName), Subject = string.Format("Test mail from {0}", smtpUserName), IsBodyHtml = true }; mail.To.Add(mail.From); var body = new StringBuilder(); body.Append("<div style=\"font: 11px verdana, arial\">"); body.Append("Success"); if (HttpContext.Current != null) { body.Append( "<br /><br />_______________________________________________________________________________<br /><br />"); body.AppendFormat("<strong>IP address:</strong> {0}<br />", Utils.GetClientIP()); body.AppendFormat("<strong>User-agent:</strong> {0}", HttpContext.Current.Request.UserAgent); } body.Append("</div>"); mail.Body = body.ToString(); return Utils.SendMailMessage(mail, smtpServer, smtpServerPort, smtpUserName, smtpPassword, enableSsl.ToString()); }
static void Main() { string inputStr = Console.ReadLine(); string multipleString = ""; while (inputStr != "END") { multipleString += inputStr; inputStr = Console.ReadLine(); } string pattern = @"(?<=<a).*?\s*href\s*=\s*((""[^""]*""(?=>))|('[^']*'(?=>))|([\w\/\:\.]+\.\w{3})|(\/[^'""]*?(?=>)))"; //string pattern = @"(?s)(?:<a)(?:[\s\n_0-9a-zA-Z=""()]*?.*?)(?:href([\s\n]*)?=(?:['""\s\n]*)?)([a-zA-Z:#\/._\-0-9!?=^+]*(\([""'a-zA-Z\s.()0-9]*\))?)(?:[\s\na-zA-Z=""()0-9]*.*?)?(?:\>)"; MatchCollection collection = Regex.Matches(multipleString, pattern); List<string> resultStrings = new List<string>(); foreach (Match match in collection) { StringBuilder tempStr = new StringBuilder(match.Groups[2].Value); if (tempStr[0] == '"' || tempStr[0] == '\'') { tempStr.Remove(0,1); } if (tempStr[tempStr.Length-1] == '"' || tempStr[tempStr.Length-1] == '\'') { tempStr.Remove(tempStr.Length-1,1); } resultStrings.Add(tempStr.ToString()); Console.WriteLine(tempStr); } //Console.WriteLine(string.Join("\r\n",resultStrings)); }
protected void Page_Load(object sender, EventArgs e) { IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container); if (Request["installation"] != null) { int installationid = Int32.Parse(Request["installation"]); userid = Int32.Parse(Request["userid"]); user = Request["user"]; sservice = container.Resolve<IStatisticService>(); IInstallationBL iinstall = container.Resolve<IInstallationBL>(); imodel = iinstall.getInstallation(installationid); Dictionary<InstallationModel, List<InstallationState>> statelist = sservice.getInstallationState(imodel.customerid); StringBuilder str = new StringBuilder(); str.Append("<table border = '1'><tr><th>Description</th><th>Messwert</th><th>Einheit</th></tr>"); foreach (var values in statelist) { if(values.Key.installationid.Equals(installationid)) { foreach (var item in values.Value) { str.Append("<tr><td>" + item.description + "</td><td>" + item.lastValue + "</td><td>" + item.unit + "</td></tr>"); } break; } } str.Append("</table>"); anlagenzustand.InnerHtml = str.ToString(); } }
public static string Encode(string str, string key) { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] bytes = Encoding.UTF8.GetBytes(str); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); StringBuilder builder = new StringBuilder(); foreach (byte num in stream.ToArray()) { builder.AppendFormat("{0:X2}", num); } stream.Close(); return builder.ToString(); }
protected virtual string FormatMethod(MethodBase method) { var sb = new StringBuilder(); if (method.DeclaringType != null) { sb.Append(method.DeclaringType.FullName); sb.Append("."); } sb.Append(method.Name); if (method.IsGenericMethod) { sb.Append("<"); sb.Append(string.Join(", ", method.GetGenericArguments().Select(t => t.Name))); sb.Append(">"); } sb.Append("("); var f = false; foreach (var p in method.GetParameters()) { if (f) sb.Append(", "); else f = true; sb.Append(p.ParameterType.Name); sb.Append(' '); sb.Append(p.Name); } sb.Append(")"); return sb.ToString(); }
internal static string Join(object thisob, string separator, bool localize) { StringBuilder builder = new StringBuilder(); uint num = Microsoft.JScript.Convert.ToUint32(LateBinding.GetMemberValue(thisob, "length")); if (num > 0x7fffffff) { throw new JScriptException(JSError.OutOfMemory); } if (num > builder.Capacity) { builder.Capacity = (int) num; } for (uint i = 0; i < num; i++) { object valueAtIndex = LateBinding.GetValueAtIndex(thisob, (ulong) i); if ((valueAtIndex != null) && !(valueAtIndex is Missing)) { if (localize) { builder.Append(Microsoft.JScript.Convert.ToLocaleString(valueAtIndex)); } else { builder.Append(Microsoft.JScript.Convert.ToString(valueAtIndex)); } } if (i < (num - 1)) { builder.Append(separator); } } return builder.ToString(); }
public static DataTable GetAllCidades(int estado_id) { DataTable retorno = new DataTable(); StringBuilder SQL = new StringBuilder(); SQL.Append(@"SELECT CidadeId, Nome FROM Cidade WHERE EstadoId = @ESTADO_ID"); try { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Mendes_varejo"].ConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand(SQL.ToString(), connection); command.Parameters.AddWithValue("@ESTADO_ID", estado_id); command.ExecuteNonQuery(); SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(retorno); } } catch (Exception erro) { throw erro; } return retorno; }
public string ComposeSentence(string[] words) { StringBuilder text = new StringBuilder(); bool hasSpace = true; for (int i = 0; i < words.Length; i++) { if (IsNoSpacePunctuation(words[i])) text.Append(words[i]); else if (IsReverseSpacePunctuation(words[i])) { hasSpace = false; text.Append(" " + words[i]); } else if (i == 0) { text.Append(StaticHelper.FirstLetterToUpper(words[i])); } else { if (words[i - 1] == ".") words[i] = StaticHelper.FirstLetterToUpper(words[i]); if (hasSpace) text.Append(" " + words[i]); else text.Append(words[i]); hasSpace = true; } } string newText = text.ToString().Trim(); return newText; }
static StringBuilder BuildExceptionReport(Exception e, StringBuilder sb, int d) { if (e == null) return sb; sb.AppendFormat("Exception of type `{0}`: {1}", e.GetType().FullName, e.Message); var tle = e as TypeLoadException; if (tle != null) { sb.AppendLine(); Indent(sb, d); sb.AppendFormat("TypeName=`{0}`", tle.TypeName); } else // TODO: more exception types { } if (e.InnerException != null) { sb.AppendLine(); Indent(sb, d); sb.Append("Inner "); BuildExceptionReport(e.InnerException, sb, d + 1); } sb.AppendLine(); Indent(sb, d); sb.Append(e.StackTrace); return sb; }
/// <summary> /// ดึงรายชื่อพนักงานตามเงื่อนไขที่กำหนด เพื่อนำไปแสดงบนหน้า ConvertByPayor /// </summary> /// <param name="doeFrom"></param> /// <param name="doeTo"></param> /// <param name="payor"></param> /// <returns></returns> public DataTable getPatient(DateTime doeFrom,DateTime doeTo,string payor,string mobileStatus) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); #region Variable var dt = new DataTable(); var strSQL = new StringBuilder(); var clsSQL = new clsSQLNative(); #endregion #region Procedure #region SQLQuery strSQL.Append("SELECT "); strSQL.Append("No,HN,PreName,Name,LastName,DOE,Payor,SyncWhen,'0' IsConvertPreOrder "); strSQL.Append("FROM "); strSQL.Append("Patient P "); strSQL.Append("WHERE "); strSQL.Append("(DOE BETWEEN '" + doeFrom.ToString("yyyy-MM-dd HH:mm") + "' AND '" + doeTo.ToString("yyyy-MM-dd HH:mm") + "') "); if(payor!="" && payor.ToLower() != "null") { strSQL.Append("AND Payor='"+payor+"' "); } if (mobileStatus == "NotRegister") { strSQL.Append("AND SyncStatus!='1' "); } else if (mobileStatus == "Register") { strSQL.Append("AND SyncStatus='1' "); } strSQL.Append("ORDER BY "); strSQL.Append("No;"); #endregion dt = clsSQL.Bind(strSQL.ToString(), clsSQLNative.DBType.SQLServer, "MobieConnect"); #endregion return dt; }
public void TopUsersThatLiked(StringBuilder builder) { var users = GetUsersThatLiked(); if (users == null || users.Count == 0) { return; } var groupedUsers = users.GroupBy(x => x).Select(x => new { x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).ToList(); int to = 0; if (groupedUsers == null || groupedUsers.Count == 0) { return; } else if (groupedUsers.Count > 0 && groupedUsers.Count < 3) { to = groupedUsers.Count + 1; } else { to = 4; } builder.Append("top users that liked your links: "); mHtmlBuilder.For(1, to, i => { builder.Append(i); builder.Append(". <strong>"); builder.Append(mQuerier.GetNameByFId(groupedUsers[i-1].Key.ToString())); builder.Append("</strong> - <strong>"); builder.Append(groupedUsers[i - 1].Count); builder.Append("</strong> times"); }); }
public override void ToString(StringBuilder sb, IQueryWithParams query) { if (this.op == CriteriaOperator.Like || this.op == CriteriaOperator.NotLike) { var valueCriteria = this.right as ValueCriteria; if (query.Dialect.IsCaseSensitive() && !ReferenceEquals(null, valueCriteria) && valueCriteria.Value is string) { sb.Append("UPPER("); this.left.ToString(sb, query); sb.Append(this.op == CriteriaOperator.Like ? ") LIKE UPPER(" : ") NOT LIKE UPPER("); this.right.ToString(sb, query); sb.Append(")"); } else { this.left.ToString(sb, query); sb.Append(this.op == CriteriaOperator.Like ? " LIKE " : " NOT LIKE "); this.right.ToString(sb, query); } } else { this.left.ToString(sb, query); sb.Append(opText[(int)this.op - (int)CriteriaOperator.AND]); this.right.ToString(sb, query); } }
/// <summary> Renders the HTML for this element </summary> /// <param name="Output"> Textwriter to write the HTML for this element </param> /// <param name="Bib"> Object to populate this element from </param> /// <param name="Skin_Code"> Code for the current skin </param> /// <param name="IsMozilla"> Flag indicates if the current browse is Mozilla Firefox (different css choices for some elements)</param> /// <param name="PopupFormBuilder"> Builder for any related popup forms for this element </param> /// <param name="Current_User"> Current user, who's rights may impact the way an element is rendered </param> /// <param name="CurrentLanguage"> Current user-interface language </param> /// <param name="Translator"> Language support object which handles simple translational duties </param> /// <param name="Base_URL"> Base URL for the current request </param> /// <remarks> This simple element does not append any popup form to the popup_form_builder</remarks> public override void Render_Template_HTML(TextWriter Output, SobekCM_Item Bib, string Skin_Code, bool IsMozilla, StringBuilder PopupFormBuilder, User_Object Current_User, Web_Language_Enum CurrentLanguage, Language_Support_Info Translator, string Base_URL) { // Check that an acronym exists if (Acronym.Length == 0) { Acronym = "Enter the name(s) of the other committee members for this thesis/dissertation"; } // Is there an ETD object? Thesis_Dissertation_Info etdInfo = Bib.Get_Metadata_Module(GlobalVar.THESIS_METADATA_MODULE_KEY) as Thesis_Dissertation_Info; if ((etdInfo == null) || ( etdInfo.Committee_Members_Count == 0 )) { render_helper(Output, String.Empty, Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL); } else { if (etdInfo.Committee_Members_Count == 1) { render_helper(Output, etdInfo.Committee_Members[0], Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL); } else { render_helper(Output, etdInfo.Committee_Members, Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL); } } }
public static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt")); Debug.Listeners.Add(new ConsoleTraceListener()); #endif Stopwatch sw = new Stopwatch(); sw.Start(); StringBuilder sb = new StringBuilder(); int lines = int.Parse(Console.ReadLine()); for (int i = 0; i < lines; i++) { string line = Console.ReadLine(); bool isValid = Validate(line); if (isValid) { sb.AppendLine("VALID"); } else { sb.AppendLine("INVALID"); } } sw.Stop(); Console.Write(sb.ToString()); Debug.WriteLine(sw.Elapsed); string bla = "asdlj"; }
public string GetXml(bool validate) { XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en"; var spectrum_licences = getLicences(); XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences)); foreach (XElement e in doc.Root.DescendantsAndSelf()) { if (e.Name.Namespace == "") e.Name = ns + e.Name.LocalName; } var errors = new StringBuilder(); if (validate) { XmlSchemaSet set = new XmlSchemaSet(); var schema = getMainSchema(); set.Add(null, schema); doc.Validate(set, (sender, args) => { errors.AppendLine(args.Message); }); } //return errors.Length > 0 ? errors.ToString() : doc.ToString(); var result = errors.Length > 0 ? "Validation Errors: " + errors.ToString() : getDocumentAsString(doc); return result; }
internal static string FormatMessage (string msg) { StringBuilder sb = new StringBuilder (); bool wasWs = false; foreach (char ch in msg) { if (ch == ' ' || ch == '\t') { if (!wasWs) sb.Append (' '); wasWs = true; continue; } wasWs = false; sb.Append (ch); } var doc = TextDocument.CreateImmutableDocument (sb.ToString()); foreach (var line in doc.Lines) { string text = doc.GetTextAt (line.Offset, line.Length).Trim (); int idx = text.IndexOf (':'); if (text.StartsWith ("*", StringComparison.Ordinal) && idx >= 0 && idx < text.Length - 1) { int offset = line.EndOffsetIncludingDelimiter; msg = text.Substring (idx + 1) + doc.GetTextAt (offset, doc.TextLength - offset); break; } } return msg.TrimStart (' ', '\t'); }
public string ByteArrayToString(byte[] data) { StringBuilder sb = new StringBuilder(); byte[] newdata = new byte[3]; // 2 bytes 3 characters // First, bits with weight 4,8,16,32,64 of byte 1 // Second, bits with weight 32,64,128 of byte 2 plus bits with weight 1,2 from byte 1 // Third, bits with weight 1,2,4,8,16 of byte 2 newdata[0] = (byte)(((int)data[0]& 0x7c)/4); newdata[1] = (byte)((((int)data[0] & 0x03)*8) + (((int)data[1] & 0xe0) / 32)); newdata[2] = (byte)((int)data[1] & 0x1f); for (int i = 0; i < newdata.Length; i++) { if (newdata[i] >= 0x01 && newdata[i] <= 0x1a) sb.Append(((char)((((int)newdata[i])) + 65 - 0x01))); else if (newdata[i] == 0x1b) sb.Append('-'); else if (newdata[i] == 0x00) sb.Append(' '); } return sb.ToString(); }
private string SerializeObject(object obj, int depth) { var type = obj.GetType(); if (!IsSerializeableType(obj) && !(obj is string)) { return null; } StringBuilder stringBuilder = new StringBuilder(); var fieldInfos = type.GetFields(); stringBuilder.Append("{\n"); foreach (var fieldInfo in fieldInfos) { var attributes = fieldInfo.GetCustomAttributes(); if (attributes.OfType<NonSerializedAttribute>().Any()) { continue; } var value = fieldInfo.GetValue(obj); stringBuilder.Append(SerializeString(fieldInfo.Name, depth + 1)); stringBuilder.Append(" : "); if (IsSimpleType(value)) { stringBuilder.Append(SerializeByDepth(value, 0) + "\n"); continue; } stringBuilder.Append(SerializeByDepth(value, depth + 1) + "\n"); } stringBuilder.Append(GetTabs(depth) + "}"); return stringBuilder.ToString(); }
/// <summary> /// Validates a credit card number using the standard Luhn/mod10 validation algorithm. /// </summary> /// <param name="cardNumber">Card number, with or without punctuation</param> /// <returns> /// <c>true</c> if card number appears valid; otherwise, <c>false</c>. /// </returns> public static bool IsCardNumberValid(string cardNumber) { int i; var cleanNumber = new StringBuilder(); for (i = 0; i < cardNumber.Length; i++) if (char.IsDigit(cardNumber, i)) cleanNumber.Append(cardNumber[i]); if (cleanNumber.Length < 13 || cleanNumber.Length > 16) return false; for (i = cleanNumber.Length + 1; i <= 16; i++) cleanNumber.Insert(0, "0"); string number = cleanNumber.ToString(); int total = 0; for (i = 1; i <= 16; i++) { int multiplier = 1 + (i % 2); int digit = int.Parse(number.Substring(i - 1, 1)); int sum = digit * multiplier; if (sum > 9) sum -= 9; total += sum; } return (total % 10 == 0); }
private static void ToCSharpString(Type type, StringBuilder name) { if (type.IsArray) { var elementType = type.GetElementType(); ToCSharpString(elementType, name); name.Append(type.Name.Substring(elementType.Name.Length)); return; } if (type.IsGenericParameter) { //NOTE: this has to go before type.IsNested because nested generic type is also a generic parameter and otherwise we'd have stack overflow name.AppendFormat("·{0}·", type.Name); return; } if (type.IsNested) { ToCSharpString(type.DeclaringType, name); name.Append("."); } if (type.IsGenericType == false) { name.Append(type.Name); return; } name.Append(type.Name.Split('`')[0]); AppendGenericParameters(name, type.GetGenericArguments()); }
public string HtmlAttributeEncode(string s) { if (String.IsNullOrEmpty (s)) return String.Empty; var needEncode = s.Any(c => c == '&' || c == '"' || c == '<' || c == '\''); if (!needEncode) return s; var output = new StringBuilder(); var len = s.Length; for (var i = 0; i < len; i++) switch (s[i]) { case '&': output.Append("&"); break; case '"': output.Append("""); break; case '<': output.Append("<"); break; case '\'': output.Append ("'"); break; default: output.Append(s[i]); break; } return output.ToString(); }
private void copyToolStripMenuItem_Click(object sender, EventArgs e) { DataGridView dataGrid = (DataGridView)this.SourceControl; StringBuilder sb = new StringBuilder(); int firstRowIndex = dataGrid.RowCount; int lastRowIndex = 0; int firstColIndex = dataGrid.ColumnCount; int lastColIndex = 0; for (int i = 0; i < dataGrid.SelectedCells.Count; i++) { if (dataGrid.SelectedCells[i].RowIndex < firstRowIndex) firstRowIndex = dataGrid.SelectedCells[i].RowIndex; if (dataGrid.SelectedCells[i].RowIndex > lastRowIndex) lastRowIndex = dataGrid.SelectedCells[i].RowIndex; if (dataGrid.SelectedCells[i].ColumnIndex < firstColIndex) firstColIndex = dataGrid.SelectedCells[i].ColumnIndex; if (dataGrid.SelectedCells[i].ColumnIndex > lastColIndex) lastColIndex = dataGrid.SelectedCells[i].ColumnIndex; } for (int i = firstRowIndex; i <= lastRowIndex; i++) { for (int j = firstColIndex; j <= lastColIndex; j++) { if (dataGrid[j, i].Selected) { try { sb.Append(dataGrid[j, i].Value.ToString()); } catch (NullReferenceException) { } if (j != lastColIndex) sb.Append("\t"); } } if (i != lastRowIndex) sb.Append("\r\n"); } Clipboard.SetDataObject(sb.ToString(), true); }
private string[] SanitizeArgs(string[] args) { var commands = new List<string>(); var enumerator = args.GetEnumerator(); StringBuilder builder = null; while (enumerator.MoveNext()) { var arg = enumerator.Current as string; if (arg.StartsWith(_token)) { if (builder != null) commands.Add(builder.ToString()); builder = new StringBuilder(); builder.Append(arg); } else { builder.Append($" {arg}"); } } commands.Add(builder.ToString()); return commands.ToArray(); }
/// <summary> /// Read Data Value From the Ini File /// </summary> /// <PARAM name="Section"></PARAM> /// <PARAM name="Key"></PARAM> /// <PARAM name="Path"></PARAM> /// <returns></returns> public string IniReadValue(string Section,string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section,Key,"",temp, 255, this.path); return temp.ToString(); }
public override string ToXML() { StringBuilder sb = new StringBuilder(); sb.Append(base.ToXML()); sb.AppendLine("<tilt>" + tilt + "</tilt>"); return sb.ToString(); }
public IList<IViewAlbumArtistSongTotalVotes> GetMostVotedThisMonth( int page = 0 , int rowCount = 0 ) { DateTime firstDayOfTheMonth; DateTime lastDayOfTheMonth; DateUtils.GetMonth(DateTime.Now , new CultureInfo("pt-BR") , out firstDayOfTheMonth , out lastDayOfTheMonth); StringBuilder builder = new StringBuilder(); builder.AppendFormat(" (battlDate BETWEEN '{0}' AND '{1} 23:59:59')",firstDayOfTheMonth.ToString("yyyy-MM-dd"), lastDayOfTheMonth.ToString("yyyy-MM-dd")); IDataQuery query = new DataQuery(); query.From = "ViewTopSongs"; query.Where = builder.ToString(); if( !String.IsNullOrEmpty(_orderBy) ) { query.OrderBy = _orderBy; } query.Page = page; query.RowCount = rowCount; IList<IViewAlbumArtistSongTotalVotes> result = _repository.Find(query); query.From = "ViewTopSongs"; this.Total = _repository.Count(query); _collection = result; return result; }
public static extern int GetPrivateProfileString(string lpAppName, // points to section name string lpKeyName, // points to key name string lpDefault, // points to default string StringBuilder lpReturnedString, // points to destination buffer int nSize, // size of destination buffer string lpFileName // points to initialization filename );
/// <summary> /// Reads from the stream. /// </summary> /// <param name="timeout">The timeout.</param> /// <returns>Any text read from the stream.</returns> public string Read(TimeSpan timeout) #endif { if (!this.byteStream.Connected || this.internalCancellation.Token.IsCancellationRequested) { return string.Empty; } StringBuilder sb = new StringBuilder(); this.byteStream.ReceiveTimeout = (int)timeout.TotalMilliseconds; DateTime endInitialTimeout = DateTime.Now.Add(timeout); DateTime rollingTimeout = ExtendRollingTimeout(timeout); do { if (this.ParseResponse(sb)) { rollingTimeout = ExtendRollingTimeout(timeout); } } while (!this.internalCancellation.Token.IsCancellationRequested && (this.IsResponsePending || IsWaitForInitialResponse(endInitialTimeout, sb) || #if ASYNC await #endif IsWaitForIncrementalResponse(rollingTimeout))); if (DateTime.Now >= rollingTimeout) { System.Diagnostics.Debug.Print("RollingTimeout exceeded {0}", DateTime.Now.ToString("ss:fff")); } return sb.ToString(); }
public ChunkStream(WebHeaderCollection headers) { _headers = headers; _chunkSize = -1; _chunks = new List<Chunk> (); _saved = new StringBuilder (); }
public static void Check_Instruction_20_CCF() { StringBuilder testProgram = new StringBuilder(); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); // TStatesByMachineCycle = "7 (4,3)" testProgram.AppendLine("LD A,0"); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); // TStatesByMachineCycle = "1 (4)" testProgram.AppendLine("CCF"); TestSystem testSystem = new TestSystem(); testSystem.LoadProgramInMemory(testProgram.ToString()); CPUStateLogger logger = new CPUStateLogger(testSystem.CPU); logger.StartLogging( CPUStateLogger.CPUStateElements.InternalState | CPUStateLogger.CPUStateElements.Registers, new Z80CPU.LifecycleEventType[] { Z80CPU.LifecycleEventType.MachineCycleEnd }); testSystem.ExecuteInstructionCount(4); logger.StopLogging(); if (!logger.CompareWithSavedLog("ALU/ArithmeticGeneralPurpose/Logs/Check_Instruction_20_CCF")) { throw new Exception("Log compare failed"); } }
/// <summary> /// Process the connection request by reading the header information from the HTTP request, and connecting to the tor server /// and dispatching the request to the relevant host. /// </summary> private void GetHeaderData() { try { StringBuilder builder = new StringBuilder(); using (StreamReader reader = new StreamReader(new NetworkStream(socket, false))) { for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { builder.Append(line); builder.Append("\r\n"); if (line.Trim().Length == 0) { break; } } } using (StringReader reader = new StringReader(builder.ToString())) { method = reader.ReadLine(); if (method == null) { throw new InvalidOperationException("The proxy connection did not supply a valid HTTP header"); } headers = new Dictionary <string, string>(); for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { string trimmed = line.Trim(); if (trimmed.Length == 0) { break; } string[] parts = trimmed.Split(new[] { ':' }, 2); if (parts.Length == 1) { continue; } headers[parts[0].Trim()] = parts[1].Trim(); } if (method.StartsWith("POST", StringComparison.CurrentCultureIgnoreCase)) { if (!headers.ContainsKey("Content-Length")) { throw new InvalidOperationException("The proxy connection is a POST method but contains no content length"); } long contentLength = long.Parse(headers["Content-Length"]); using (MemoryStream memory = new MemoryStream()) { long read = 0; byte[] buffer = new byte[512]; while (contentLength > read) { int received = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); if (received <= 0) { throw new InvalidOperationException("The proxy connection was terminated while reading POST data"); } memory.Write(buffer, 0, received); read += received; } post = memory.ToArray(); } } if (method.StartsWith("CONNECT", StringComparison.CurrentCultureIgnoreCase)) { string[] connectTargets = method.Split(' '); if (connectTargets.Length < 3) { throw new InvalidOperationException("The proxy connection supplied a CONNECT command with insufficient parameters"); } http = connectTargets[2]; string connectTarget = connectTargets[1]; string[] connectParams = connectTarget.Split(':'); if (connectParams.Length == 2) { host = connectParams[0]; port = int.Parse(connectParams[1]); } else { host = connectParams[0]; port = 443; } } else { if (!headers.ContainsKey("Host")) { throw new InvalidOperationException("The proxy connection did not supply a connection host"); } string connectTarget = headers["Host"]; string[] connectParams = connectTarget.Split(':'); if (connectParams.Length == 1) { host = connectParams[0]; } else { host = connectParams[0]; port = int.Parse(connectParams[1]); } } } } catch (Exception exception) { throw new TorException("The proxy connection failed to process", exception); } }
protected async Task<string> CallTheDriver<TModel>(ActionContext context, TModel model) { //context.Controller.ViewData.Model = Model; StringBuilder html = new StringBuilder(); StringBuilder header = new StringBuilder(); StringBuilder footer = new StringBuilder(); // use action name if the view name was not provided if (string.IsNullOrEmpty(ViewName)) { ViewName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName; } ViewEngineResult viewResult = GetView(context, ViewName, MasterName); // view not found, throw an exception with searched locations if (viewResult.View == null) { var locations = new StringBuilder(); locations.AppendLine(); foreach (string location in viewResult.SearchedLocations) { locations.AppendLine(location); } throw new InvalidOperationException(string.Format("The view '{0}' or its master was not found, searched locations: {1}", ViewName, locations)); } ITempDataProvider tempDataProvider = context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)) as ITempDataProvider; using (var output = new StringWriter()) { var view = viewResult.View; var viewContext = new ViewContext( context, viewResult.View, new ViewDataDictionary<TModel>( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, new TempDataDictionary(context.HttpContext, tempDataProvider), output, new HtmlHelperOptions()); await view.RenderAsync(viewContext); html = output.GetStringBuilder(); } if (!string.IsNullOrEmpty(HeaderView)) { using (var hw = new StringWriter()) { ViewEngineResult headerViewResult = GetView(context, HeaderView, MasterName, isMainPage: false); if (headerViewResult != null) { var viewContext = new ViewContext( context, headerViewResult.View, new ViewDataDictionary<TModel>( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, new TempDataDictionary(context.HttpContext, tempDataProvider), hw, new HtmlHelperOptions()); await headerViewResult.View.RenderAsync(viewContext); header = hw.GetStringBuilder(); ExtraSwitches += " --header-html header.html"; } } } if (!string.IsNullOrEmpty(FooterView)) { using (var hw = new StringWriter()) { ViewEngineResult footerViewResult = GetView(context, FooterView, MasterName, isMainPage: false); if (footerViewResult != null) { var viewContext = new ViewContext( context, footerViewResult.View, new ViewDataDictionary<TModel>( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, new TempDataDictionary(context.HttpContext, tempDataProvider), hw, new HtmlHelperOptions()); await footerViewResult.View.RenderAsync(viewContext); footer = hw.GetStringBuilder(); ExtraSwitches += " --footer-html footer.html"; } } } // replace href and src attributes with full URLs var apiKey = RotativaHqConfiguration.RotativaHqApiKey; if (apiKey == null) { throw new InvalidOperationException("Apikey not defined."); } var client = new RotativaHqClient(apiKey); var contentDisposition = this.ShowInline ? "inline" : ""; var fileUrl = client.GetPdfUrl(context.HttpContext, GetConvertOptions(), html.ToString(), this.FileName, header.ToString(), footer.ToString(), contentDisposition); return fileUrl; }
private string ParseString() { var s = new StringBuilder(); char c; // ditch opening quote json.Read(); var parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (var i = 0; i < 4; i++) { hex[i] = NextChar; } s.Append((char)Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return(s.ToString()); }
/// <summary> /// Text wrapping functionality. The 'maxWidth' should be in local coordinates (take pixels and divide them by transform's scale). /// </summary> public string WrapText(string text, float maxWidth, int maxLineCount, bool encoding, SymbolStyle symbolStyle) { if (mReplacement != null) { return(mReplacement.WrapText(text, maxWidth, maxLineCount, encoding, symbolStyle)); } // Width of the line in pixels int lineWidth = Mathf.RoundToInt(maxWidth * size); if (lineWidth < 1) { return(text); } StringBuilder sb = new StringBuilder(); int textLength = text.Length; int remainingWidth = lineWidth; int previousChar = 0; int start = 0; int offset = 0; bool lineIsEmpty = true; bool multiline = (maxLineCount != 1); int lineCount = 1; // Run through all characters for (; offset < textLength; ++offset) { char ch = text[offset]; // New line character -- start a new line if (ch == '\n') { if (!multiline || lineCount == maxLineCount) { break; } remainingWidth = lineWidth; // Add the previous word to the final string if (start < offset) { sb.Append(text.Substring(start, offset - start + 1)); } else { sb.Append(ch); } lineIsEmpty = true; ++lineCount; start = offset + 1; previousChar = 0; continue; } // If this marks the end of a word, add it to the final string. if (ch == ' ' && previousChar != ' ' && start < offset) { sb.Append(text.Substring(start, offset - start + 1)); lineIsEmpty = false; start = offset + 1; previousChar = ch; } // When encoded symbols such as [RrGgBb] or [-] are encountered, skip past them if (encoding && ch == '[') { if (offset + 2 < textLength) { if (text[offset + 1] == '-' && text[offset + 2] == ']') { offset += 2; continue; } else if (offset + 7 < textLength && text[offset + 7] == ']') { if (NGUITools.EncodeColor(NGUITools.ParseColor(text, offset + 1)) == text.Substring(offset + 1, 6).ToUpper()) { offset += 7; continue; } } } } // See if there is a symbol matching this text BMSymbol symbol = (encoding && symbolStyle != SymbolStyle.None) ? mFont.MatchSymbol(text, offset, textLength) : null; // Find the glyph for this character BMGlyph glyph = (symbol == null) ? mFont.GetGlyph(ch) : null; // Calculate how wide this symbol or character is going to be int glyphWidth = mSpacingX; if (symbol != null) { glyphWidth += symbol.width; } else if (glyph != null) { glyphWidth += (previousChar != 0) ? glyph.advance + glyph.GetKerning(previousChar) : glyph.advance; } else { continue; } // Remaining width after this glyph gets printed remainingWidth -= glyphWidth; // Doesn't fit? if (remainingWidth < 0) { // Can't start a new line if (lineIsEmpty || !multiline || lineCount == maxLineCount) { // This is the first word on the line -- add it up to the character that fits sb.Append(text.Substring(start, Mathf.Max(0, offset - start))); if (!multiline || lineCount == maxLineCount) { start = offset; break; } EndLine(ref sb); // Start a brand-new line lineIsEmpty = true; ++lineCount; if (ch == ' ') { start = offset + 1; remainingWidth = lineWidth; } else { start = offset; remainingWidth = lineWidth - glyphWidth; } previousChar = 0; } else { // Skip all spaces before the word while (start < textLength && text[start] == ' ') { ++start; } // Revert the position to the beginning of the word and reset the line lineIsEmpty = true; remainingWidth = lineWidth; offset = start - 1; previousChar = 0; if (!multiline || lineCount == maxLineCount) { break; } ++lineCount; EndLine(ref sb); continue; } } else { previousChar = ch; } // Advance the offset past the symbol if (symbol != null) { offset += symbol.length - 1; previousChar = 0; } } if (start < offset) { sb.Append(text.Substring(start, offset - start)); } return(sb.ToString()); }
/// <summary> /// /// </summary> /// <returns></returns> public static Cls_Apl_Principal_Negocio Consultar_Venta(Cls_Apl_Principal_Negocio Venta) { Conexion.Iniciar_Helper(); Conexion.HelperGenerico.Conexion_y_Apertura(); StringBuilder Mi_Sql = new StringBuilder(); try { Mi_Sql.Append("SELECT V.*, P.*, "); Mi_Sql.Append("(SELECT A.Vigencia_Inicio FROM " + Ope_Accesos.Tabla_Ope_Accesos); Mi_Sql.Append(" A WHERE A." + Ope_Accesos.Campo_No_Venta); Mi_Sql.Append(" = V." + Ope_Ventas.Campo_No_Venta + " LIMIT 1) Vigencia_Inicio "); Mi_Sql.Append("FROM " + Ope_Ventas.Tabla_Ope_Ventas + " V "); Mi_Sql.Append("JOIN " + Ope_Pagos.Tabla_Ope_Pagos + " P "); Mi_Sql.Append("ON V." + Ope_Ventas.Campo_No_Venta + " = P." + Ope_Pagos.Campo_No_Venta); Mi_Sql.Append(" WHERE V." + Ope_Ventas.Campo_No_Venta + " = '" + Venta.P_No_Venta + "'"); var Vnt = Conexion.HelperGenerico.Obtener_Data_Reader(Mi_Sql.ToString()); while (Vnt.Read()) { Venta.P_Subtotal = Convert.ToDecimal(Vnt[Ope_Ventas.Campo_Subtotal]); Venta.P_Total = Vnt[Ope_Ventas.Campo_Total].ToString(); Venta.P_Estatus = Vnt[Ope_Ventas.Campo_Estatus].ToString(); Venta.P_Email = Vnt[Ope_Ventas.Campo_Correo_Electronico].ToString(); Venta.P_Telefono = Vnt[Ope_Ventas.Campo_Telefono].ToString(); Venta.P_Numero_Tarjeta = Vnt[Ope_Pagos.Campo_Numero_Tarjeta_Banco].ToString(); Venta.P_Nombre = Vnt[Ope_Pagos.Campo_Titular_Tarjeta].ToString(); Venta.P_Domicilio = Vnt[Ope_Pagos.Campo_Domicilio].ToString(); Venta.P_Estado = Vnt[Ope_Pagos.Campo_Estado].ToString(); Venta.P_Codigo_Postal = Vnt[Ope_Pagos.Campo_Codigo_Postal].ToString(); Venta.P_Ciudad = Vnt[Ope_Pagos.Campo_Ciudad].ToString(); Venta.P_Fecha_Inicio_Vigencia = DateTime.Parse( Vnt[Ope_Accesos.Campo_Vigencia_Inicio].ToString()); } Vnt.Close(); /*Se realiza la consulta para generar los accesos*/ Mi_Sql.Clear(); Mi_Sql.Append("SELECT a.Producto_Id PRODUCTO_ID, count(*) CANTIDAD, p.Costo COSTO, "); Mi_Sql.Append("sum(p.Costo) TOTAL, p.Tipo TIPO, p.Descripcion DESCRIPCION, "); Mi_Sql.Append("p.Ruta_Imagen RUTA_IMAGEN,p.Codigo CODIGO, "); Mi_Sql.Append("(select group_concat(ac.No_Acceso separator ', ') "); Mi_Sql.Append("from ope_accesos ac where ac.No_Venta = a.No_Venta "); Mi_Sql.Append("and ac.Producto_Id = a.Producto_Id group by ac.Producto_Id) ACCESOS "); Mi_Sql.Append("from ope_accesos a "); Mi_Sql.Append("join cat_productos p on p.Producto_Id = a.Producto_ID "); Mi_Sql.Append("where No_Venta = '" + Venta.P_No_Venta + "' "); Mi_Sql.Append("group by Producto_Id;"); Venta.P_Dt_Productos = Conexion.HelperGenerico.Obtener_Data_Table(Mi_Sql.ToString()); return Venta; } catch (Exception e) { throw e; } finally { Conexion.HelperGenerico.Cerrar_Conexion(); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((Math.Sqrt(42) >= 42)) { {} } else { StringBuilder escape = new StringBuilder(); for (int i = 0; i < tainted_2.Length; ++i) { char current = tainted_2[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } tainted_3 = escape.ToString(); } //flaw string query = string.Format("//user[@name='{0}']", tainted_3); string filename = "file.xml"; XmlDocument document = new XmlDocument( ); document.Load(filename); XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; XmlNode node = document.SelectSingleNode(query); node.WriteTo(writer); writer.Close( ); }
private Day[] loadCalendar(int year, int month) { var dict = new Day[34]; bool isBold = false; bool isItalic = false; bool isStrike = false; var filename = "data\\" + year + LZ(month) + ".xml"; if (File.Exists(filename)) { bool inText = false; StringBuilder text = new StringBuilder(); int day = 0; string[] lines = File.ReadAllLines(filename); foreach (var line in lines) { var s = line.Trim(); if (s.StartsWith("<Day DayValue=\"")) { isBold = s.Contains("bold=\"True\""); isItalic = s.Contains("italic=\"True\""); isStrike = s.Contains("strike=\"True\""); s = s.Substring(15); int p = s.IndexOf('"'); if (p != -1) s = s.Substring(0, p); day = Convert.ToInt32(s); } else if (s.StartsWith("<Text>")) { s = s.Substring(6); if (s.StartsWith("-")) s = s.Substring(1); if (s.EndsWith("</Text>")) { var dd = new Day(xmldecode(s.Substring(0, s.Length - 7))); dd.isBold = isBold; dd.isItalic = isItalic; dd.isStrike = isStrike; dict[day] = dd; } else { inText = true; text.Append(s); } } else if (s.EndsWith("</Text>")) { inText = false; text.Append("\n"); text.Append(s.Substring(0, s.Length - 7)); var dd = new Day(xmldecode(text.ToString())); dd.isBold = isBold; dd.isItalic = isItalic; dd.isStrike = isStrike; dict[day] = dd; text.Clear(); } else if (inText) { text.Append("\n"); text.Append(s); } } } return dict; }
/// <include file='doc\ThreadExceptionDialog.uex' path='docs/doc[@for="ThreadExceptionDialog.ThreadExceptionDialog"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.ThreadExceptionDialog'/> class. /// /// </para> /// </devdoc> public ThreadExceptionDialog(Exception t) { string messageRes; string messageText; Button[] buttons; bool detailAnchor = false; if (t is WarningException) { WarningException w = (WarningException)t; messageRes = SR.ExDlgWarningText; messageText = w.Message; if (w.HelpUrl == null) { buttons = new Button[] {continueButton}; } else { buttons = new Button[] {continueButton, helpButton}; } } else { messageText = t.Message; detailAnchor = true; if (Application.AllowQuit) { if (t is SecurityException) { messageRes = "ExDlgSecurityErrorText"; } else { messageRes = "ExDlgErrorText"; } buttons = new Button[] {detailsButton, continueButton, quitButton}; } else { if (t is SecurityException) { messageRes = "ExDlgSecurityContinueErrorText"; } else { messageRes = "ExDlgContinueErrorText"; } buttons = new Button[] {detailsButton, continueButton}; } } if (messageText.Length == 0) { messageText = t.GetType().Name; } if (t is SecurityException) { messageText = SR.GetString(messageRes, t.GetType().Name, Trim(messageText)); } else { messageText = SR.GetString(messageRes, Trim(messageText)); } StringBuilder detailsTextBuilder = new StringBuilder(); string newline = "\r\n"; string separator = SR.GetString(SR.ExDlgMsgSeperator); string sectionseparator = SR.GetString(SR.ExDlgMsgSectionSeperator); if (Application.CustomThreadExceptionHandlerAttached) { detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgHeaderNonSwitchable)); } else { detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgHeaderSwitchable)); } detailsTextBuilder.Append(string.Format(sectionseparator, SR.GetString(SR.ExDlgMsgExceptionSection))); detailsTextBuilder.Append(t.ToString()); detailsTextBuilder.Append(newline); detailsTextBuilder.Append(newline); detailsTextBuilder.Append(string.Format(sectionseparator, SR.GetString(SR.ExDlgMsgLoadedAssembliesSection))); new FileIOPermission(PermissionState.Unrestricted).Assert(); try { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { AssemblyName name = asm.GetName(); string fileVer = SR.GetString(SR.NotAvailable); try { // bug 113573 -- if there's a path with an escaped value in it // like c:\temp\foo%2fbar, the AssemblyName call will unescape it to // c:\temp\foo\bar, which is wrong, and this will fail. It doesn't look like the // assembly name class handles this properly -- even the "CodeBase" property is un-escaped // so we can't circumvent this. // if (name.EscapedCodeBase != null && name.EscapedCodeBase.Length > 0) { Uri codeBase = new Uri(name.EscapedCodeBase); if (codeBase.Scheme == "file") { fileVer = FileVersionInfo.GetVersionInfo(NativeMethods.GetLocalPath(name.EscapedCodeBase)).FileVersion; } } } catch(System.IO.FileNotFoundException){ } detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgLoadedAssembliesEntry, name.Name, name.Version, fileVer, name.EscapedCodeBase)); detailsTextBuilder.Append(separator); } } finally { CodeAccessPermission.RevertAssert(); } detailsTextBuilder.Append(string.Format(sectionseparator, SR.GetString(SR.ExDlgMsgJITDebuggingSection))); if (Application.CustomThreadExceptionHandlerAttached) { detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgFooterNonSwitchable)); } else { detailsTextBuilder.Append(SR.GetString(SR.ExDlgMsgFooterSwitchable)); } detailsTextBuilder.Append(newline); detailsTextBuilder.Append(newline); string detailsText = detailsTextBuilder.ToString(); Graphics g = message.CreateGraphicsInternal(); Size textSize = Size.Ceiling(g.MeasureString(messageText, Font, MAXWIDTH - 80)); g.Dispose(); if (textSize.Width < 180) textSize.Width = 180; if (textSize.Height > MAXHEIGHT) textSize.Height = MAXHEIGHT; int width = textSize.Width + 80; int buttonTop = Math.Max(textSize.Height, 40) + 26; // SECREVIEW : We must get a hold of the parent to get at it's text // : to make this dialog look like the parent. // IntSecurity.GetParent.Assert(); try { Form activeForm = Form.ActiveForm; if (activeForm == null || activeForm.Text.Length == 0) { Text = SR.GetString(SR.ExDlgCaption); } else { Text = SR.GetString(SR.ExDlgCaption2, activeForm.Text); } } finally { CodeAccessPermission.RevertAssert(); } AcceptButton = continueButton; CancelButton = continueButton; FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; MinimizeBox = false; StartPosition = FormStartPosition.CenterScreen; Icon = null; ClientSize = new Size(width, buttonTop + 31); TopMost = true; pictureBox.Location = new Point(0, 0); pictureBox.Size = new Size(64, 64); pictureBox.SizeMode = PictureBoxSizeMode.CenterImage; if (t is SecurityException) { pictureBox.Image = SystemIcons.Information.ToBitmap(); } else { pictureBox.Image = SystemIcons.Error.ToBitmap(); } Controls.Add(pictureBox); message.SetBounds(64, 8 + (40 - Math.Min(textSize.Height, 40)) / 2, textSize.Width, textSize.Height); message.Text = messageText; Controls.Add(message); continueButton.Text = SR.GetString(SR.ExDlgContinue); continueButton.FlatStyle = FlatStyle.Standard; continueButton.DialogResult = DialogResult.Cancel; quitButton.Text = SR.GetString(SR.ExDlgQuit); quitButton.FlatStyle = FlatStyle.Standard; quitButton.DialogResult = DialogResult.Abort; helpButton.Text = SR.GetString(SR.ExDlgHelp); helpButton.FlatStyle = FlatStyle.Standard; helpButton.DialogResult = DialogResult.Yes; detailsButton.Text = SR.GetString(SR.ExDlgShowDetails); detailsButton.FlatStyle = FlatStyle.Standard; detailsButton.Click += new EventHandler(DetailsClick); Button b = null; int startIndex = 0; if (detailAnchor) { b = detailsButton; expandImage = new Bitmap(this.GetType(), "down.bmp"); expandImage.MakeTransparent(); collapseImage = new Bitmap(this.GetType(), "up.bmp"); collapseImage.MakeTransparent(); b.SetBounds( 8, buttonTop, 100, 23 ); b.Image = expandImage; b.ImageAlign = ContentAlignment.MiddleLeft; Controls.Add(b); startIndex = 1; } int buttonLeft = (width - 8 - ((buttons.Length - startIndex) * 105 - 5)); for (int i = startIndex; i < buttons.Length; i++) { b = buttons[i]; b.SetBounds(buttonLeft, buttonTop, 100, 23); Controls.Add(b); buttonLeft += 105; } details.Text = detailsText; details.ScrollBars = ScrollBars.Both; details.Multiline = true; details.ReadOnly = true; details.WordWrap = false; details.TabStop = false; details.AcceptsReturn = false; details.SetBounds(8, buttonTop + 31, width - 16,154); Controls.Add(details); }
/// <summary> /// Gets the position of a member in this project content (not a referenced one). /// </summary> /// <param name="fullMemberName">The member name in Reflection syntax (always case sensitive, ` for generics). /// member name = [ExplicitInterface .] MemberName [`TypeArgumentCount] [(Parameters)]</param> public static IMember GetMemberByReflectionName(IClass curClass, string fullMemberName) { if (curClass == null) { return(null); } int pos = fullMemberName.IndexOf('('); if (pos > 0) { // is method call int colonPos = fullMemberName.LastIndexOf(':'); if (colonPos > 0) { fullMemberName = fullMemberName.Substring(0, colonPos); } string interfaceName = null; string memberName = fullMemberName.Substring(0, pos); int pos2 = memberName.LastIndexOf('.'); if (pos2 > 0) { interfaceName = memberName.Substring(0, pos2); memberName = memberName.Substring(pos2 + 1); } // put class name in front of full member name because we'll compare against it later fullMemberName = curClass.DotNetName + "." + fullMemberName; IMethod firstMethod = null; foreach (IMethod m in curClass.Methods) { if (m.Name == memberName) { if (firstMethod == null) { firstMethod = m; } StringBuilder dotnetName = new StringBuilder(m.DotNetName); dotnetName.Append('('); for (int i = 0; i < m.Parameters.Count; i++) { if (i > 0) { dotnetName.Append(','); } if (m.Parameters[i].ReturnType != null) { dotnetName.Append(m.Parameters[i].ReturnType.DotNetName); } } dotnetName.Append(')'); if (dotnetName.ToString() == fullMemberName) { return(m); } } } return(firstMethod); } else { string interfaceName = null; string memberName = fullMemberName; pos = memberName.LastIndexOf('.'); if (pos > 0) { interfaceName = memberName.Substring(0, pos); memberName = memberName.Substring(pos + 1); } // get first method with that name, but prefer method without parameters IMethod firstMethod = null; foreach (IMethod m in curClass.Methods) { if (m.Name == memberName) { if (firstMethod == null || m.Parameters.Count == 0) { firstMethod = m; } } } if (firstMethod != null) { return(firstMethod); } return(curClass.SearchMember(memberName, LanguageProperties.CSharp)); } }
private static extern int GetFinalPathNameByHandle(SafeKernelObjectHandle hFile, StringBuilder lpszFilePath, int cchFilePath, FinalPathNameFlags dwFlags);
/// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LoanContractUnderwriterSummary {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Appraisal: ").Append(Appraisal).Append("\n"); sb.Append(" AppraisalCompletedDate: ").Append(AppraisalCompletedDate).Append("\n"); sb.Append(" AppraisalExpiredDate: ").Append(AppraisalExpiredDate).Append("\n"); sb.Append(" AppraisalOrderedDate: ").Append(AppraisalOrderedDate).Append("\n"); sb.Append(" AppraisalType: ").Append(AppraisalType).Append("\n"); sb.Append(" ApprovalExpiredDate: ").Append(ApprovalExpiredDate).Append("\n"); sb.Append(" ApprovedBy: ").Append(ApprovedBy).Append("\n"); sb.Append(" ApprovedDate: ").Append(ApprovedDate).Append("\n"); sb.Append(" AusNumber: ").Append(AusNumber).Append("\n"); sb.Append(" AusRunDate: ").Append(AusRunDate).Append("\n"); sb.Append(" AusSource: ").Append(AusSource).Append("\n"); sb.Append(" BenefitRequiredIndicator: ").Append(BenefitRequiredIndicator).Append("\n"); sb.Append(" ClearToCloseDate: ").Append(ClearToCloseDate).Append("\n"); sb.Append(" Concerns: ").Append(Concerns).Append("\n"); sb.Append(" Conditions: ").Append(Conditions).Append("\n"); sb.Append(" Credit: ").Append(Credit).Append("\n"); sb.Append(" CreditApprovalDate: ").Append(CreditApprovalDate).Append("\n"); sb.Append(" DeniedBy: ").Append(DeniedBy).Append("\n"); sb.Append(" DeniedDate: ").Append(DeniedDate).Append("\n"); sb.Append(" DifferentApprovalExpiredDate: ").Append(DifferentApprovalExpiredDate).Append("\n"); sb.Append(" DifferentApprovedBy: ").Append(DifferentApprovedBy).Append("\n"); sb.Append(" DifferentApprovedDate: ").Append(DifferentApprovedDate).Append("\n"); sb.Append(" Exceptions: ").Append(Exceptions).Append("\n"); sb.Append(" ExceptionSignOffBy: ").Append(ExceptionSignOffBy).Append("\n"); sb.Append(" ExceptionSignOffDate: ").Append(ExceptionSignOffDate).Append("\n"); sb.Append(" MaxRate: ").Append(MaxRate).Append("\n"); sb.Append(" MiOrderedDate: ").Append(MiOrderedDate).Append("\n"); sb.Append(" MiReceivedDate: ").Append(MiReceivedDate).Append("\n"); sb.Append(" ModifiedLoanAmount: ").Append(ModifiedLoanAmount).Append("\n"); sb.Append(" ModifiedLoanRate: ").Append(ModifiedLoanRate).Append("\n"); sb.Append(" ModifiedLoanTerm: ").Append(ModifiedLoanTerm).Append("\n"); sb.Append(" ModifiedLtv: ").Append(ModifiedLtv).Append("\n"); sb.Append(" ModifiedMonthlyPayment: ").Append(ModifiedMonthlyPayment).Append("\n"); sb.Append(" OriginalAppraiser: ").Append(OriginalAppraiser).Append("\n"); sb.Append(" OriginalAppraisersValue: ").Append(OriginalAppraisersValue).Append("\n"); sb.Append(" ResubmittedDate: ").Append(ResubmittedDate).Append("\n"); sb.Append(" ReviewAppraiser: ").Append(ReviewAppraiser).Append("\n"); sb.Append(" ReviewCompletedDate: ").Append(ReviewCompletedDate).Append("\n"); sb.Append(" ReviewRequestedDate: ").Append(ReviewRequestedDate).Append("\n"); sb.Append(" ReviewType: ").Append(ReviewType).Append("\n"); sb.Append(" ReviewValue: ").Append(ReviewValue).Append("\n"); sb.Append(" SentToDate: ").Append(SentToDate).Append("\n"); sb.Append(" SignOffBy: ").Append(SignOffBy).Append("\n"); sb.Append(" SignOffDate: ").Append(SignOffDate).Append("\n"); sb.Append(" Strengths: ").Append(Strengths).Append("\n"); sb.Append(" SubmittedDate: ").Append(SubmittedDate).Append("\n"); sb.Append(" SupervisoryAppraiserLicenseNumber: ").Append(SupervisoryAppraiserLicenseNumber).Append("\n"); sb.Append(" SuspendedBy: ").Append(SuspendedBy).Append("\n"); sb.Append(" SuspendedDate: ").Append(SuspendedDate).Append("\n"); sb.Append(" SuspendedReasons: ").Append(SuspendedReasons).Append("\n"); sb.Append(" IsAgencyWithAgreement: ").Append(IsAgencyWithAgreement).Append("\n"); sb.Append(" IsAgencyWaiver: ").Append(IsAgencyWaiver).Append("\n"); sb.Append(" IsAgencyManually: ").Append(IsAgencyManually).Append("\n"); sb.Append("}\n"); return(sb.ToString()); }
private bool GenerateOutreachCallReportCsv(IEnumerable <HourlyOutreachCallReportModel> modelData, string csvFilePath) { var csvStringBuilder = new StringBuilder(); var members = (typeof(HourlyOutreachCallReportModel)).GetMembers(); var header = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <CallCenterNotes>)) { continue; } } else { continue; } string propertyName = memberInfo.Name; bool isHidden = false; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is DisplayNameAttribute) { propertyName = (attribute as DisplayNameAttribute).DisplayName; } } } if (isHidden) { continue; } header.Add(propertyName); } header.Add("Disposition Notes"); csvStringBuilder.Append(string.Join(",", header.ToArray()) + Environment.NewLine); var sanitizer = new CSVSanitizer(); foreach (var model in modelData) { var values = new List <string>(); foreach (var memberInfo in members) { if (memberInfo.MemberType != MemberTypes.Property) { continue; } var propInfo = (memberInfo as PropertyInfo); if (propInfo != null) { if (propInfo.PropertyType == typeof(FeedbackMessageModel) || propInfo.PropertyType == typeof(IEnumerable <CallCenterNotes>)) { continue; } } else { continue; } bool isHidden = false; FormatAttribute formatter = null; var attributes = propInfo.GetCustomAttributes(false); if (!attributes.IsNullOrEmpty()) { foreach (var attribute in attributes) { if (attribute is HiddenAttribute) { isHidden = true; break; } if (attribute is FormatAttribute) { formatter = (FormatAttribute)attribute; } } } if (isHidden) { continue; } var obj = propInfo.GetValue(model, null); if (obj == null) { values.Add(string.Empty); } else if (formatter != null) { values.Add(formatter.ToString(obj)); } else { values.Add(sanitizer.EscapeString(obj.ToString())); } } if (model.Notes != null && model.Notes.Count() > 0) { var notesString = model.Notes.Aggregate("", (current, note) => current + ("[ " + note.DateCreated.ToShortDateString() + " ] - Notes: " + note.Notes + "\n")); values.Add(sanitizer.EscapeString(notesString)); } else { values.Add("N/A"); } csvStringBuilder.Append(string.Join(",", values.ToArray()) + Environment.NewLine); } var request = new GenericReportRequest { CsvFilePath = csvFilePath, Model = csvStringBuilder.ToString() }; var isGenerated = _baseReportService.GetResponse(request); return(isGenerated); }
public void SendMailPreBookOrder(int OrderID, int CustomerId, string TemplatePath, string Subject, bool SentToCustomer = false) { StringBuilder sbMailTemplate = new StringBuilder(); sbMailTemplate.Append(System.IO.File.ReadAllText(TemplatePath)); OrderInfoViewModel objOInfo = OrderInfo(OrderID); List<string> lstOfEmailIDs = new List<string>(); if (SentToCustomer && objOInfo != null && objOInfo.UserDetail != null) { lstOfEmailIDs.Add(objOInfo.UserDetail.emailId); } else { lstOfEmailIDs.Add(ConfigurationManager.AppSettings["Email_ID"].ToString()); lstOfEmailIDs.Add(ConfigurationManager.AppSettings["CCemail"].ToString()); } if (objOInfo != null && objOInfo.BillingAddress != null) { List<string> objLst = objOInfo.OrderItemDetail.Select(x => x.Stock).ToList(); string LotNos = "LOTNO~" + string.Join(",", objLst); DataTable dt = this.objStockDetailsService.GetDataForExcelExport(LotNos, false, CustomerId); if (dt.Columns.Count > 0) { dt.Columns.Remove("Sizes"); dt.Columns.Remove("CertificateNo"); dt.Columns.Remove("Reportdate"); dt.Columns.Remove("EyeClean"); dt.Columns.Remove("Shade"); dt.Columns.Remove("TableBlack"); dt.Columns.Remove("SideBlack"); dt.Columns.Remove("Milky"); dt.Columns.Remove("CuletSize"); dt.Columns.Remove("OpensName"); dt.Columns.Remove("GroupName"); dt.Columns.Remove("MemberComments"); dt.Columns.Remove("refdata"); dt.Columns.Remove("V360"); dt.Columns.Remove("Video"); if (SentToCustomer == true) { dt.Columns.Remove("SalesLocation"); } } DataTable dtOrderCharges = objOInfo.ConvertOrderChangesInDatetable(); string htmlTableForOrderDetail = CommonFunction.ConvertDataTableToHTML(dt, false, true); string htmlTableForOrderChargesDetail = CommonFunction.ConvertDataTableToHTML(dtOrderCharges, false, true); sbMailTemplate = sbMailTemplate.Replace("${CustomerName}", objOInfo.BillingAddress.firstName + " " + objOInfo.BillingAddress.lastName); sbMailTemplate = sbMailTemplate.Replace("${OrderNo}", OrderID.ToString()); sbMailTemplate = sbMailTemplate.Replace("${TABLEDATA}", htmlTableForOrderDetail); sbMailTemplate = sbMailTemplate.Replace("${TABLEDATAFORCHARGES}", htmlTableForOrderChargesDetail); sbMailTemplate = sbMailTemplate.Replace("${CompanyName}", objOInfo.BillingAddress.companyName); sbMailTemplate = sbMailTemplate.Replace("${Address}", objOInfo.BillingAddress.address01 + " " + objOInfo.BillingAddress.address02); sbMailTemplate = sbMailTemplate.Replace("${CountryName}", objOInfo.BillingAddress.countryName); sbMailTemplate = sbMailTemplate.Replace("${phoneCode01}", objOInfo.UserDetail.phoneCode01); sbMailTemplate = sbMailTemplate.Replace("${phone01}", objOInfo.UserDetail.phone01); sbMailTemplate = sbMailTemplate.Replace("${emailId}", objOInfo.UserDetail.emailId); sbMailTemplate = sbMailTemplate.Replace("${bankName}", objOInfo.UserDetail.bankName); sbMailTemplate = sbMailTemplate.Replace("${branchName}", objOInfo.UserDetail.branchName); sbMailTemplate = sbMailTemplate.Replace("${branchAddress}", objOInfo.UserDetail.branchAddress); sbMailTemplate = sbMailTemplate.Replace("${accNumber}", objOInfo.UserDetail.accNumber); sbMailTemplate = sbMailTemplate.Replace("${swiftCode}", objOInfo.UserDetail.swiftCode); if (this.objMU == null) { this.objMU = new MailUtility(); } objMU.SendMail(lstOfEmailIDs, Subject, true, sbMailTemplate.ToString()); } }
protected void bindData() { StringBuilder html_Header = new StringBuilder(); StringBuilder html_Header1 = new StringBuilder(); StringBuilder html_Header2 = new StringBuilder(); StringBuilder html_Header3 = new StringBuilder(); StringBuilder html_Header4 = new StringBuilder(); try { string inco_terms = string.Empty; string isdata = string.Empty; DataTable dt = (DataTable)ActionController.ExecuteAction("", "Car_Expense_Approval.aspx", "getpkcarexpns", ref isdata, txtProcessID.Text, txtInstanceID.Text); isdata = ""; DataSet ds = (DataSet)ActionController.ExecuteAction("", "Car_Expense_Approval.aspx", "getcarexpnsdetails", ref isdata, dt.Rows[0]["PK_CAR_EXPNS_ID"].ToString()); if (ds != null) { if (ds.Tables[0].Rows.Count > 0) { html_Header.Append("<table class='table table-bordered' id='tblfuel' width='100%'>"); html_Header.Append("<thead><tr><th>#</th><th style='text-align:center'>Date</th><th style='text-align:center'>Perticular</th><th style='text-align:center'>Litre</th><th style='text-align:center'>Amount</th></tr></thead>"); html_Header.Append("<tbody>"); if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { html_Header.Append("<tr><td>" + (i + 1) + "</td><td style='text-align:center'>" + ds.Tables[0].Rows[i]["FUEL_DATE"] + "<input type='hidden' id='txtfueldate" + (i + 1) + "' runat='server' Value='" + ds.Tables[0].Rows[i]["FUEL_DATE"] + "' /></td><td style='text-align:center'>" + ds.Tables[0].Rows[i]["PETROL_PUMP"] + "</td><td style='text-align:center'>" + ds.Tables[0].Rows[i]["FUEL_LITRE"] + "</td><td style='text-align:right'>" + ds.Tables[0].Rows[i]["AMOUNT"] + "<input type='hidden' id='txtfuelamount" + (i + 1) + "' runat='server' Value='" + ds.Tables[0].Rows[i]["AMOUNT"] + "' /></td></tr>"); } } html_Header.Append("</tbody></table>"); divfuel.InnerHtml = html_Header.ToString(); } if (ds.Tables[1].Rows.Count > 0) { html_Header1.Append("<table class='table table-bordered' id='tblmaintenance' width='100%'>"); html_Header1.Append("<thead><tr><th>#</th><th style='text-align:center'>Date</th><th style='text-align:center'>Vehical No.</th><th style='text-align:center'>Date Of Purchase</th><th style='text-align:center'>Amount</th></tr> </thead>"); html_Header1.Append("<tbody>"); if (ds.Tables[1].Rows.Count > 0) { for (int j = 0; j < ds.Tables[1].Rows.Count; j++) { html_Header1.Append("<tr><td>" + (j + 1) + "</td><td style='text-align:center'>" + ds.Tables[1].Rows[j]["MAINTAINCE_DATE"] + "<input type='hidden' id='txtmaintenancedate" + (j + 1) + "' runat='server' Value='" + ds.Tables[1].Rows[j]["MAINTAINCE_DATE"] + "' /></td><td style='text-align:center'>" + ds.Tables[1].Rows[j]["VEHICLE_NO"] + "</td><td style='text-align:center'>" + ds.Tables[1].Rows[j]["DATE_OF_PURCHASE"] + "</td><td style='text-align:right'>" + ds.Tables[1].Rows[j]["AMOUNT"] + "<input type='hidden' id='txtmaintenanceamount" + (j + 1) + "' runat='server' Value='" + ds.Tables[1].Rows[j]["AMOUNT"] + "' /></td></tr>"); } } html_Header1.Append("</tbody></table>"); divmaintenance.InnerHtml = html_Header1.ToString(); } if (ds.Tables[2].Rows.Count > 0) { html_Header2.Append("<table class='table table-bordered' id='tbldriver' width='100%'>"); html_Header2.Append("<thead><tr><th>#</th><th style='text-align:center'>Type</th><th style='text-align:center'>Date</th><th style='text-align:center'>Amount</th></tr></thead>"); html_Header2.Append("<tbody>"); if (ds.Tables[2].Rows.Count > 0) { for (int k = 0; k < ds.Tables[2].Rows.Count; k++) { html_Header2.Append("<tr><td>" + (k + 1) + "</td><td style='text-align:center'>" + ds.Tables[2].Rows[k]["DRIVER_TYPE"] + "</td><td style='text-align:center'>" + ds.Tables[2].Rows[k]["DATE"] + "<input type='hidden' id='txtdriverdate" + (k + 1) + "' runat='server' Value='" + ds.Tables[2].Rows[k]["DATE"] + "' /></td><td style='text-align:right'>" + ds.Tables[2].Rows[k]["AMOUNT"] + "<input type='hidden' id='txtdriveramount" + (k + 1) + "' runat='server' Value='" + ds.Tables[2].Rows[k]["AMOUNT"] + "' /></td></tr>"); } } html_Header2.Append("</tbody></table>"); div_driver.InnerHtml = html_Header2.ToString(); } if (ds.Tables[3].Rows.Count > 0) { html_Header4.Append("<table class='table table-bordered' id='tbltyre' width='100%'>"); html_Header4.Append("<thead><tr><th>#</th><th style='text-align:center'>Type</th><th style='text-align:center'>Date</th><th style='text-align:center'>Amount</th></tr></thead>"); html_Header4.Append("<tbody>"); if (ds.Tables[3].Rows.Count > 0) { for (int k = 0; k < ds.Tables[3].Rows.Count; k++) { html_Header4.Append("<tr><td>" + (k + 1) + "</td><td style='text-align:center'>" + ds.Tables[3].Rows[k]["TYRE_BATTERY"] + "</td><td style='text-align:center'>" + ds.Tables[3].Rows[k]["TYRE_BATT_DATE"] + "<input type='hidden' id='txtdate" + (k + 1) + "' runat='server' Value='" + ds.Tables[3].Rows[k]["TYRE_BATT_DATE"] + "' /></td><td style='text-align:right'>" + ds.Tables[3].Rows[k]["AMOUNT"] + "<input type='hidden' id='txtamount" + (k + 1) + "' runat='server' Value='" + ds.Tables[3].Rows[k]["AMOUNT"] + "' /></td></tr>"); } } html_Header4.Append("</tbody></table>"); dv_tyre.InnerHtml = html_Header4.ToString(); } } /***********************************************************************************Remark********************************************************************************************************************/ //html_Header3.Append("<div class='col-md-6' style='margin-top:0.3%'><div class='panel panel-grey'><div class='panel-heading'><h4 class='panel-title'>Remarks</h4></div><div class='panel-body'>"); //html_Header3.Append("<table class='table table-bordered' id='tblremark' width='100%'>"); //html_Header3.Append("<tbody>"); //html_Header3.Append("<tr><td style='text-align:center'><textarea name='txtRemark' cols='45' class='form-control' ID='txtRemark'></textarea></td></tr>"); //html_Header3.Append("</tbody>"); //html_Header3.Append("</table></div></div></div>"); /*******************************************************************************************************************************************************************************************************/ //div_doc_remark.InnerHtml = Convert.ToString(html_Header3); } catch (Exception Exc) { Logger.WriteEventLog(false, Exc); } }
public override string ToString() { var sb = new StringBuilder(); sb.Append("class LineCapStyle {\n"); sb.Append("}\n"); return sb.ToString(); }
extern static bool GetVolumeInformation(string vol, StringBuilder name, int nameSize, out uint serialNum, out uint maxNameLen, out uint flags, StringBuilder fileSysName, int fileSysNameSize);
/// <summary> /// 初始JS /// </summary> void SchedulerInitJS() { string strResourceIDList = ucResourceIDList; string strCultureCode = ucUICultureCode; string strSchedSysPath = Util._SysPath + "/dhtmlxScheduler/"; Util.setJS(Util.getFixURL(strSchedSysPath + "dhtmlxscheduler.js"), "dhtmlx_JS"); Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_active_links.js"), "dhtmlx_actlink"); Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_recurring.js"), "dhtmlx_recurring"); Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_minical.js"), "dhtmlx_minical"); if (ucIsToolTip) { Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_tooltip.js"), "dhtmlx_tooltip"); } if (ucIsYearView) { Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_year_view.js"), "dhtmlx_yearview"); } Util.setCSS(Util.getFixURL(strSchedSysPath + "dhtmlxscheduler.css")); //判斷顯示語系 switch (strCultureCode) { case "zh-CHT": Util.setJS(Util.getFixURL(strSchedSysPath + "locale/locale_tw.js"), "dhtmlx_Loc01"); Util.setJS(Util.getFixURL(strSchedSysPath + "locale/recurring/locale_recurring_tw.js"), "dhtmlx_Loc02"); break; case "zh-CHS": case "zh-Hans": Util.setJS(Util.getFixURL(strSchedSysPath + "locale/locale_cn.js"), "dhtmlx_Loc01"); Util.setJS(Util.getFixURL(strSchedSysPath + "locale/recurring/locale_recurring_cn.js"), "dhtmlx_Loc02"); break; default: break; } string strDataURL = string.Format("{0}?DBName={1}&TableName={2}&IsReadOnly={3}&ResourceIDList={4}&NewColor={5}&NewTextColor={6}", Util.getFixURL(strSchedSysPath + "SchedulerHandler.ashx"), ucDBName, ucTableName, (ucIsReadOnly == true) ? "Y" : "N", strResourceIDList, ucNewEventColor, ucNewEventTextColor); Util.setJSContent(""); StringBuilder sb = new StringBuilder(); sb.Append("\nfunction init() { \n" + " scheduler.config.xml_date = '%Y-%m-%d %H:%i'; \n"); sb.AppendFormat(" scheduler.config.first_hour = {0}; \n", ucFirstHour); sb.AppendFormat(" scheduler.config.last_hour = {0}; \n", ucLastHour); sb.AppendFormat(" scheduler.config.time_step = {0}; \n", ucTimeStep); sb.AppendFormat(" scheduler.config.start_on_monday = {0}; \n", ucIsStartOnMonday ? 1 : 0); sb.AppendFormat(" scheduler.config.event_duration = {0}; \n", ucEventDuration); sb.Append(" scheduler.config.auto_end_date = true; \n" + " scheduler.config.details_on_create = true;\n" + " scheduler.config.details_on_dblclick = true;\n"); sb.Append(" scheduler.config.lightbox.sections=[\n" + " {name:'text' , height:24 , map_to:'text' , type:'textarea' , focus:true },\n" + " {name:'description' , height:200, map_to:'description' , type:'textarea' },\n" + " {name:'recurring',type:'recurring',map_to:'rec_type',button:'recurring'},\n" + " {name:'time' , height:72 , map_to:'auto' , type:'time' }\n" + " ];\n"); ResourceInfo oRS = new ResourceInfo(); switch (strCultureCode) { case "en": oRS = new ResourceInfo() { ResourceID = "Source :", Subject = "Subject:", Description = "Desc. :", StartDate = "Start :", EndDate = "End :", UpdInfo = "Update :", Msg_EventConflict = "Event Collision !", Msg_NotEventOwner = "Not Event Owner !" }; break; case "zh-CHT": case "zh-Hant": oRS = new ResourceInfo() { ResourceID = "識別:", Subject = "主旨:", Description = "描述:", StartDate = "開始:", EndDate = "結束:", UpdInfo = "更新:", Msg_EventConflict = "該時段已有事件存在 !", Msg_NotEventOwner = "無權編修此事件 !" }; break; case "zh-CHS": case "zh-Hans": oRS = new ResourceInfo() { ResourceID = "识别:", Subject = "主旨:", Description = "描述:", StartDate = "开始:", EndDate = "结束:", UpdInfo = "更新:", Msg_EventConflict = "该时段已有事件存在!", Msg_NotEventOwner = "无权编修此事件!" }; break; } if (ucIsToolTip) { sb.Append(" scheduler.templates.tooltip_text = function(start,end,ev){{"); sb.AppendFormat(" return '<b>{0}</b> '+ ev.text ", oRS.Subject); if (ucIsShowEventDetail) { sb.AppendFormat(" + '<br/><b>{0}</b> ' + ev.description ", oRS.Description); } if (ucIsShowEventID) { sb.AppendFormat(" + '<hr/><b>{0}</b> [' + ev.ResourceID + ']' ", oRS.ResourceID); } sb.AppendFormat(" + '<br/><b>{0}</b> ' + scheduler.templates.tooltip_date_format(start) ", oRS.StartDate); sb.AppendFormat(" + '<br/><b>{0}</b> ' + scheduler.templates.tooltip_date_format(end)", oRS.EndDate); if (ucIsShowEventUpdInfo) { sb.AppendFormat(" + '<br/><b>{0}</b> ' + ev.UpdDateTime.substr(0, 16) + ' By ' + ev.UpdUser + ' - ' + ev.UpdUserName ", oRS.UpdInfo); } sb.Append(" ;}};\n"); } if (!ucIsShowEventTime) { sb.Append("scheduler.templates.event_date = function(start,end,ev){ return '' ;}; \n"); } if (!ucIsNavBar) { sb.Append(" scheduler.xy.nav_height = 0;\n"); dhx_cal_navline.Style["display"] = "none"; } if (!ucIsMiniCalEnabled) { dhx_minical_icon.Style["display"] = "none"; } if (ucIsYearView) { sb.Append(" document.getElementById('yearView').style.display = '';\n"); } if (ucIsMiniCalOnly) { mini_here.Style["display"] = ""; scheduler_here.Style["display"] = "none"; sb.AppendFormat(" scheduler.load('{0}&Rnd={1}' ,", strDataURL, Util.getRandomNum(10000, 99999)[0]); sb.Append(" function(){ scheduler.renderCalendar({\n" + " container:'mini_here',date:scheduler._date,navigation:true,handler:function(date,calendar){ \n" ); //在獨立的小日曆按下日期後的動作 if (ucIsMiniCalToScheduler) { string strScheUrl = strScheUrl = string.Format("{0}?DBName={1}&TableName={2}&ResourceIDList={3}&IsReadOnly={4}&LoadMode={5}&Width={6}&Height={7}", Util.getFixURL("~/Util/SchedulerAdmin.aspx"), ucDBName, ucTableName, ucResourceIDList, (ucIsReadOnly == true) ? "Y" : "N", ucLoadMode, ucWidth, ucHeight); strScheUrl += string.Format("&IsShowEventDetail={0}&IsShowEventTime={1}&IsShowEventID={2}&IsShowEventUpdInfo={3}&IsConflictEnabled={4}&IsOwnerEditOnly={5}", (ucIsShowEventDetail) ? "Y" : "N", (ucIsShowEventTime) ? "Y" : "N", (ucIsShowEventID) ? "Y" : "N", (ucIsShowEventUpdInfo) ? "Y" : "N", (ucIsConflictEnabled) ? "Y" : "N", (ucIsOwnerEditOnly) ? "Y" : "N" ); sb.Append("var PopUrl = '" + strScheUrl + "&LoadDate=' + date.getFullYear() + ',' + date.getMonth() + ',' + date.getDate(); \n"); string strSchePop = string.Format("var {0}_Pop=window.open(PopUrl + '&Caption={1}','{0}_PopWin','{2}');{0}_Pop.focus();return false;", "ScheAdmin", ucCaption, Util.getAppSetting("app://CfgPopupSpecs/")); sb.Append(strSchePop); } else { sb.Append(" alert('Selected ScheDate = [' + date.getFullYear() + ',' + date.getMonth() + ',' + date.getDate() + ']'); \n"); } sb.Append(" }\n" + " });\n" + " });\n" ); } else { mini_here.Style["display"] = "none"; scheduler_here.Style["display"] = ""; sb.AppendFormat(" scheduler.load('{0}&Rnd={1}');\n", strDataURL, Util.getRandomNum(10000, 99999)[0]); } if (ucIsReadOnly == true || strResourceIDList.Split(',').Length > 1) // 只要 ResourceID 數量大於1 即為唯讀 { //當 [唯讀] 或 [多個 ResourceID] Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_readonly.js"), "dhtmlx_readonly"); sb.Append(" scheduler.config.drag_move = false;\n"); //2015.11.26 add [ucIsShowReadOnlyForm] if (ucIsShowReadOnlyForm) { sb.Append(" scheduler.config.readonly = false;\n"); sb.Append(" scheduler.config.readonly_form = true;\n"); } else { sb.Append(" scheduler.config.readonly = true;\n"); sb.Append(" scheduler.config.readonly_form = false;\n"); } sb.Append(" scheduler.attachEvent('onEmptyClick', function(date,e) { return false; } ); \n"); sb.Append(" scheduler.attachEvent('onClick', function(id, e) { return false; } ); \n"); } else { //可編輯 //Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_quick_info.js"), "dhtmlx_quickinfo"); sb.AppendFormat(" var dp = new dataProcessor('{0}&Rnd={1}');\n", strDataURL, Util.getRandomNum(10000, 99999)[0]); sb.Append(" dp.init(scheduler);\n"); //非既有事件 Owner 不能進行修改/刪除 if (ucIsOwnerEditOnly) { UserInfo oUser = UserInfo.getUserInfo(); if (oUser != null && !string.IsNullOrEmpty(oUser.UserID)) { sb.Append(" scheduler.attachEvent('onClick', function(id, e) {\n" + " ev = scheduler.getEvent(id); \n" + " if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n" //+ " alert ('" + oRS.Msg_NotEventOwner +"'); \n" + " return false; }\n" + " return true; \n" + " }); \n"); sb.Append(" scheduler.attachEvent('onDblClick', function(id, e) {\n" + " ev = scheduler.getEvent(id); \n" + " if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n" + " alert ('" + oRS.Msg_NotEventOwner + "'); \n" + " return false; }\n" + " return true; \n" + " }); \n"); sb.Append(" scheduler.attachEvent('onBeforeDrag', function(id, e) {\n" + " ev = scheduler.getEvent(id); \n" + " if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n" //+ " alert ('" + oRS.Msg_NotEventOwner + "'); \n" + " return false; }\n" + " return true; \n" + " }); \n"); } } } //若同時段只允許一個事件 if (!ucIsConflictEnabled) { Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_collision.js"), "dhtmlx_collision"); sb.Append(" scheduler.attachEvent('onEventCollision', function (ev, evs) { \n" + " alert('" + oRS.Msg_EventConflict + "'); \n" + " return true; \n" + " }); \n"); } sb.Append(" scheduler.config.show_loading = true;\n"); sb.AppendFormat(" scheduler.init('scheduler_here', new Date({1}), '{0}');\n", ucLoadMode, ucLoadDate); sb.Append("} \n" + "window.onload = function () { init(); };\n"); Util.setJSContent(sb.ToString(), "dhtmlx_Init"); //-- 切換小月曆的 script Util.setJSContent("\nfunction show_minical() {\n" + " if (scheduler.isCalendarVisible()) {\n" + " scheduler.destroyCalendar();\n" + " } else {\n" + " scheduler.renderCalendar({\n" + " position: 'dhx_minical_icon',\n" + " date: scheduler._date,\n" + " navigation: true,\n" + " handler: function (date, calendar) {\n" + " scheduler.setCurrentView(date);\n" + " scheduler.destroyCalendar()\n" + " }\n" + " });\n" + " }\n" + "}\n", "dhtmlx_showmini"); }
/// <summary> /// Gets the string representation of the path /// </summary> internal String GetStepString(List <RDFNamespace> prefixes) { var result = new StringBuilder(); #region Single Property if (this.Steps.Count == 1) { //InversePath (will swap start/end) if (this.Steps[0].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[0].StepProperty; result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); } #endregion #region Multiple Properties else { //Initialize printing Boolean openedParenthesis = false; //Iterate properties for (int i = 0; i < this.Steps.Count; i++) { //Alternative: generate union pattern if (this.Steps[i].StepFlavor == RDFQueryEnums.RDFPropertyPathStepFlavors.Alternative) { if (!openedParenthesis) { openedParenthesis = true; result.Append("("); } //InversePath (will swap start/end) if (this.Steps[i].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[i].StepProperty; if (i < this.Steps.Count - 1) { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append((Char)this.Steps[i].StepFlavor); } else { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append(")"); } } //Sequence: generate pattern else { if (openedParenthesis) { result.Remove(result.Length - 1, 1); openedParenthesis = false; result.Append(")/"); } //InversePath (will swap start/end) if (this.Steps[i].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[i].StepProperty; if (i < this.Steps.Count - 1) { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append((Char)this.Steps[i].StepFlavor); } else { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); } } } } #endregion return(result.ToString()); }
/// <summary> /// Metodo para consultar si el dia actual es un dia feriado /// </summary> /// <returns></returns> /// <creo>Leslie González Vázquez</creo> /// <fecha creo>20/Mayo/2014</fecha creo> /// <modifico></modifico> /// <fecha modifico></fecha modifico> /// <causa modificacion></motivo modificacion> internal static DataTable Consultar_Productos_Servicios(Cls_Apl_Principal_Negocio Negocio) { DataTable Dt_Datos = new DataTable(); DataTable Dt_Datos_Producto_Id = new DataTable(); StringBuilder Mi_Sql = new StringBuilder(); Boolean Dia_Festivo = false; Conexion.Iniciar_Helper(); Conexion.HelperGenerico.Conexion_y_Apertura(); String Producto_Id_Parametro = ""; try { //consultamos si el dia de la visita es dia festivo Dia_Festivo = Consultar_Dias_Festivos(Negocio.P_Fecha_Visita); //Mi_Sql.Append("select " + Cat_Parametros.Campo_Producto_Id_Web + " from " + Cat_Parametros.Tabla_Cat_Parametros); //Dt_Datos_Producto_Id = Conexion.HelperGenerico.Obtener_Data_Table(Mi_Sql.ToString()); //// se obtiene el parametro del producto que se mostrara en el modulo web //foreach (DataRow Registro in Dt_Datos_Producto_Id.Rows) //{ // if (!String.IsNullOrEmpty(Registro[Cat_Parametros.Campo_Producto_Id_Web].ToString())) // Producto_Id_Parametro = Registro[Cat_Parametros.Campo_Producto_Id_Web].ToString(); //} Mi_Sql.Clear(); Mi_Sql.Append("select 0 as Cantidad, " + Cat_Productos.Campo_Producto_Id + ", "); Mi_Sql.Append(Cat_Productos.Campo_Nombre + ", "); Mi_Sql.Append(Cat_Productos.Campo_Descripcion + ", "); Mi_Sql.Append(Cat_Productos.Campo_Costo + ", "); Mi_Sql.Append(Cat_Productos.Campo_Codigo + ", "); Mi_Sql.Append(Cat_Productos.Campo_Ruta_Imagen + ", "); Mi_Sql.Append(Cat_Productos.Campo_Tipo ); Mi_Sql.Append(" from " + Cat_Productos.Tabla_Cat_Productos); Mi_Sql.Append(" where " + Cat_Productos.Campo_Tipo_Servicio + " != 'ESTACIONAMIENTO'"); Mi_Sql.Append(" and " + Cat_Productos.Campo_Estatus + " = 'ACTIVO' "); Mi_Sql.Append(" and " + Cat_Productos.Campo_Web + "= 'S'"); //if (!String.IsNullOrEmpty(Producto_Id_Parametro)) // Mi_Sql.Append(" and " + Cat_Productos.Campo_Producto_Id + " = '" + Producto_Id_Parametro + "'"); //if (Dia_Festivo) //{ // Mi_Sql.Append(" and " + Cat_Productos.Campo_Tipo + " = 'Servicio'"); // Mi_Sql.Append(" union "); // Mi_Sql.Append("select 0 as Cantidad, " + Cat_Productos.Campo_Producto_Id + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Nombre + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Descripcion + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Costo + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Codigo + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Ruta_Imagen + ", "); // Mi_Sql.Append(Cat_Productos.Campo_Tipo); // Mi_Sql.Append(" from " + Cat_Productos.Tabla_Cat_Productos); // Mi_Sql.Append(" where upper(" + Cat_Productos.Campo_Nombre + ") = 'ENTRADA GENERAL'"); //} Mi_Sql.Append(" order by " + Cat_Productos.Campo_Tipo + " asc"); Dt_Datos = Conexion.HelperGenerico.Obtener_Data_Table(Mi_Sql.ToString()); } catch (Exception Ex) { throw new Exception(" Error al consultar los productos y servicios. Error[" + Ex.Message + "]"); } finally { Conexion.HelperGenerico.Cerrar_Conexion(); } return Dt_Datos; }
static void Main(string[] args) { string email = Console.ReadLine(); string input; while ((input = Console.ReadLine()) != "Complete") { string[] tokens = input.Split(" "); if (tokens[0] == "GetUsername") { bool isVaild=false; foreach(var element in email) { if(element=='@') { isVaild = true; } } if(isVaild) { int i = 0; StringBuilder name=new StringBuilder(); while (email[i] != '@') { name.Append(email[i]); i++; } Console.WriteLine(name); } else { Console.WriteLine($"The email {email} doesn't contain the @ symbol."); } } if (tokens[0] == "Encrypt") { byte[] asciiBytes = Encoding.ASCII.GetBytes(email); Console.WriteLine(string.Join(" ",asciiBytes)); } if (tokens[0] == "Make"&&tokens[1]=="Upper") { email = email.ToUpper(); Console.WriteLine(email); } if(tokens[0]=="Make"&&tokens[1]=="Lower") { email = email.ToLower(); Console.WriteLine(email); } if(tokens[0]== "GetDomain") { int count = int.Parse(tokens[1]); int emailLength = email.Length; StringBuilder domain = new StringBuilder(); for(int i=0;i<count;i++) { domain.Append(email[emailLength - count + i]); } Console.WriteLine(domain); } if(tokens[0]=="Replace") { char symbol =char.Parse( tokens[1]); for(int i = 0; i < email.Length; i ++) { if(email[i]==symbol) { email=email.Replace(symbol, '-'); break; } } Console.WriteLine(email); } } }
public static MvcHtmlString ChangeableFor <TModel, TValue, TType>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, Changeable <TType> changeable) { // helper to take our Changeable<T> property, and create lambdas to get var controller = html.ViewContext.Controller; var actionName = controller.ValueProvider.GetValue("action").RawValue.ToString(); var allMethods = controller.GetType().GetMethods(); var methods = allMethods.Where(m => m.Name == actionName); foreach (var method in methods) { var attributes = method.GetCustomAttributes(true); foreach (var attribute in attributes) { if (attribute.GetType().Equals(typeof(HttpPostAttribute))) { var a = attribute; } } } var name = ExpressionHelper.GetExpressionText(expression); if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", "Name cannot be null"); } // get the metadata for our Changeable<T> property var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); var type = metadata.ModelType; var containerType = metadata.ContainerType; // create a lambda expression to get the value of our Changeable<T> var arg = Expression.Parameter(containerType, "x"); Expression expr = arg; expr = Expression.Property(expr, name); expr = Expression.Property(expr, "Value"); var funcExpr = Expression.Lambda(expr, arg) as Expression <Func <TModel, TType> >; var valueModelMetadata = ModelMetadata.FromLambdaExpression(funcExpr, html.ViewData); // create a lambda expression to get whether our Changeable<T> has changed Expression exprChanged = arg; exprChanged = Expression.Property(exprChanged, name); exprChanged = Expression.Property(exprChanged, "Changed"); var funcExprChanged = Expression.Lambda(exprChanged, arg) as Expression <Func <TModel, bool> >; // use a stringbuilder for our HTML markup // return label, checkbox, hidden input, EDITOR, and validation message field // NOTE: this is over-simplified markup! // ALSO NOTE: the EditorFor is passed the strongly typed model taken from our T. Bonus! var htmlSb = new StringBuilder("\n"); htmlSb.Append(LabelExtensions.Label(html, metadata.GetDisplayName())); htmlSb.Append("<br />\n"); htmlSb.Append(InputExtensions.CheckBoxFor(html, funcExprChanged)); htmlSb.Append(" Changed<br />\n"); htmlSb.Append(InputExtensions.Hidden(html, name + ".OldValue", valueModelMetadata.Model) + "\n"); htmlSb.Append(EditorExtensions.EditorFor(html, funcExpr, new KeyValuePair <string, object>("parentMetadata", metadata))); //new object[] { "parentMetadata", metadata })); htmlSb.Append(ValidationExtensions.ValidationMessageFor(html, funcExpr)); htmlSb.Append("<br />\n"); return(new MvcHtmlString(htmlSb.ToString())); }
/// <summary> /// Generates a final Path based on parameters in Dictionary and resource properties. /// </summary> /// <typeparam name="T">MPBase resource.</typeparam> /// <param name="path">Path we are processing.</param> /// <param name="mapParams">Collection of parameters that we will use to process the final path.</param> /// <param name="resource">Resource containing parameters values to include in the final path.</param> /// <param name="requestOptions">Object containing the request options.</param> /// <returns>Processed path to call the API.</returns> public static string ParsePath<T>(string path, Dictionary<string, string> mapParams, T resource, MPRequestOptions requestOptions) where T : MPBase { string param_pattern = @":([a-z0-9_]+)"; MatchCollection matches = Regex.Matches(path, param_pattern); foreach (Match param in matches) { string param_string = param.Value.Replace(":", ""); if (mapParams != null) { foreach (KeyValuePair<String, String> entry in mapParams) { if (param_string == entry.Key) { path = path.Replace(param.Value, entry.Value); } } } if (resource != null) { JObject json = JObject.FromObject(resource); var resource_value = json.GetValue(ToPascalCase(param_string)); if (resource_value != null) { path = path.Replace(param.Value, resource_value.ToString()); } } } StringBuilder result = new StringBuilder(); result.Insert(0, SDK.BaseUrl); result.Append(path); if (requestOptions == null) { requestOptions = new MPRequestOptions(); } string accessToken; if (!String.IsNullOrEmpty(requestOptions.AccessToken)) { accessToken = requestOptions.AccessToken; } else if (resource != null && !String.IsNullOrEmpty(resource.MarketplaceAccessToken)) { accessToken = resource.MarketplaceAccessToken; } else { accessToken = SDK.GetAccessToken(); } if (!String.IsNullOrEmpty(accessToken) && !path.Equals("/oauth/token", StringComparison.InvariantCultureIgnoreCase)) { result.Append(string.Format("{0}{1}", "?access_token=", accessToken)); } bool search = !path.Contains(':') && mapParams != null && mapParams.Any(); if (search) //search url format, no :id type. Params after access_token { foreach (var elem in mapParams) { if (!string.IsNullOrEmpty(elem.Value)) { result.Append(string.Format("{0}{1}={2}", "&", elem.Key, elem.Value)); } } } return result.ToString(); }
/// <summary> /// Initializes a new file for <see cref="IMulticastLogEntry"/>: the final file name is based on <see cref="FileUtil.FileNameUniqueTimeUtcFormat"/> with a ".ckmon" extension. /// You must call <see cref="MonitorFileOutputBase.Initialize">Initialize</see> before actually using this object. /// </summary> /// <param name="configuredPath">The path: it can be absolute and when relative, it will be under <see cref="SystemActivityMonitor.RootLogPath"/> (that must be set).</param> /// <param name="maxCountPerFile">Maximum number of entries per file. Must be greater than 1.</param> /// <param name="useGzipCompression">True to gzip the file.</param> public MonitorTextFileOutput(string configuredPath, int maxCountPerFile, bool useGzipCompression) : base(configuredPath, ".txt" + (useGzipCompression ? ".gzip" : string.Empty), maxCountPerFile, useGzipCompression) { _builder = new StringBuilder(); _monitorNames = new Dictionary <Guid, string>(); }
private static void GetSimpleFormatString(Node constantNode, List <NodeInfo> nodeInfos, StringBuilder textLine) { constantNode.Walk((text, value, depth) => { if (value != null) { nodeInfos.Add(new NodeInfo { Location = textLine.Length, Value = value, Depth = depth }); } textLine.Append(text); }, 0); }
public static StringBuilder Append(this StringBuilder sb, ReadOnlySpan<char> value) => MemoryProvider.Instance.Append(sb, value);
protected void Page_Load(object sender, EventArgs e) { Session["Masterpage"] = "~/DashboardSite.Master"; //2/11/2016 NS added for VSPLUS-2531 //2/25/2016 Durga Modified for VSPLUS-2634 int ind = -1; int diffInMin = 0; List <string> tempStatus = VSWebBL.DashboardBL.DashboardBL.Ins.GetProcessStatus(); //2/25/2016 Durga Modified for VSPLUS-2634 //3/1/2016 NS modified - when nothing was being returned, a red button showed up next to the menu if (string.IsNullOrEmpty(tempStatus[0])) { ASPxButton2.Style.Value = "display: none"; } else { ASPxButton2.Text = (string.IsNullOrEmpty(tempStatus[0]) ? "Test" : "Updated: " + tempStatus[0].Replace("on ", "")); } diffInMin = Convert.ToInt32(string.IsNullOrEmpty(tempStatus[1]) == true ? "0" : tempStatus[1]); if (diffInMin < 10) { ASPxButton2.CssClass = "greenButton"; } else { if (diffInMin >= 10 && diffInMin < 30) { ASPxButton2.CssClass = "yellowButton"; } else { ASPxButton2.CssClass = "redButton"; } } SetLinkVisibility(); if (!IsPostBack) { ProcessPageSessions(); CheckMasterService(); } bool isDashBoardOnlyAccess = false; if ((Request.Url.AbsoluteUri.ToLower().Contains("overallhealth1.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("devicetypelist.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("summarylandscape.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("maildeliverystatus.aspx"))) { //if the session variable is not found or the session variable is empty, either the user is ciming in as dashboardonly mode or the session expired. Either cases, we'll change the mode to DashBoardOnlyMode if (Session["UserFullName"] == null || Session["UserFullName"].ToString() == "" || Session["UserFullName"].ToString() == "Anonymous") { Session["IsDashboard"] = "true"; Session["UserFullName"] = "Anonymous"; isDashBoardOnlyAccess = true; ASPxMenu1.Visible = true; nameAndLogoutButton.Visible = false; ASPxMenu3.Visible = false; } else { CreateMenu1(); } } CreateMenu1(); if (Session["FilterByValue"] == null || Session["FilterByValue"].ToString() == "") { Session["FilterByValue"] = "null"; } if (Session["ViewBy"] == null || Session["FilterByValue"].ToString() == "") { Session["ViewBy"] = "ServerType"; } if (Session["UserFullName"].ToString() != "Anonymous" || Session["SummaryEXJournal"] != null || isDashBoardOnlyAccess == true) { UserFullNameLabel.Text = Session["UserFullName"].ToString(); } else { Response.Redirect("~/login.aspx", false); //Mukund, 05Aug14, VSPLUS-844:Page redirect on callback Context.ApplicationInstance.CompleteRequest(); } if (Session["IsDashboard"] != null && Session["IsDashboard"].ToString() != "") { if (Convert.ToBoolean(Session["IsDashboard"].ToString()) == true) { //VSPLUS-1767, Mukund, timeout issue Session.Timeout = 600; //9/5/2013 NS commented out the !IsPostBack condition since otherwise page refresh did not take place //when async postback was sent by the timer //if (!IsPostBack) //{ // Handle the session timeout string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/SessionExpired.aspx"; StringBuilder script = new StringBuilder(); script.Append("function expireSession(){ \n"); script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl)); script.Append("} \n"); script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true); //} if (Session["Isconfigurator"] != null && Session["Isconfigurator"].ToString() != "") { if (Convert.ToBoolean(Session["Isconfigurator"].ToString()) == true) { ASPxMenu1.Items[6].Visible = true; } } //Mukund added code 11-Oct-13, to make ExJournal,visible or not string ExJournalEnabled = VSWebBL.SettingBL.SettingsBL.Ins.Getvalue("Enable ExJournal"); if (ExJournalEnabled == "true") { //3/29/2015 NS modified for VSPLUS-1610 ASPxMenu1.Items[0].Items.FindByName("EXJournal Summary").Visible = true; } else { //3/29/2015 NS modified for VSPLUS-1610 if (ASPxMenu1.Items[0].Items.FindByName("EXJournal Summary") != null) { ASPxMenu1.Items[0].Items.FindByName("EXJournal Summary").Visible = false; } } Company cmpobj = new Company(); //1/6/2014 NS added cmpobj = VSWebBL.ConfiguratorBL.CompanyBL.Ins.GetLogo(); //1/15/2014 NS modified logo.Src = cmpobj.LogoPath; //"/images/logo.png"; } } else if (Session["Isconfigurator"] != null && Session["Isconfigurator"] != "") { if (Convert.ToBoolean(Session["Isconfigurator"].ToString()) == true) { Response.Redirect("~/Configurator/Default.aspx", false); //Mukund, 05Aug14, VSPLUS-844:Page redirect on callback Context.ApplicationInstance.CompleteRequest(); } else { Response.Redirect("~/login.aspx", false); //Mukund, 05Aug14, VSPLUS-844:Page redirect on callback Context.ApplicationInstance.CompleteRequest(); } } else { //MD 30Dec2013 if (Session["SummaryEXJournal"] != null) { //Response.Redirect("~/Dashboard/SummaryEXJournal.aspx"); ASPxMenu1.Visible = false; StatusBox1.Visible = false; SearchTextBox.Visible = false; ASPxButton1.Visible = false; Session["SummaryEXJournal"] = null; } else { if (Request.Url.AbsoluteUri.ToLower().Contains("overallhealth1.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("devicetypelist.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("summarylandscape.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("maildeliverystatus.aspx") || Request.Url.AbsoluteUri.ToLower().Contains("summaryexjournal.aspx")) { //VSPLUS-1767, Mukund, timeout issue //reset the session timeout here Session.Timeout = 600; Session["IsDashboard"] = ""; Session["UserFullName"] = "Anonymous"; isDashBoardOnlyAccess = true; ASPxMenu1.Visible = true; nameAndLogoutButton.Visible = false; } else { Response.Redirect("~/SessionExpired.aspx", false); //Mukund, 05Aug14, VSPLUS-844:Page redirect on callback Context.ApplicationInstance.CompleteRequest(); } } } //24/3/2015 Sowjanya added //9/4/2013 NS added timer refresh interval; set in milliseconds; refreshtime comes from the Users table and should be set in seconds if (Session["Refreshtime"] != "" && Session["Refreshtime"] != null) { timer1.Interval = Convert.ToInt32(Session["Refreshtime"]) * 1000; } else { timer1.Interval = 10000; } //2/8/2013 NS added //9/5/2013 NS commented out the !IsPostBack condition since otherwise page refresh did not take place //when async postback was sent by the timer if (!IsPostBack) { AssignStatusbox(); } //24/3/2015 Sowjanya added if (Session["UserID"] != null) { if (Session["UserID"].ToString() != "") { //2/27/2015 NS added DisplaySysMessages(); } } //Mukund 16Jul14, VSPLUS-741, VSPLUS-785 Disable/Enable Timer to update count in Header boxes //Check MenuItems table for new fields SessionNames & TimerEnable DisableTimer(); //10/27/2014 NS added for VSPLUS-1039 if (CultureInfo.CurrentCulture.Name.Contains("zh-")) { fontLink.Href = "http://fonts.useso.com/css?family=Francois One"; } else { fontLink.Href = "http://fonts.googleapis.com/css?family=Francois One"; } //3/2/2016 NS added getAssemblyVersionInfo(); getBuildInfo(); }
Serializer() { builder = new StringBuilder(); }
public string Output( Dictionary <string, Dictionary <string, int> > rows, string name, OutputType type = OutputType.Xlsx, string[] outOrder = null, bool percents = false) { var sorted = outOrder ?? (IEnumerable <string>)rows.Keys .Where(s => rows[s].Count > 0 || !ColumnIsEmpty(rows, s)) .OrderBy(s => s).ToArray(); Console.WriteLine("graph {1} has {0} nodes", sorted.Count(), name); var path = GetOutputPath(name, type); if (type == OutputType.Xlsx) { using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write)) { var wb = new XSSFWorkbook(); var sheet = wb.CreateSheet(name); var erowN = 0; var ecellN = 0; var erow = sheet.CreateRow(erowN++); var cell = erow.CreateCell(ecellN++); cell.SetCellValue(string.Empty); foreach (var col in sorted) { cell = erow.CreateCell(ecellN++); cell.SetCellValue(col); } var diagonalStyle = wb.CreateCellStyle(); diagonalStyle.FillBackgroundColor = IndexedColors.Yellow.Index; diagonalStyle.FillPattern = FillPattern.LeastDots; foreach (var row in sorted) { erow = sheet.CreateRow(erowN++); ecellN = 0; cell = erow.CreateCell(ecellN++); cell.SetCellValue(row); var cols = rows[row]; foreach (var col in sorted) { cell = erow.CreateCell(ecellN++); cell.SetCellValue(cols.ContainsKey(col) ? cols[col] : 0); if (row == col) { cell.CellStyle = diagonalStyle; } } } wb.Write(stream); stream.Close(); } } else { var sb = new StringBuilder(); sb.Append("$, "); foreach (var col in sorted) { sb.Append(col + ", "); } sb.AppendLine(); foreach (var row in sorted) { sb.Append(row + ", "); var cols = rows[row]; foreach (var col in sorted) { sb.Append(cols.ContainsKey(col) ? cols[col] : 0); sb.Append(", "); } sb.AppendLine(); } if (type == OutputType.Csv) { File.WriteAllText(path, sb.ToString()); } else { // OutOfMemoryException for graph with 7000 nodes return(sb.ToString()); } } return(null); }
/// <summary> /// 更新一条数据 /// </summary> public bool Update(WeiXinPF.Model.wx_agent_info model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update wx_agent_info set "); strSql.Append("managerId=@managerId,"); strSql.Append("companyName=@companyName,"); strSql.Append("companyInfo=@companyInfo,"); strSql.Append("agentPrice=@agentPrice,"); strSql.Append("agentPrice2=@agentPrice2,"); strSql.Append("sqJine=@sqJine,"); strSql.Append("czTotMoney=@czTotMoney,"); strSql.Append("remainMony=@remainMony,"); strSql.Append("userNum=@userNum,"); strSql.Append("wcodeNum=@wcodeNum,"); strSql.Append("agentType=@agentType,"); strSql.Append("agentLevel=@agentLevel,"); strSql.Append("industry=@industry,"); strSql.Append("agentArea=@agentArea,"); strSql.Append("expiryDate=@expiryDate,"); strSql.Append("aRemark=@aRemark,"); strSql.Append("createDate=@createDate"); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@managerId", SqlDbType.Int, 4), new SqlParameter("@companyName", SqlDbType.VarChar, 200), new SqlParameter("@companyInfo", SqlDbType.VarChar, 800), new SqlParameter("@agentPrice", SqlDbType.Int, 4), new SqlParameter("@agentPrice2", SqlDbType.Int, 4), new SqlParameter("@sqJine", SqlDbType.Int, 4), new SqlParameter("@czTotMoney", SqlDbType.Int, 4), new SqlParameter("@remainMony", SqlDbType.Int, 4), new SqlParameter("@userNum", SqlDbType.Int, 4), new SqlParameter("@wcodeNum", SqlDbType.Int, 4), new SqlParameter("@agentType", SqlDbType.Int, 4), new SqlParameter("@agentLevel", SqlDbType.VarChar, 50), new SqlParameter("@industry", SqlDbType.VarChar, 200), new SqlParameter("@agentArea", SqlDbType.VarChar, 300), new SqlParameter("@expiryDate", SqlDbType.DateTime), new SqlParameter("@aRemark", SqlDbType.VarChar, 1500), new SqlParameter("@createDate", SqlDbType.DateTime), new SqlParameter("@id", SqlDbType.Int, 4) }; parameters[0].Value = model.managerId; parameters[1].Value = model.companyName; parameters[2].Value = model.companyInfo; parameters[3].Value = model.agentPrice; parameters[4].Value = model.agentPrice2; parameters[5].Value = model.sqJine; parameters[6].Value = model.czTotMoney; parameters[7].Value = model.remainMony; parameters[8].Value = model.userNum; parameters[9].Value = model.wcodeNum; parameters[10].Value = model.agentType; parameters[11].Value = model.agentLevel; parameters[12].Value = model.industry; parameters[13].Value = model.agentArea; parameters[14].Value = model.expiryDate; parameters[15].Value = model.aRemark; parameters[16].Value = model.createDate; parameters[17].Value = model.id; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return(true); } else { return(false); } }
private static string GetShortPath(string path) { var shortPath = new StringBuilder(MAX_PATH); GetShortPathName(path, shortPath, MAX_PATH); return shortPath.ToString(); }