public String cmd(String cnd) { cnd = cnd.Trim(); String output = " "; Console.WriteLine(cnd); if ((cnd.Substring(0, 3).ToLower() == "cd_") && (cnd.Length > 2)) { if (System.IO.Directory.Exists(cnd.Substring(2).Trim())) cpath = cnd.Substring(2).Trim(); } else { cnd = cnd.Insert(0, "/B /c "); Process p = new Process(); p.StartInfo.WorkingDirectory = cpath; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = cnd; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); output = p.StandardOutput.ReadToEnd(); // output of cmd output = (output.Length == 0) ? " " : output; p.WaitForExit(); } return output; } // end cmd
public RepositoryFile(IRepository repository, String path, RepositoryStatus contentsStatus, RepositoryStatus propertiesStatus) { if (path == null) throw new ArgumentNullException("path"); if (path.Trim().Length == 0) throw new ArgumentException("Path must be set to a valid path", "path"); if (path[path.Length-1] == '/') throw new ArgumentException("Path must be set to a file, not a directory", "path"); if (propertiesStatus == RepositoryStatus.Added || propertiesStatus == RepositoryStatus.Deleted) { throw new ArgumentException("Properties status cannot be set to Added or Deleted, use Updated", "propertiesStatus"); } this.contentsStatus = contentsStatus; this.propertiesStatus = propertiesStatus; this.repository = repository; SetPathRelatedFields(path); if (fileName.EndsWith(" ")) throw new ArgumentException("Filename cannot end with trailing spaces", "path"); if (fileName.StartsWith(" ")) throw new ArgumentException("Filename cannot begin with leading spaces", "path"); }
/// <summary>计算value值</summary> public void calculateTheAliveValue(IToken token, String condition) { if (!token.IsAlive) { return;//如果token是dead状态,表明synchronizer的joinpoint是dead状态,不需要重新计算。 } //1、如果没有转移条件,默认为true if (condition == null || condition.Trim().Equals("")) { token.IsAlive=true; return; } //2、default类型的不需要计算其alive值,该值由synchronizer决定 if (condition.Trim().Equals(ConditionConstant.DEFAULT)) { return; } //3、计算EL表达式 try { Boolean alive = determineTheAliveOfToken(token.ProcessInstance.ProcessInstanceVariables, condition); token.IsAlive=alive; } catch (Exception ex) { throw new EngineException(token.ProcessInstanceId, token.ProcessInstance.WorkflowProcess, token.NodeId, ex.Message); } }
//返回IPC中/前的所有字符串加/后的4个字符 public static String DocDbFormatIPC(String ipc) { if (ipc.Trim() == "") { return ipc.Trim(); } else if (!ipc.Contains('/')) { return ipc.Split(' ')[0].Trim(); } else { String[] tem = ipc.Split('/'); String result = ipc.Split('/')[0].Trim() + "/"; if (tem[1].Length > 4)//只取/后的4个字符 { result = result + tem[1].Substring(0, 4).Trim(); } else { result = result + tem[1].Trim(); } return result; } }
/// <summary> /// 初始化,需要sap系统名与表名,表名与结构名一致。 /// </summary> /// <param name="psysName"></param> /// <param name="pTableName"></param> public SapTable(String psysName, String pTableName) { SystemName = psysName; TableName = pTableName.Trim().ToUpper(); StructureName = pTableName.Trim().ToUpper(); // prepareFieldsFromSapSystem(); }
public Logger(String outputLocation) { if (writer != null) { writer.Flush(); writer.Close(); } FileStream ostrm; TextWriter oldOut = Console.Out; if (outputLocation != null) { try { ostrm = new FileStream(outputLocation.Trim(), FileMode.OpenOrCreate, FileAccess.Write); ostrm.SetLength(0); // clear the file ostrm.Flush(); writer = new StreamWriter(ostrm); writer.AutoFlush = true; } catch (Exception e) { Console.WriteLine("Cannot open " + outputLocation.Trim() + " for writing"); Console.WriteLine(e.Message); return; } } }
//! method for create telegraph with a telegraph type string public Telegraph CreateTelegraph(System.String strType, params Object[] Args) { if (null == strType) { return(null); } if ("" == strType.Trim().ToUpper()) { return(null); } foreach (Telegraph tTelegraph in m_SupportTelegraphList) { if (tTelegraph.Type.Trim().ToUpper() == strType.Trim().ToUpper()) { Telegraph tResultTelegraph = tTelegraph.CreateTelegraph(Args); if (null != tResultTelegraph) { return(tResultTelegraph); } } } return(null); }
public ActionResult Create([Bind(Include = "BookID,Title,Genre")] Book book,String AuthorName) { if (ModelState.IsValid) { var auToCheck = from auth in db.Authors where auth.AuthorName == AuthorName select auth; if (AuthorName.Trim() != auToCheck.FirstOrDefault().AuthorName.Trim()) { Author au = new Author(); au.AuthorName = AuthorName.Trim(); db.Authors.Add(au); au.Books.Add(book); book.Authors.Add(au); } else { book.Authors.Add(auToCheck.FirstOrDefault()); } db.Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } return View(book); }
public void addException(String exception) { if (!WhiteList.Contains(exception.Trim().ToLower())) { WhiteList.Add(exception.Trim().ToLower()); } }
public string sendpayment(String apiusername, String apipassword, String amount, String sender, String reason) { DataTable dt = new DataTable(); string result = null; string holdserial = null; SqlConnection mycoon=myreadconn.realreadconn(); my_storedpro.username = reason.Trim(); my_storedpro.amount = double.Parse(amount); my_storedpro.controller = sender.Trim(); my_storedpro.balbefore = double.Parse(get_bal(reason.Trim()).ToString()); holdserial = myreadconn.GetNextMobileSerial(mycoon); my_storedpro.serial = (holdserial.Trim() + sender.Trim()).Trim(); myreadconn.EditNextMobileSerial(holdserial, mycoon); if ((apiusername == "globalbets") && (apipassword == "dewilos")) { result = my_storedpro.epay(); } return result + "|" + my_storedpro.serial; }
/// <summary> It adds the specified input text to the input queue of the work flow. After this method, /// you are allowed to get the analysis result by using one of the following methods: /// /// - getResultOfSentence() : to get the result for one sentence at the front of result queue /// - getResultOfDocument() : to get the entire result for all sentences /// /// If the input document is not small, getResultOfDocument() may show lower performance, and it /// could be better to call getResultOfSentence() repeatedly. You need to pay attention on this. /// /// </summary> /// <param name="document">- the path for the text file to be analyzed /// </param> /// <throws> IOException </throws> public virtual void analyze(System.IO.FileInfo document) { System.IO.StreamReader br = new System.IO.StreamReader(document.FullName, System.Text.Encoding.UTF8); LinkedBlockingQueue <PlainSentence> queue = queuePhase1[0]; if (queue == null) { return; } System.String line = null; int i = 0; while ((line = br.ReadLine()) != null) { if (br.Peek() != -1) { queue.Add(new PlainSentence(0, i++, false, line.Trim())); } else { queue.Add(new PlainSentence(0, i++, true, line.Trim())); break; } } br.Close(); if (!isThreadMode) { analyzeInSingleThread(); } }
public bool removeException(String exception) { bool pass = false; if (WhiteList.Contains(exception.Trim().ToLower())) { WhiteList.Remove(exception.Trim().ToLower()); } return pass; }
public void 添加错误消息(String 异常描述, String 异常代码, String 异常信息, int 异常级别, int 异常类型, String 主机名称, String 方法名称, String 消息编码, String 绑定地址编码, int 异常信息状态, String 请求消息体, int 请求类型, String 请求密码, int 绑定类型) { //bool isAddOk = true; 错误消息处理逻辑 错误逻辑 = new 错误消息处理逻辑(); 异常信息对象 异常对象 = new 异常信息对象(); 异常对象.异常时间 = System.DateTime.Now; 异常对象.异常描述 = 异常描述.Trim(); 异常对象.异常代码 = 异常代码.Trim(); 异常对象.异常信息 = 异常信息.Trim(); 异常对象.异常级别 = 异常级别; 异常对象.异常类型 = 异常类型; 异常对象.主机名称 = 主机名称.Trim(); 异常对象.方法名称 = 方法名称.Trim(); 异常对象.请求密码 = 请求密码.Trim(); 异常对象.绑定类型 = 绑定类型; 异常对象.请求类型 = 请求类型; 异常对象.消息编码 = new Guid(消息编码); 异常对象.绑定地址编码 = new Guid(绑定地址编码); 异常对象.异常信息状态 = 异常信息状态; 异常对象.请求消息体 = 请求消息体; XmlDocument document = new XmlDocument(); document.LoadXml(请求消息体); string serviceName = document.DocumentElement.SelectSingleNode("服务名称").InnerText.Trim(); string reqBeginTime = document.DocumentElement.SelectSingleNode("请求时间").InnerText.Trim(); //Audit.AuditServcie auditServcie = new JN.ESB.Exception.Service.Audit.AuditServcie(); //auditServcie.AddAuditBusiness(主机名称, 请求消息体, 消息编码, 方法名称, reqBeginTime, serviceName, 0); 服务目录业务逻辑 UDDI = new 服务目录业务逻辑(); List<个人> 系统管理员 = UDDI.获得系统管理员(); if ((String.IsNullOrEmpty(绑定地址编码.Trim()) || 绑定地址编码.Trim() == "00000000-0000-0000-0000-000000000000")) { if(UDDI.获得绑定信息_服务名称(serviceName)!=null){ 异常对象.绑定地址编码 = UDDI.获得绑定信息_服务名称(serviceName).服务地址编码; } } 错误逻辑.创建错误消息(异常对象); try { if (!(异常对象.绑定地址编码.Value == Guid.Empty)) { 服务地址 地址 = UDDI.获得绑定信息_服务地址编码(异常对象.绑定地址编码.Value); 个人 服务管理员 = UDDI.获得管理员_具体绑定服务(地址); if (!(系统管理员.Contains(服务管理员))) 系统管理员.Add(服务管理员); } this.发送OA邮件(异常对象, 系统管理员); } catch { } }
/// <summary> /// Default-ctor to build a named SPARQL variable /// </summary> public RDFVariable(String variableName) { if (variableName != null && variableName.Trim() != String.Empty) { this.VariableName = "?" + variableName.Trim().ToUpperInvariant(); this.PatternMemberID = RDFModelUtilities.CreateHash(this.ToString()); } else { throw new RDFQueryException("Cannot create RDFVariable because given \"variableName\" parameter is null or empty."); } }
// ------------------------------ Url --------------------------------------- /// <summary> /// 检查url是否完整(是否以http开头或者以域名开头) /// </summary> /// <param name="url"></param> /// <returns></returns> public static Boolean IsFullUrl( String url ) { if (strUtil.IsNullOrEmpty( url )) return false; if (url.Trim().StartsWith( "/" )) return false; if (url.Trim().StartsWith( "http://" )) return true; String[] arrItem = url.Split( '/' ); if (arrItem.Length < 1) return false; int dotIndex = arrItem[0].IndexOf( "." ); if (dotIndex <= 0) return false; return hasCommonExt( arrItem[0] ) == false; }
/** * Extract the mime part from an Http Content-Type header */ public static String extractMimePart(String contentType) { contentType = contentType.Trim(); int separator = contentType.IndexOf(';'); if (separator != -1) { contentType = contentType.Substring(0, separator); } return contentType.Trim().ToLower(); }
public static void HandleMessage(String message, ref bool displayMessage) { if (!MyAPIGateway.Multiplayer.IsServer || !message.Trim().ToLower().StartsWith("dc")) { displayMessage = true; return; } gMessage = message.Trim().Substring(2).Trim(); displayMessage = false; }
public static object CheckForEmptyStringVal(String value) { if (value.Trim().Length == 0) { return DBNull.Value; } else { return value.Trim(); } }
private static Boolean meetsReq(String prop, String req) { if (req.Trim() == "") { return true; } else { if (prop.Trim() == req.Trim()) { return true; } else { return false; } } }
public override int Write(String line) { lock (_locker) // ensure synchronization { line = RemoveComment(line); if (line.Trim().Length > 0) { m_serialport.Write(line); } return line.Trim().Length; } }
// check for exact match public Result[] search(String txt, bool all = false) { if (this.pat.Length == 0) return null; String txtLocal = this.IgnoreCase ? txt.Trim().ToLower() : txt.Trim(); int N = txtLocal.Length; List<Result> result = new List<Result>(); if (N < M) return null; long txtHash = hash(txtLocal, M); // check for match at offset 0 if (Array.IndexOf(patHash, txtHash) != -1) { String[] sample = getSample(0, txt, M); //String[] sample = new string[] { "", "", "" }; result.Add(new Result() { Line = 1, Index = 0, Length = M, TextStart = sample[0], Pattern = sample[1], TextEnd = sample[2] }); if (!all) return result.ToArray(); } // check for hash match; if hash match, check for exact match for (int i = M; i < N; i++) { // Remove leading digit, add trailing digit, check for match. txtHash = (txtHash + Q - RM * txtLocal[i - M] % Q) % Q; txtHash = (txtHash * R + txtLocal[i]) % Q; //check hash in hash array if (Array.IndexOf(patHash, txtHash) != -1) { // match int offset = i - M + 1; String[] sample = getSample(offset, txt, M); result.Add(new Result() { Line = getLine(offset, txtLocal), Index = offset, Length = M, TextStart = sample[0], Pattern = sample[1], TextEnd = sample[2] }); if (!all) return result.ToArray(); } } return result.Count > 0 ? result.ToArray() : null; }
/** * Check if name provided is valid for use as the name of a RandomVariable. * * @param name * proposed for the RandomVariable. * @throws IllegalArgumentException * if not a valid RandomVariable name. */ public static void checkValidRandomVariableName(String name) { if (null == name || name.Trim().Length == 0 || name.Trim().Length != name.Length || name.Contains(" ")) { throw new ArgumentException( "Name of RandomVariable must be specified and contain no leading, trailing or embedded spaces."); } if (name.Substring(0, 1).ToLower().Equals(name.Substring(0, 1))) { throw new ArgumentException( "Name must start with a leading upper case letter."); } }
public void addException(String exception, bool filter = false, int filterLength = -1) { if (!WhiteList.Contains(exception.Trim().ToLower())) { WhiteList.Add(exception.Trim().ToLower()); } if (filter) { if (filterLength == -1) { filterLength = exception.Length; } filterExceptions(filterLength); } }
public JsonResult AlbumAutoComplete(String title,String artist = null) { List<Album> albums; if (artist == null) { albums = _db.Albums.Where(a => a.Title.ToLower().Contains(title.Trim().ToLower())).OrderBy(a => a.Title).ToList(); } else { albums = _db.Albums.Where(a => a.Title.ToLower().Contains(title.Trim().ToLower()) && a.Artist.Name.ToLower().Contains(artist.Trim().ToLower())).OrderBy(a => a.Title).ToList(); } JsonResult results = new JsonResult(); results.Data = albums; results.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return results; }
public CommandEntry(Command command, Arguments?arguments) { Command = command.Trim(); Arguments = string.IsNullOrWhiteSpace(arguments) ? null : arguments.Trim(); }
/// <summary> Reads lines from a Reader and adds every non-comment line as an entry to a HashSet (omitting /// leading and trailing whitespace). Every line of the Reader should contain only /// one word. The words need to be in lowercase if you make use of an /// Analyzer which uses LowerCaseFilter (like StandardAnalyzer). /// /// </summary> /// <param name="reader">Reader containing the wordlist /// </param> /// <param name="comment">The string representing a comment. /// </param> /// <returns> A HashSet with the reader's words /// </returns> public static List <string> GetWordSet(System.IO.TextReader reader, System.String comment) { List <string> result = new List <string>(); System.IO.StreamReader br = null; try { System.String word = null; while ((word = reader.ReadLine()) != null) { if (word.StartsWith(comment) == false) { result.Add(word.Trim()); } } } finally { if (br != null) { br.Close(); } } return(result); }
public static object ListConcepto(int jtStartIndex, int jtPageSize, string jtSorting, String TipoTabla,String descripcion) { int indexPage; if (jtStartIndex != 0) { indexPage = jtStartIndex / jtPageSize; } else { indexPage = jtStartIndex; } eTabla o = new eTabla(); bTablaVC tb = new bTablaVC(); o._id_Empresa = 0; o._tipo_Tabla = TipoTabla.Trim(); o._descripcion = descripcion; o._valor = "N"; o._estado = "S"; o._inicio = indexPage; o._fin = jtPageSize; o._order = jtSorting.Substring(1).ToUpper(); int total; List<eTabla> list = tb.GetSelectConcepto(o,out total); return new { Result = "OK", Records = list, TotalRecordCount = total }; }
/// <summary> /// /// </summary> /// <param name="paramValue">#RRGGBB00, RRGGBB00</param> /// <returns>System.Drawing.Color</returns> public static System.Drawing.Color stringToColor(System.String paramValue) { int red; int green; int blue; int a = 0; System.Drawing.Color color; if (paramValue.Length <= 0) { color = System.Drawing.Color.FromName("Red"); } else { if (paramValue[0] == '#') { paramValue = paramValue.Trim('#'); red = (System.Int32.Parse(paramValue.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier)); green = (System.Int32.Parse(paramValue.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier)); blue = (System.Int32.Parse(paramValue.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier)); if (paramValue.Length > 6) { a = (System.Int32.Parse(paramValue.Substring(6, 2), System.Globalization.NumberStyles.AllowHexSpecifier)); } color = System.Drawing.Color.FromArgb(red, green, blue, a); } else { color = System.Drawing.Color.FromName(paramValue); } } return(color); }
// accept either a POINT(X Y) or a "X Y" public point(String ps) { if (ps.StartsWith(geomType, StringComparison.InvariantCultureIgnoreCase)) { // remove point, and matching brackets ps = ps.Substring(geomType.Length); if (ps.StartsWith("(")) { ps = ps.Substring(1); } if (ps.EndsWith(")")) { ps = ps.Remove(ps.Length - 1); } } ps = ps.Trim(); // trim leading and trailing spaces String[] coord = ps.Split(CoordSeparator.ToCharArray()); if (coord.Length == 2) { X = Double.Parse(coord[0]); Y = Double.Parse(coord[1]); } else { throw new WaterOneFlowException("Could not create a point. Coordinates are separated by a space 'X Y'"); } }
/// Client Received data from Server /// </summary> /// <param name="asyn">IAsyncResult</param> public void ClientDataReceived(IAsyncResult asyn) { try { SocketPacket socPacket = (SocketPacket)asyn.AsyncState; int iRx = socPacket.mSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.ASCII.GetDecoder(); int charLen = d.GetChars(socPacket.mDataBuffer, 0, iRx, chars, 0); string data = new System.String(chars); data = data.Trim(); //Logger.TranferDataLog(" Reciep -" + data + "-" + DateTime.Now.ToString()); if (data.Contains("RECEIVE")) { TransferSaleDataToServer.GetScriptAndFlusToDataBase(); } else if (data.Contains("TRANSFER")) // format : TRANSFER -- ra lenh chuyen so lieu { TransferSaleDataToServer.SaveFileAndLog(); } ClientWaitData(); } catch (SocketException ex) { Logger.TranferDataLog("SocketException " + ex.ToString()); ClearConectSocket(); } catch (Exception ex) { isCallRecieptData = true; Logger.TranferDataLog("Error Data ClientDataReceived: " + ex.ToString()); } }
}//AnalyseFile /// <summary> /// getDstFileNameByThrdNum eg. is log contains: [Thrd: 5476] then dest file: ./DstLogPath/Thrd_5476.log /// </summary> /// <param name="strThrdNum"></param> /// <returns></returns> private System.String getDstFileNameByThrdNum(System.String strThrdNum) { System.String strDstFileName = ""; System.String strThrdNumSubStr = ""; int nfindSunStr = -1; //[Thrd: 5476] if (strThrdNum.Length > 0) { nfindSunStr = -1; nfindSunStr = strThrdNum.IndexOf(":"); } if (nfindSunStr > 0) { strThrdNumSubStr = strThrdNum.Substring(nfindSunStr + 1); nfindSunStr = -1; } //remove "]" strThrdNumSubStr = strThrdNumSubStr.Replace("]", " "); //remove " " strThrdNumSubStr = strThrdNumSubStr.Trim(); //./DstLogPath/Thrd_5476.log strDstFileName = m_strDstLogPath + "Thrd_" + strThrdNumSubStr + ".log"; return(strDstFileName); }//AnalyseFile
//! \brief method for exporting object to xml file public Boolean Export ( System.String strPath, TType tObject ) { if ((null == strPath) || (null == tObject)) { return(false); } else if ("" == strPath.Trim()) { return(false); } XmlWriterSettings XmlSetting = new XmlWriterSettings(); XmlSetting.Indent = true; //!< enable indent XmlSetting.IndentChars = " "; //!< using whitespace as indent-chars XmlSetting.OmitXmlDeclaration = true; using (XmlWriter Writer = XmlWriter.Create(strPath, XmlSetting)) { //! create root node Writer.WriteStartElement(XMLRootName); Writer.WriteEndElement(); Writer.Close(); } return(Append(strPath, tObject)); }
/// <summary> Configures the logging to email /// </summary> private void configureEmail() { System.String smtpHost = rsvc.getString(RuntimeConstants.LOGSYSTEM_LOG4J_EMAIL_SERVER); System.String emailFrom = rsvc.getString(RuntimeConstants.LOGSYSTEM_LOG4J_EMAIL_FROM); System.String emailTo = rsvc.getString(RuntimeConstants.LOGSYSTEM_LOG4J_EMAIL_TO); System.String emailSubject = rsvc.getString(RuntimeConstants.LOGSYSTEM_LOG4J_EMAIL_SUBJECT); System.String bufferSize = rsvc.getString(RuntimeConstants.LOGSYSTEM_LOG4J_EMAIL_BUFFER_SIZE); if (smtpHost == null || smtpHost.Trim().Equals("") || emailFrom == null || smtpHost.Trim().Equals("") || emailTo == null || emailTo.Trim().Equals("") || emailSubject == null || emailSubject.Trim().Equals("") || bufferSize == null || bufferSize.Trim().Equals("")) { return; } SMTPAppender appender = new SMTPAppender(); appender.SMTPHost = smtpHost; appender.From = emailFrom; appender.To = emailTo; appender.Subject = emailSubject; appender.BufferSize = System.Int32.Parse(bufferSize); appender.Layout = layout; appender.activateOptions(); logger.addAppender(appender); }
/// <summary> Removes all unecessary whitespace from the given String (intended to be used with Primitive values). /// This includes leading and trailing whitespace, and repeated space characters. Carriage returns, /// line feeds, and tabs are replaced with spaces. /// </summary> protected internal virtual System.String removeWhitespace(System.String s) { s = s.Replace('\r', ' '); s = s.Replace('\n', ' '); s = s.Replace('\t', ' '); bool repeatedSpacesExist = true; while (repeatedSpacesExist) { int loc = s.IndexOf(" "); if (loc < 0) { repeatedSpacesExist = false; } else { System.Text.StringBuilder buf = new System.Text.StringBuilder(); buf.Append(s.Substring(0, (loc) - (0))); buf.Append(" "); buf.Append(s.Substring(loc + 2)); s = buf.ToString(); } } return(s.Trim()); }
// 因为音频播放是异步的,方便及时增加播放后的回调内容 public void addCallbackToEffectClip(System.String clipName = "", callback method = null) { if (method == null) { ProjectUtils.Warn("addCallbackToEffectClip Lost method"); return; } ; // 适配,当 audio 刚刚加入队列时, _effectClipObj 并未被赋值 if (!clipName.Trim().Equals("")) { // 避免同名对象进入而使得 callback 没有成功绑定 for (int i = _effectClipPlayList.Count - 1; i >= 0; i--) { AudioPlayObj obj = _effectClipPlayList[i]; if (obj.clip.name == clipName) { obj.handle += method; return; } } } }
public CentroMedicoDataSet.UsuariosDataTable getUsersByCrit(String criterio) { criterio.Trim(); SqlConnection conexion = new SqlConnection(strConexion); conexion.Open(); StringBuilder query = new StringBuilder(); if (criterio.Equals("")) { query.AppendFormat("select * from usuarios"); } else { query.AppendFormat("select * from usuarios where NssUsuario like '%{0}%' or nombre like '%{0}%' or apellidos like '%{0}%' or direccion like '%{0}%' or localidad like '%{0}%' or telefono like '%{0}%' or dni like '%{0}%' or email like '%{0}%'", criterio); } SqlDataAdapter adapter = new SqlDataAdapter(query.ToString(), conexion); CentroMedicoDataSet.UsuariosDataTable tabla = new CentroMedicoDataSet.UsuariosDataTable(); adapter.Fill(tabla); conexion.Close(); return tabla; }
/// <summary> It loads the pre-analyzed dictionary from data file to the hash table. /// The file format of dictionary should be like this: "ITEM\tCONTENT\n" /// </summary> /// <param name="dictionaryFileName">- the path for the pre-analyzed dictionary file /// </param> /// <throws> UnsupportedEncodingException </throws> /// <throws> FileNotFoundException </throws> /// <throws> IOException </throws> public virtual void readDic(System.String dictionaryFileName) { dictionary.Clear(); System.String str = ""; System.IO.StreamReader in_Renamed = new System.IO.StreamReader( new System.IO.FileStream(dictionaryFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read) , Encoding.UTF8); while ((str = in_Renamed.ReadLine()) != null) { str.Trim(); if (str.Equals("")) { continue; } StringTokenizer tok = new StringTokenizer(str, "\t"); System.String key = tok.NextToken; System.String value_Renamed = ""; while (tok.HasMoreTokens) { value_Renamed += (tok.NextToken + "\n"); } dictionary[key] = value_Renamed.Trim(); } }
private String FormatValue(System.String Text) { Text = Text.Trim(); Text = Text.TrimStart(new Char[] { '.' }); return(Text); }
/// <summary> Loads a text file and adds every line as an entry to a HashSet (omitting /// leading and trailing whitespace). Every line of the file should contain only /// one word. The words need to be in lowercase if you make use of an /// Analyzer which uses LowerCaseFilter (like GermanAnalyzer). /// /// </summary> /// <param name="wordfile">File containing the wordlist /// </param> /// <returns> A HashSet with the file's words /// </returns> public static System.Collections.Hashtable GetWordSet(System.IO.FileInfo wordfile) { System.Collections.Hashtable result = new System.Collections.Hashtable(); System.IO.StreamReader freader = null; System.IO.StreamReader lnr = null; try { freader = new System.IO.StreamReader(wordfile.FullName, System.Text.Encoding.Default); lnr = new System.IO.StreamReader(freader.BaseStream, freader.CurrentEncoding); System.String word = null; while ((word = lnr.ReadLine()) != null) { System.String trimedWord = word.Trim(); result.Add(trimedWord, trimedWord); } } finally { if (lnr != null) { lnr.Close(); } if (freader != null) { freader.Close(); } } return(result); }
public static Uri NormalizeIdentityUrl(String identityUrl) { Uri retVal = null; // To get an iname to fit onto a Uri object, we prefix // with "xri:". This is because Uri object will not allow "xri://". if (identityUrl.StartsWith("xri://")) { identityUrl = identityUrl.Substring("xri://".Length); retVal = new Uri("xri:" + identityUrl); } else if (identityUrl.StartsWith("=") || identityUrl.StartsWith("@")) { retVal = new Uri("xri:" + identityUrl); } else if (!identityUrl.StartsWith("http://")) { retVal = Janrain.OpenId.UriUtil.NormalizeUri(string.Format("http://{0}/", identityUrl.Trim("/".ToCharArray()))); } else { retVal = Janrain.OpenId.UriUtil.NormalizeUri(identityUrl); } return retVal; }
public static String ChangeExtension(String Path,String Ext) { int sindex = Path.LastIndexOf('.'); if (sindex == -1) return Path; return Path.Remove(sindex) + '.' + Ext.Trim(' ', '.').ToLower(); }
public LogOnResultDto LogOn(String username, String password) { LogOnResultDto result = new LogOnResultDto(); result.IsSuccessful = false; username = username.Trim().ToLower(); password = password.Trim(); using (var session = _sessionManager.GetSession()) { if (!String.IsNullOrEmpty(username)) { var results = session.Linq<User>() .Where(u => u.LoweredUsername == username); var user = results.FirstOrDefault(); if (user != null) { if (user.Password == password) { result.IsSuccessful = true; result.UserId = user.Id; } } } } if (!result.IsSuccessful) result.Errors = new String[] { "The username or password is incorrect." }; return result; }
/// <summary> /// Get an array of ints's from a string of comma separated text. /// </summary> /// <param name="format">The way to format this list.</param> /// <param name="str">The string that contains a list of numbers.</param> /// <returns>An array of ints parsed from the string.</returns> public static int[] FromListInt(CSVFormat format, String str) { if (str.Trim().Length == 0) { return new int[0]; } // first count the numbers String[] tok = str.Split(format.Separator); int count = tok.Length; // now allocate an object to hold that many numbers var result = new int[count]; // and finally parse the numbers for (int index = 0; index < tok.Length; index++) { try { String num = tok[index]; int value = int.Parse(num); result[index] = value; } catch (Exception e) { throw new PersistError(e); } } return result; }
public RegistrationValidationResultDto IsRegistrationValid(String username, String password, String email) { var result = new RegistrationValidationResultDto(); result.UserId = Guid.NewGuid().ToString(); var errors = new List<String>(); username = username.Trim(); password = password.Trim(); email = email.Trim(); User user = new User() { Username = username.Trim(), EmailAddress = email.Trim(), Password = password.Trim(), Id = Guid.NewGuid().ToString(), LoweredUsername = username.Trim().ToLower() }; result.IsValid = IsUserValid(user, errors); result.Errors = errors.ToArray(); return result; }
/// <summary> Description of the Method /// /// </summary> /// <returns> Description of the Return Value /// </returns> public override System.String ToString() { buffer.Length = 0; if (fullName.Trim().Equals("")) { fullName = "-, -"; } buffer.Append(fullName); buffer.Append('\t'); buffer.Append(rating); buffer.Append('\t'); buffer.Append(quickRating); buffer.Append('\t'); if (memberNumber.Trim().Equals("")) { memberNumber = "-"; } buffer.Append(memberNumber); buffer.Append('\t'); if (expires.Trim().Equals("")) { expires = "-"; } buffer.Append(expires); buffer.Append('\t'); if (state.Trim().Equals("")) { state = "--"; } buffer.Append(state); return(buffer.ToString()); }
public System.String get_AssigenStrSQL(System.String strSQLLine) { System.String strGet = System.String.Empty; System.String strPartAssigen = System.String.Empty; Int32 nIndex = 0; //std::string strSql = databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, string[] splitStrObject = strSQLLine.Split(new Char[] { '=' }); //std::string strSql //databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, strPartAssigen = splitStrObject[0]; strPartAssigen = strPartAssigen.Trim(); nIndex = strPartAssigen.IndexOf(" "); if (-1 == nIndex) { strGet = strPartAssigen; } else { strGet = strPartAssigen.Substring(nIndex + 1); strGet.Trim(); } return(strGet); }
public EProcessLineType CheckProcessLineType(System.String strLineSrc) { EProcessLineType nProcessLineType = EProcessLineType.EProcessLineType_Copy; System.String strLineSrcTmp = strLineSrc; //lsl -- if line with "//" "/*" begin, then just copy strLineSrcTmp = strLineSrcTmp.Trim(); if (0 == strLineSrcTmp.IndexOf("//") || 0 == strLineSrcTmp.IndexOf("/*")) { nProcessLineType = EProcessLineType.EProcessLineType_Copy; return(nProcessLineType); } if (strLineSrc.Contains(m_strLineKey_strSql_size)) { nProcessLineType = EProcessLineType.EProcessLineType_Disable; return(nProcessLineType); } if (strLineSrc.Contains(m_strLineKey_prepareSQLStatement)) { nProcessLineType = EProcessLineType.EProcessLineType_ConvertToObject; return(nProcessLineType); } nProcessLineType = EProcessLineType.EProcessLineType_Copy; return(nProcessLineType); }//CheckProcessLineType
public System.String get_DatabaseHandle(System.String strSQLLine) { System.String strPartDatabaseSQL = System.String.Empty; System.String strPartDatabase = System.String.Empty; Int32 nIndex = 0; //std::string strSql = databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, string[] splitStrObject = strSQLLine.Split(new Char[] { '=' }); //std::string strSql //databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, strPartDatabaseSQL = splitStrObject[1]; strPartDatabaseSQL = strPartDatabaseSQL.Trim(); nIndex = strPartDatabaseSQL.IndexOf("->"); if (-1 == nIndex) { strPartDatabase = "databaseConnection"; } else { strPartDatabase = strPartDatabaseSQL.Substring(0, nIndex); strPartDatabase = strPartDatabase.Trim(); } return(strPartDatabase); }
/// <summary> It reads the morpheme dictionary file, and initializes the trie structure.</summary> /// <param name="dictionaryFileName">- the file path of the morpheme dictionary /// </param> /// <param name="tagSet">- the morpheme tag set /// </param> /// <throws> IOException </throws> public virtual void read_dic(System.String dictionaryFileName, TagSet tagSet) { System.String str = ""; System.IO.StreamReader in_Renamed = new System.IO.StreamReader( new System.IO.FileStream(dictionaryFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.UTF8); INFO[] info_list = new INFO[255]; for (int i = 0; i < 255; i++) { info_list[i] = new INFO(this); } while ((str = in_Renamed.ReadLine()) != null) { str.Trim(); if (str.Equals("")) { continue; } StringTokenizer tok = new StringTokenizer(str, "\t "); System.String word = tok.NextToken; int isize = 0; while (tok.HasMoreTokens) { System.String data = tok.NextToken; StringTokenizer tok2 = new StringTokenizer(data, "."); System.String curt = tok2.NextToken; int x = tagSet.getTagID(curt); if (x == -1) { System.Console.Error.WriteLine("read_dic:tag error"); continue; } if (tok2.HasMoreTokens) { info_list[isize].phoneme = (short)tagSet.getIrregularID(tok2.NextToken); } else { info_list[isize].phoneme = TagSet.PHONEME_TYPE_ALL; } info_list[isize].tag = x; isize++; } info_list[isize].tag = 0; info_list[isize].phoneme = 0; char[] word3 = Code.toTripleArray(word); for (int i = 0; i < isize; i++) { store(word3, info_list[i]); } } }
/// <summary> /// 去除字符串首尾处的空格、回车、换行符、制表符 /// </summary> public static System.String TBBRTrim(this System.String SourceString) { if (!System.String.IsNullOrEmpty(SourceString)) { return(SourceString.Trim().Trim('\r').Trim('\n').Trim('\t')); } return(System.String.Empty); }
internal static System.String[] matchPrefixedField(System.String prefix, System.String rawText, char endChar, bool trim) { // System.Collections.ArrayList matches = null; // commented by .net follower (http://dotnetfollower.com) System.Collections.Generic.List <Object> matches = null; // added by .net follower (http://dotnetfollower.com) int i = 0; int max = rawText.Length; while (i < max) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf(prefix, i); if (i < 0) { break; } i += prefix.Length; // Skip past this prefix we found to start int start = i; // Found the start of a match here bool done = false; while (!done) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf((System.Char)endChar, i); if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = rawText.Length; done = true; } else if (rawText[i - 1] == '\\') { // semicolon was escaped so continue i++; } else { // found a match if (matches == null) { // matches = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(3)); // lazy init // commented by .net follower (http://dotnetfollower.com) matches = new System.Collections.Generic.List <Object>(3); // lazy init // added by .net follower (http://dotnetfollower.com) } System.String element = unescapeBackslash(rawText.Substring(start, (i) - (start))); if (trim) { element = element.Trim(); } matches.Add(element); i++; done = true; } } } if (matches == null || (matches.Count == 0)) { return(null); } return(toStringArray(matches)); }
/// <summary> /// Convert any string expression to numeric or it's default value (zero). /// </summary> /// <typeparam name="T">Generic return data type</typeparam> /// <param name="s">string expression to be evaluated</param> /// <returns>numeric or zero value</returns> public static T ToDefaultNumber <T>(this System.String s) where T : struct { if (s.Trim().Equals(System.String.Empty)) { return(default(T)); } return((T)Convert.ChangeType(s, typeof(T))); }
public override System.String getVersion(System.String message) { System.String version = parseLeaf(message, "MSH.12", 0); if (version == null || version.Trim().Length == 0) { version = parseLeaf(message, "VID.1", message.IndexOf("MSH.12")); } return(version); }
/// <summary>Read Element named mime-type. </summary> private MimeType ReadMimeType(System.Xml.XmlElement element) { System.String name = null; System.String description = null; MimeType type = null; System.Xml.XmlNamedNodeMap attrs = (System.Xml.XmlAttributeCollection)element.Attributes; for (int i = 0; i < attrs.Count; i++) { System.Xml.XmlAttribute attr = (System.Xml.XmlAttribute)attrs.Item(i); if (attr.Name.Equals("name")) { name = attr.Value; } else if (attr.Name.Equals("description")) { description = attr.Value; } } if ((name == null) || (name.Trim().Equals(""))) { return(null); } try { //System.Diagnostics.Trace.WriteLine("Mime type:" + name); type = new MimeType(name); } catch (MimeTypeException mte) { // Mime Type not valid... just ignore it System.Diagnostics.Trace.WriteLine(mte.ToString() + " ... Ignoring!"); return(null); } type.Description = description; System.Xml.XmlNodeList nodes = element.ChildNodes; for (int i = 0; i < nodes.Count; i++) { System.Xml.XmlNode node = nodes.Item(i); if (System.Convert.ToInt16(node.NodeType) == (short)System.Xml.XmlNodeType.Element) { System.Xml.XmlElement nodeElement = (System.Xml.XmlElement)node; if (nodeElement.Name.Equals("ext")) { ReadExt(nodeElement, type); } else if (nodeElement.Name.Equals("magic")) { ReadMagic(nodeElement, type); } } } return(type); }
public static bool IsNullOrWhiteSpace(this System.String str) { if (str == null) { return(true); } return(str.Trim() == String.Empty); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="defValue"></param> /// <returns></returns> public static int Get(System.String key, int defValue) { System.String theValue = System.Configuration.ConfigurationSettings.AppSettings.Get(key); if (theValue == null) { return(defValue); } return(System.Convert.ToInt16(theValue.Trim())); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="defValue"></param> /// <returns></returns> public static long Get(System.String key, long defValue) { System.String theValue = System.Configuration.ConfigurationManager.AppSettings.Get(key); if (theValue == null) { return(defValue); } return(System.Convert.ToInt32(theValue.Trim())); }
public static System.String RemoveChar(System.String consoleInput) { consoleInput = consoleInput.Replace('(', ' '); consoleInput = consoleInput.Replace(')', ' '); consoleInput = consoleInput.Replace(',', ' '); consoleInput = consoleInput.Trim(); return(consoleInput); }
/* -------------------------- Private methods ---------------------------- */ /// <summary> Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of IpAddresses</summary> private System.Collections.ArrayList createInitialHosts(System.String l) { Tokenizer tok = new Tokenizer(l, ","); System.String t; Address addr; int port; System.Collections.ArrayList retval = new System.Collections.ArrayList(); System.Collections.Hashtable hosts = new System.Collections.Hashtable(); //to be removed later on while (tok.HasMoreTokens()) { try { t = tok.NextToken(); System.String host = t.Substring(0, (t.IndexOf((System.Char) '[')) - (0)); host = host.Trim(); port = System.Int32.Parse(t.Substring(t.IndexOf((System.Char) '[') + 1, (t.IndexOf((System.Char) ']')) - (t.IndexOf((System.Char) '[') + 1))); hosts.Add(host, port); } catch (System.FormatException e) { Stack.NCacheLog.Error("exeption is " + e); } catch (Exception e) { Stack.NCacheLog.Error("TcpPing.createInitialHosts", "Error: " + e.ToString()); throw new Exception("Invalid initial members list"); } } try { System.Collections.IDictionaryEnumerator ide; for (int i = 0; i < port_range; i++) { ide = hosts.GetEnumerator(); while (ide.MoveNext()) { port = Convert.ToInt32(ide.Value); addr = new Address((String)ide.Key, port + i); retval.Add(addr); } } } catch (Exception ex) { Stack.NCacheLog.Error("TcpPing.CreateInitialHosts()", "Error :" + ex); throw new Exception("Invalid initial memebers list"); } return(retval); }
/// <summary> /// 获取一个字符串是否不为空 /// </summary> /// <param name="InputString">原始字符串</param> public static bool IsNotNullOrEmpty(this System.String InputString) { if (InputString != null) { return(!System.String.IsNullOrEmpty(InputString.Trim())); } else { return(false); } }