/// <summary> /// Check if we may use that name - we allow only names like "layout_my_XYZ" /// </summary> /// <param name="mapName">A map name</param> /// <returns>True if valid</returns> public static Boolean IsValidMappingName( String mapName ) { Boolean retVal = true; // for now retVal &= mapName.StartsWith( c_UserMapStartsWith ); retVal &= ( mapName.IndexOfAny( new char[] { ' ', '\t', '\n', '\r', '\0' } ) < 0 ); // make sure we don't have spaces etc. return retVal; }
public nanoPubSubClient(String clientId) { if(clientId.IndexOfAny(new char[] { '#' }) != -1) { throw new Exception("invalid character '#' in client ID"); } this.clientId = clientId; }
public void Write(String s) { if (x != 0) wr.Write("" + Sep); if (s.IndexOfAny(new char[] { Sep, Quote, '\r', '\n' }) < 0) { wr.Write(s); } else { wr.Write(Quote + s.Replace("" + Quote, "" + Quote + Quote) + Quote); } x++; }
/// <summary> /// Определяет, является ли указанное название файла валидным /// </summary> /// <param name="Input"></param> /// <returns></returns> public static Boolean IsValidFilename(String Input) { if (Input.HasVisibleChars() == false) { return false; } if (Input.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { return false; } if (Input.Length > MAX_FILENAME) { return false; } if (Input.EndsWith(" ", StringComparison.InvariantCultureIgnoreCase) == true) { return false; } String part = Input.Trim().Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim(); if (part.IsIn(StringComparison.OrdinalIgnoreCase, FilePathTools.IllegalFilenames) == true) { return false; } return true; }
// Constructor. public DirectoryInfo(String path) { if(path == null) { throw new ArgumentNullException("path"); } else if(path.IndexOfAny(Path.InvalidPathChars) != -1) { throw new ArgumentException (_("IO_InvalidPathname"), "path"); } OriginalPath = path; FullPath = Path.GetFullPath(path); }
private static String a(String arg) { // for function calls just return it. if (arg != null && arg.IndexOfAny("()".ToCharArray()) != -1) { return arg; } // for numbers. int i; if (arg != null && int.TryParse(arg, out i)) { return arg; } // strings return arg == null ? "nil" : "\""+arg+"\""; }
/// <summary> /// Определяет, является ли указанный путь валидным. Поддерживает абсолютные и относительные пути, с названиями файлов и без, а также названия файлов без путей /// </summary> /// <param name="Input"></param> /// <returns></returns> public static Boolean IsValidFilePath(String Input) { if (Input.HasVisibleChars() == false) { return false; } if (Input.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { return false; } if(Input.Length >= MAX_PATH) {return false; } String[] parts = Input.Split(new char[1] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); for (Int32 i = 0; i < parts.Length - 1; i++) { String current = parts[i]; if (i < parts.Length - 1) { if(current.Length >= MAX_DIRECTORYNAME) {return false; } } if (current.HasVisibleChars() == false) { return false; } String first_part = current.Trim().Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0]; if (first_part.Trim().IsIn(StringComparison.OrdinalIgnoreCase, IllegalFilenames) == true) { return false; } } return FilePathTools.IsValidFilename(parts[parts.Length - 1]); }
public Projekt GetProjektViaNumericProjektID(String NumericProjektID) { if (NumericProjektID.IndexOfAny(DataSet.AllNumerics) == -1) return null; if (NumericProjektID.Length > 6) { NumericProjektID = NumericProjektID.Substring(0, 6); } else { String WordUpStartYear = DataSet.WordUpNameID.Substring(6, 2) + "0000"; NumericProjektID = WordUpStartYear.Substring(0, 6 - NumericProjektID.Length) + NumericProjektID; } string SelectStatement = $"Select * from {NativeName} where {NumericProjektIdCol} = '{NumericProjektID}'"; Projekt[] Result = DownloadRows(SelectStatement); if (Result.Length != 1) return null; return Result[0]; }
public static void ExecuteCommand(String command, PSHost host) { Console.WriteLine("Executing command:"); string outputLine = command; int ichNewline = command.IndexOfAny("\r\n".ToCharArray()); if (ichNewline > 0) outputLine = command.Substring(0, ichNewline); Console.WriteLine(outputLine); using (Runspace space = RunspaceFactory.CreateRunspace(host)) { space.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = space; ps.AddScript(command); // Create the output buffer for the results. PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); IAsyncResult async = ps.BeginInvoke(); foreach (PSObject result in ps.EndInvoke(async)) { Console.WriteLine(result.ToString()); } PSDataStreams streams = ps.Streams; if (streams.Error != null) { foreach (ErrorRecord record in streams.Error) { Console.WriteLine(GetMessageFromErrorRecord(record)); throw record.Exception; } } } } }
public static PSDataCollection<PSObject> ExecuteCommand(String command) { Console.WriteLine("Executing command:"); string outputLine = command; int ichNewline = command.IndexOfAny("\r\n".ToCharArray()); if (ichNewline > 0) outputLine = command.Substring(0, ichNewline); Console.WriteLine(outputLine); using (PowerShell ps = PowerShell.Create()) { ps.AddScript(command); IAsyncResult async = ps.BeginInvoke(); PSDataCollection<PSObject> output = ps.EndInvoke(async); foreach (PSObject result in output) { Console.WriteLine(result.ToString()); } return output; } }
/*** Main encode function ***/ /* punycode_encode() converts Unicode to Punycode. The input */ /* is represented as an array of Unicode code points (not code */ /* units; surrogate pairs are not allowed), and the output */ /* will be represented as an array of ASCII code points. The */ /* output string is *not* null-terminated; it will contain */ /* zeros if and only if the input contains zeros. (Of course */ /* the caller can leave room for a terminator and add one if */ /* needed.) The input_length is the number of code points in */ /* the input. The output_length is an in/out argument: the */ /* caller passes in the maximum number of code points that it */ /* can receive, and on successful return it will contain the */ /* number of code points actually output. The case_flags array */ /* holds input_length boolean values, where nonzero suggests that */ /* the corresponding Unicode character be forced to uppercase */ /* after being decoded (if possible), and zero suggests that */ /* it be forced to lowercase (if possible). ASCII code points */ /* are encoded literally, except that ASCII letters are forced */ /* to uppercase or lowercase according to the corresponding */ /* uppercase flags. If case_flags is a null pointer then ASCII */ /* letters are left as they are, and other code points are */ /* treated as if their uppercase flags were zero. The return */ /* value can be any of the punycode_status values defined above */ /* except punycode_bad_input; if not punycode_success, then */ /* output_size and output might contain garbage. */ static String punycode_encode(String unicode) { // 0 length strings aren't allowed if (unicode.Length == 0) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadLabelSize"), "unicode"); Contract.EndContractBlock(); StringBuilder output = new StringBuilder(unicode.Length); int iNextDot = 0; int iAfterLastDot = 0; int iOutputAfterLastDot = 0; // Find the next dot while (iNextDot < unicode.Length) { // Find end of this segment iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot); Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; // Only allowed to have empty . section at end (www.microsoft.com.) if (iNextDot == iAfterLastDot) { // Only allowed to have empty sections as trailing . if (iNextDot != unicode.Length) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadLabelSize"), "unicode"); // Last dot, stop break; } // We'll need an Ace prefix output.Append(M_strAcePrefix); // Everything resets every segment. bool bRightToLeft = false; // Check for RTL. If right-to-left, then 1st & last chars must be RTL BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot); if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic) { // It has to be right to left. bRightToLeft = true; // Check last char int iTest = iNextDot - 1; if (Char.IsLowSurrogate(unicode, iTest)) { iTest--; } eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest); if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic) { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadBidi"), "unicode"); } } // Handle the basic code points int basicCount; int numProcessed = 0; // Num code points that have been processed so far (this segment) for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount); // If we're RTL, we can't have LTR chars if (bRightToLeft && testBidi == BidiCategory.LeftToRight) { // Oops, throw error throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadBidi"), "unicode"); } // If we're not RTL we can't have RTL chars if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft || testBidi == BidiCategory.RightToLeftArabic)) { // Oops, throw error throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadBidi"), "unicode"); } // If its basic then add it if (basic(unicode[basicCount])) { output.Append(encode_basic(unicode[basicCount])); numProcessed++; } // If its a surrogate, skip the next since our bidi category tester doesn't handle it. else if (Char.IsSurrogatePair(unicode, basicCount)) basicCount++; } int numBasicCodePoints = numProcessed; // number of basic code points // Stop if we ONLY had basic code points if (numBasicCodePoints == iNextDot - iAfterLastDot) { // Get rid of xn-- and this segments done output.Remove(iOutputAfterLastDot, M_strAcePrefix.Length); } else { // If it has some non-basic code points the input cannot start with xn-- if (unicode.Length - iAfterLastDot >= M_strAcePrefix.Length && unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals( M_strAcePrefix, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadPunycode"), "unicode"); // Need to do ACE encoding int numSurrogatePairs = 0; // number of surrogate pairs so far // Add a delimiter (-) if we had any basic code points (between basic and encoded pieces) if (numBasicCodePoints > 0) { output.Append(delimiter); } // Initialize the state int n = initial_n; int delta = 0; int bias = initial_bias; // Main loop while (numProcessed < (iNextDot - iAfterLastDot)) { /* All non-basic code points < n have been */ /* handled already. Find the next larger one: */ int j; int m; int test = 0; for (m = maxint, j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1) { test = Char.ConvertToUtf32(unicode, j); if (test >= n && test < m) m = test; } /* Increase delta enough to advance the decoder's */ /* <n,i> state to <m,0>, but guard against overflow: */ delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1)); Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); n = m; for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) { // Make sure we're aware of surrogates test = Char.ConvertToUtf32(unicode, j); // Adjust for character position (only the chars in our string already, some // haven't been processed. if (test < n) { delta++; Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) { // Represent delta as a generalized variable-length integer: int q, k; for (q = delta, k = punycodeBase; ; k += punycodeBase) { int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (q < t) break; Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t"); output.Append(encode_digit(t + (q - t) % (punycodeBase - t))); q = (q - t) / (punycodeBase - t); } output.Append(encode_digit(q)); bias = adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints); delta = 0; numProcessed++; if (IsSupplementary(m)) { numProcessed++; numSurrogatePairs++; } } } ++delta; ++n; Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); } } // Make sure its not too big if (output.Length - iOutputAfterLastDot > M_labelLimit) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadLabelSize"), "unicode"); // Done with this segment, add dot if necessary if (iNextDot != unicode.Length) output.Append('.'); iAfterLastDot = iNextDot + 1; iOutputAfterLastDot = output.Length; } // Throw if we're too long if (output.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadNameSize", M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), "unicode"); // Return our output string return output.ToString(); }
/// <summary>获取显示名,如果描述不存在,则使用名称,否则使用描述前面部分,句号(中英文皆可)、换行分隔</summary> /// <param name="name"></param> /// <param name="description"></param> /// <returns></returns> public virtual String GetDisplayName(String name, String description) { if (String.IsNullOrEmpty(description)) return name; name = description.Trim(); var p = name.IndexOfAny(new Char[] { '.', '。', '\r', '\n' }); // p=0表示符号在第一位,不考虑 if (p > 0) name = name.Substring(0, p).Trim(); name = name.Replace("$", null); name = name.Replace("(", null); name = name.Replace(")", null); name = name.Replace("(", null); name = name.Replace(")", null); name = name.Replace(" ", null); name = name.Replace(" ", null); name = name.Replace("/", "_"); name = name.Replace("\\", "_"); if (name[0] == '_') name = name.Substring(1); return name; }
public static String Escape(String str) { // Optimize for nothing to escape (all parameters are run through this function!) int pos = str.IndexOfAny(new char[] { '=', '&' }); if (pos != -1) { // Escape the string int len = str.Length; char[] charArray = str.ToCharArray(); StringBuilder sb = new StringBuilder(str.Length + 10); // A random guess at max number of escaped chars for (int i = 0; i < str.Length; ++i) { if (charArray[i] == '=') sb.Append("="); else if (charArray[i] == '&') sb.Append("&"); sb.Append(charArray[i]); } return sb.ToString(); } else return str; }
public static String Escape( String str ) { if (str == null) return null; StringBuilder sb = null; int strLen = str.Length; int index; // Pointer into the string that indicates the location of the current '&' character int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed). do { index = str.IndexOfAny( s_escapeChars, newIndex ); if (index == -1) { if (sb == null) return str; else { sb.Append( str, newIndex, strLen - newIndex ); return sb.ToString(); } } else { if (sb == null) sb = new StringBuilder(); sb.Append( str, newIndex, index - newIndex ); sb.Append( GetEscapeSequence( str[index] ) ); newIndex = ( index + 1 ); } } while (true); // no normal exit is possible }
public static bool IsValidAttributeValue( String value ) { if (value == null) return false; return value.IndexOfAny( s_valueIllegalCharacters ) == -1; }
public static bool IsValidText( String text ) { if (text == null) return false; return text.IndexOfAny( s_textIllegalCharacters ) == -1; }
private Type GetTypeNoLock(String className, bool throwOnError, bool ignoreCase) { // public API to to a type. The reason that we need this function override from module // is because clients might need to get foo[] when foo is being built. For example, if // foo class contains a data member of type foo[]. // This API first delegate to the Module.GetType implementation. If succeeded, great! // If not, we have to look up the current module to find the TypeBuilder to represent the base // type and form the Type object for "foo[,]". // Module.GetType() will verify className. Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase); if (baseType != null) return baseType; // Now try to see if we contain a TypeBuilder for this type or not. // Might have a compound type name, indicated via an unescaped // '[', '*' or '&'. Split the name at this point. String baseName = null; String parameters = null; int startIndex = 0; while (startIndex <= className.Length) { // Are there any possible special characters left? int i = className.IndexOfAny(new char[]{'[', '*', '&'}, startIndex); if (i == -1) { // No, type name is simple. baseName = className; parameters = null; break; } // Found a potential special character, but it might be escaped. int slashes = 0; for (int j = i - 1; j >= 0 && className[j] == '\\'; j--) slashes++; // Odd number of slashes indicates escaping. if (slashes % 2 == 1) { startIndex = i + 1; continue; } // Found the end of the base type name. baseName = className.Substring(0, i); parameters = className.Substring(i); break; } // If we didn't find a basename yet, the entire class name is // the base name and we don't have a composite type. if (baseName == null) { baseName = className; parameters = null; } baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&"); if (parameters != null) { // try to see if reflection can find the base type. It can be such that reflection // does not support the complex format string yet! baseType = InternalModule.GetType(baseName, false, ignoreCase); } if (baseType == null) { // try to find it among the unbaked types. // starting with the current module first of all. baseType = FindTypeBuilderWithName(baseName, ignoreCase); if (baseType == null && Assembly is AssemblyBuilder) { // now goto Assembly level to find the type. int size; List<ModuleBuilder> modList; modList = ContainingAssemblyBuilder.m_assemblyData.m_moduleBuilderList; size = modList.Count; for (int i = 0; i < size && baseType == null; i++) { ModuleBuilder mBuilder = modList[i]; baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase); } } if (baseType == null) return null; } if (parameters == null) return baseType; return GetType(parameters, baseType); }
static String[] NormalizeArgument( String arg ) { // Here's where the actual work to convert a given argument from the // .Net "standard" form to the "caspol native" form. String[] retval; char[] colonAndEquals = new char[] { ':', '=' }; // We only convert args that start with a forward slash // Note: this allows you to mix and match the argument styles. if (arg[0] == '/') { int colonIndex = arg.IndexOfAny( colonAndEquals ); if (colonIndex == -1) { // There are no subarguments, so just test the argument // and return it as necessary. retval = new String[1]; String temp = '-' + arg.Substring( 1, arg.Length - 1 ); if (TestArgument( temp )) retval[0] = temp; else retval[0] = arg; return retval; } else { // There are subarguments so it gets a little trickier. char[] commaAndQuote = new char[] { ',', '\"' }; // First, test the first argument to make sure it will be // valid with the change to a dash. String temp = '-' + arg.Substring( 1, colonIndex - 1 ); if (!TestArgument( temp )) { retval = new String[1]; retval[0] = temp; return retval; } // If so, we start a list of the arguments contained within // this single new form argument. ArrayList newArgs = new ArrayList(); newArgs.Add( temp ); String remainingArgs = arg.Substring( colonIndex + 1 ); bool inQuote = false; String intermediateArg = null; // Iterate through the rest of the new form argument // parsing out all the individual arguments. for (;;) { // We handle the quoted case explicitly here, so things get // a little wacky. int commaIndex = remainingArgs.IndexOfAny( commaAndQuote ); if (commaIndex == -1) { if (remainingArgs.Length > 0) { newArgs.Add( remainingArgs ); } break; } else if (remainingArgs[commaIndex] == '\"') { // Here we capture any quotes in the string. If we are in a quote, this newly // discovered quote means the quote is complete and we add the argument // to the list. If not, we are starting a new quote so we reset the intermediate argument. if (inQuote) { newArgs.Add( intermediateArg + (commaIndex == 0 ? "" : remainingArgs.Substring( 0, commaIndex )) ); remainingArgs = remainingArgs.Substring( commaIndex + 1 ); inQuote = false; } else { remainingArgs = remainingArgs.Substring( 1 ); intermediateArg = ""; inQuote = true; } } else if (!inQuote) { // If we are not in a quote, we just add the substring to the // argument list, ignoring consecutive commas. if (commaIndex == 0) { remainingArgs = remainingArgs.Substring( 1 ); } else { newArgs.Add( remainingArgs.Substring( 0, commaIndex ) ); remainingArgs = remainingArgs.Substring( commaIndex + 1 ); } } else { // If we are in a quote, then we want to append everything to the // intermediateArg (including the comma). intermediateArg += remainingArgs.Substring( 0, commaIndex + 1 ); remainingArgs = remainingArgs.Substring( commaIndex + 1 ); } } retval = new String[newArgs.Count]; newArgs.CopyTo( retval ); return retval; } } else { retval = new String[1]; retval[0] = arg; return retval; } }
private static double RFCTimeZoneToGMTBias( String zone ) { String s; if( zone.IndexOfAny( "+-".ToCharArray() ) == 0 ) // +hhmm format { int fact; if( zone.Substring(0, 1) == "-" ) { fact = -1; } else { fact = 1; } s = zone.Substring(1).TrimEnd(); double hh = Math.Min( 23, int.Parse( s.Substring(0, 2) ) ); double mm = Math.Min( 59, int.Parse( s.Substring(2, 2) ) ) / 60; return fact * (hh + mm); } else { // named format s = zone.ToUpper().Trim(); for( int i = 0; i < timeZones; i++ ) { if( ZoneBias[i].Zone.Equals(s) ) { return ZoneBias[i].Bias / 60; } } } return 0.0; }
internal bool MatchSpecifiedWords(String target, bool checkWordBoundary, ref int matchLength) { int valueRemaining = Value.Length - Index; matchLength = target.Length; if (matchLength > valueRemaining || m_info.Compare(Value, Index, matchLength, target, 0, matchLength, CompareOptions.IgnoreCase) !=0) { // Check word by word int targetPosition = 0; // Where we are in the target string int thisPosition = Index; // Where we are in this string int wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition); if (wsIndex == -1) { return false; } do { int segmentLength = wsIndex - targetPosition; if (thisPosition >= Value.Length - segmentLength) { // Subtraction to prevent overflow. return false; } if (segmentLength == 0) { // If segmentLength == 0, it means that we have leading space in the target string. // In that case, skip the leading spaces in the target and this string. matchLength--; } else { // Make sure we also have whitespace in the input string if (!Char.IsWhiteSpace(Value[thisPosition + segmentLength])) { return false; } if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) { return false; } // Advance the input string thisPosition = thisPosition + segmentLength + 1; } // Advance our target string targetPosition = wsIndex + 1; // Skip past multiple whitespace while (thisPosition < Value.Length && Char.IsWhiteSpace(Value[thisPosition])) { thisPosition++; matchLength++; } } while ((wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition)) >= 0); // now check the last segment; if (targetPosition < target.Length) { int segmentLength = target.Length - targetPosition; if (thisPosition > Value.Length - segmentLength) { return false; } if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) { return false; } } } if (checkWordBoundary) { int nextCharIndex = Index + matchLength; if (nextCharIndex < Value.Length) { if (Char.IsLetter(Value[nextCharIndex])) { return (false); } } } return (true); }
static bool includeType(String package,String fullTypeName) { return fullTypeName.StartsWith(package) && (package[package.Length-1] != '.' || fullTypeName.IndexOf('.',package.Length)==-1) && (fullTypeName.IndexOfAny(new char[] {'$','+'})==-1 && fullTypeName.IndexOf("__")==-1 && fullTypeName.IndexOf("PrivateImplementationDetails")==-1); }
//This function parses a string of numbers and operations and treats it as a single level of order of operations (no nested parentheses) //-It essentially just performs the multiplication/divided operations on the first pass condensing the string as it goes, and on the second pass it does addition/subtraction private static String solveString(String equation) { Stack<double> total = new Stack<double>(); char[] symbol = { '+', '-', '*', '/' }; char[] plusOrMinus = { '+', '-' }; char[] timesOrDivide = { '*', '/' }; char[] charEquation = equation.ToCharArray(); for (int i = 0; i < charEquation.Length; i++) { if (equation.IndexOfAny(symbol, i, 1) > -1 && charEquation.GetValue(i + 1).Equals('-')) { charEquation.SetValue('!', i + 1); } } equation = ""; foreach (char i in charEquation) { equation += Convert.ToString(i); } equation = "0+" + equation + "+0"; int num1_Start = 0; int num1_End = 0; int num2_Start = 0; int num2_End = 0; String num1_str = ""; String num2_str = ""; String answer = ""; double num1 = 0; double num2 = 0; int pos = 0; //Position of last + or - operator before current * or / operator double numBuffer = 0; while (equation.IndexOfAny(timesOrDivide) > -1) { pos = LastIndexOfAny(equation, plusOrMinus, 0, equation.IndexOfAny(timesOrDivide)); num1_Start = pos + 1; num1_End = equation.IndexOfAny(timesOrDivide) - 1; num2_Start = equation.IndexOfAny(timesOrDivide) + 1; num2_End = equation.IndexOfAny(symbol, equation.IndexOfAny(timesOrDivide) + 1) - 1; num1_str = equation.Substring(num1_Start, num1_End - num1_Start + 1); num2_str = equation.Substring(num2_Start, num2_End - num2_Start + 1); if (num1_str.IndexOf("!") > -1) { num1_str = num1_str.Replace("!", "-"); } if (num2_str.IndexOf("!") > -1) { num2_str = num2_str.Replace("!", "-"); } num1 = Convert.ToDouble(num1_str); num2 = Convert.ToDouble(num2_str); if (equation.Substring(equation.IndexOfAny(timesOrDivide), 1) == "*") { answer = Convert.ToString(num1 * num2); } else { answer = Convert.ToString(num1 / num2); } if (answer.IndexOf("-") > -1) { answer = answer.Replace("-", "!"); } if (answer.IndexOf("-") > -1) { answer = answer.Replace("-", "!"); } equation = equation.Substring(0, num1_Start) + answer + equation.Substring(num2_End + 1, equation.Length - num2_End - 1); } equation = equation.Insert(0, "+"); while (equation.IndexOfAny(plusOrMinus) > -1) { if (equation.Substring(1, 1).Equals("!")) { if (equation.Substring(0, 1).Equals("+")) { total.Push(Convert.ToDouble("-" + equation.Substring(2, equation.IndexOfAny(plusOrMinus, 1) - 2))); equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1)); } else { total.Push(Convert.ToDouble(equation.Substring(2, equation.IndexOfAny(plusOrMinus, 2) - 2))); equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1)); } } else if (equation.Length > 2) { if (equation.Substring(0, 1).Equals("+")) { total.Push(Convert.ToDouble(equation.Substring(1, equation.IndexOfAny(plusOrMinus, 1) - 1))); equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1)); } else { total.Push(Convert.ToDouble("-" + equation.Substring(1, equation.IndexOfAny(plusOrMinus, 1) - 1))); equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1)); } } else { equation = ""; } } while (total.Count > 0) { numBuffer += total.Pop(); } return Convert.ToString(numBuffer); }
internal static bool HasIllegalCharacters(String path, bool checkAdditional) { Contract.Requires(path != null); if (checkAdditional) { return path.IndexOfAny(InvalidPathCharsWithAdditionalChecks) >= 0; } return path.IndexOfAny(RealInvalidPathChars) >= 0; }
/// <summary> /// POST方法获取页面 /// </summary> /// <param name="url"></param> /// <param name="paramList">格式: a=xxx&b=xxx&c=xxx</param> /// <returns></returns> private static string PostUrl(String url, String paramList) { HttpWebResponse res = null; string strResult = ""; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Proxy = WebRequest.GetSystemWebProxy(); req.Method = "POST"; req.KeepAlive = true; req.ContentType = "application/x-www-form-urlencoded"; //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; CookieContainer cookieCon = new CookieContainer(); req.CookieContainer = cookieCon; StringBuilder UrlEncoded = new StringBuilder(); Char[] reserved = { '?', '=', '&' }; byte[] SomeBytes = null; if (paramList != null) { int i = 0, j; while (i < paramList.Length) { j = paramList.IndexOfAny(reserved, i); if (j == -1) { // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i))); UrlEncoded.Append((paramList.Substring(i, paramList.Length - i))); break; } // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i))); UrlEncoded.Append((paramList.Substring(i, j - i))); UrlEncoded.Append(paramList.Substring(j, 1)); i = j + 1; } SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString()); req.ContentLength = SomeBytes.Length; Stream newStream = req.GetRequestStream(); newStream.Write(SomeBytes, 0, SomeBytes.Length); newStream.Close(); } else { req.ContentLength = 0; } res = (HttpWebResponse)req.GetResponse(); Stream ReceiveStream = res.GetResponseStream(); // Encoding encode = System.Text.Encoding.Default;//GetEncoding("utf-8"); string encodeheader = res.ContentType; string encodestr = System.Text.Encoding.Default.HeaderName; if ((encodeheader.IndexOf("charset=") >= 0) && (encodeheader.IndexOf("charset=GBK") == -1) && (encodeheader.IndexOf("charset=gbk") == -1)) { int i = encodeheader.IndexOf("charset="); encodestr = encodeheader.Substring(i + 8); } Encoding encode = System.Text.Encoding.GetEncoding(encodestr);//GetEncoding("utf-8"); StreamReader sr = new StreamReader(ReceiveStream, encode); Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); strResult += str; count = sr.Read(read, 0, 256); } } catch (Exception e) { strResult = e.ToString(); } finally { if (res != null) { res.Close(); } } return strResult; }
/// <internalonly/> /// <devdoc> /// <para>Searches the current naming container for a control with the specified /// <paramref name="id"/> and an offset to aid in the /// search.</para> /// </devdoc> protected virtual Control FindControl(String id, int pathOffset) { // DevDiv #338426 - Since this is a recursive function, malicious clients can send us an id // which causes a very deep stack dive, resulting in SO (which terminates the worker process). // We avoid this via the following call, which at the time of this writing ensures that at // least 50% of the available stack remains. The check is very quick: < 1 microsecond. RuntimeHelpers.EnsureSufficientExecutionStack(); string childID; EnsureChildControls(); // If we're not the naming container, let it do the job if (!(flags[isNamingContainer])) { Control namingContainer = NamingContainer; if (namingContainer != null) { return namingContainer.FindControl(id, pathOffset); } return null; } // No registered control, demand create the named controls table //call HasControls doesn't ensures _occasionalFields != null if (HasControls()) { EnsureOccasionalFields(); if (_occasionalFields.NamedControls == null) { EnsureNamedControlsTable(); } } if (_occasionalFields == null || _occasionalFields.NamedControls == null) { return null; } // Need to support ':' for V1 backward compatibility. char[] findControlSeparators = { ID_SEPARATOR, LEGACY_ID_SEPARATOR }; // Is it a hierarchical name? int newPathOffset = id.IndexOfAny(findControlSeparators, pathOffset); // If not, handle it here if (newPathOffset == -1) { childID = id.Substring(pathOffset); return _occasionalFields.NamedControls[childID] as Control; } // Get the name of the child, and try to locate it childID = id.Substring(pathOffset, newPathOffset - pathOffset); Control child = _occasionalFields.NamedControls[childID] as Control; // Child doesn't exist: fail if (child == null) return null; return child.FindControl(id, newPathOffset + 1); }
/// <summary> /// ExtractSegmentedReversedUrl /// </summary> /// <param name="key"></param> /// <param name="reversed"></param> /// <param name="srUrl"></param> /// <returns></returns> public SegmentedReversedUrl ExtractSegmentedReversedUrl(String reversedKey, bool reversed) { SegmentedReversedUrl srUrl = null; if (!reversed) { reversedKey = UrlReverser.Reverse(reversedKey); } if (String.IsNullOrEmpty(reversedKey)) { return srUrl; } if (reversedKey.Length < ProtocolPrefixLength) { return srUrl; } String port = null; if (reversedKey[0] == SchemeHttpEncodingSymbol) { } else if (reversedKey[0] == schemeHttpsEncodingSymbol) { } else { return srUrl; } Int32 portEndIndex = reversedKey.IndexOf(PortSpacer); if (portEndIndex == -1 || portEndIndex > (ProtocolPrefixLength) - 1) { portEndIndex = 1 + MaxPortLength; } if (portEndIndex > 1) { port = reversedKey.Substring(1, portEndIndex - 1); } // Start to parse host here Int32 hostStartIndex = ProtocolPrefixLength; if (hostStartIndex >= reversedKey.Length) { return srUrl; } Int32 hostEndIndex = reversedKey.IndexOf(PathDelimeter, hostStartIndex); if (hostEndIndex == -1) { hostEndIndex = reversedKey.Length; } if (hostEndIndex == hostStartIndex) { return srUrl; } String host = reversedKey.Substring(hostStartIndex, hostEndIndex - hostStartIndex); String[] byDot = host.Split(new char[]{HostDelimeter}, StringSplitOptions.RemoveEmptyEntries); Boolean isIP = byDot.Length == 4 && IsIPHost(byDot[0], byDot[1], byDot[2], byDot[3]); int domainEndIndex = hostStartIndex; if (isIP) { domainEndIndex = hostEndIndex; } else if (byDot.Length <= 2) { domainEndIndex = hostEndIndex; } else { // Get domain bool tldfound = false; for (; domainEndIndex < hostEndIndex; ++domainEndIndex) { if (reversedKey[domainEndIndex] != HostDelimeter) { continue; } else { string suspiciousTld = reversedKey.Substring(hostStartIndex, domainEndIndex - hostStartIndex + 1); if (tlds.ContainsKey(suspiciousTld)) { tldfound = true; } else { if (tldfound) { // The sub string up to the last HostDelimeter is the tld // so that the sub string up to here is the domain ++domainEndIndex; break; } } } } // tld prefix not found, so just treat the first two segments as the domain if (!tldfound) { domainEndIndex = hostStartIndex; domainEndIndex += byDot[0].Length + 1 + byDot[1].Length + 1; } } // Find L1Path int L1EndIndex = -1; int L1StartIndex = -1; int UrlEndIndex = reversedKey.Length; if (hostEndIndex == reversedKey.Length) { L1EndIndex = 0; L1StartIndex = 0; UrlEndIndex = 0; } else { L1StartIndex = hostEndIndex; L1EndIndex = reversedKey.IndexOfAny(L1PathDelimeters, L1StartIndex + 1); if (L1EndIndex == -1) { L1EndIndex = L1StartIndex; } ++L1EndIndex; } String domain = reversedKey.Substring(0, domainEndIndex ); String hostSuffix = reversedKey.Substring(domainEndIndex, hostEndIndex - domainEndIndex); String l1PathSuffix = reversedKey.Substring(L1StartIndex, L1EndIndex - L1StartIndex); String urlSuffix = reversedKey.Substring(L1EndIndex, UrlEndIndex - L1EndIndex); // Sanity check for segments // will potentially hurt the performance, so don't use it in production /* if (l1PathSuffix.Length > 0) { Common.Assert(l1PathSuffix[0] == '/', "Assertion failed: L1PathSuffix doesn't start with /, L1PathSuffix = {0}, Key = {1}", l1PathSuffix, reversedKey); Common.Assert(l1PathSuffix[l1PathSuffix.Length - 1] == L1PathDelimeters[0] || l1PathSuffix[l1PathSuffix.Length - 1] == L1PathDelimeters[1], "Assertion failed: L1PathSuffix doesn't end with /, L1PathSuffix = {0}, Key = {1}", l1PathSuffix, reversedKey); } */ srUrl = new SegmentedReversedUrl(domain, hostSuffix, l1PathSuffix, urlSuffix); return srUrl; }
private static void VerifyPath(String path) { if (path != null) { path = path.Trim(); #if !PLATFORM_UNIX if (path.Length > 2 && path.IndexOf( ':', 2 ) != -1) throw new NotSupportedException( Environment.GetResourceString( "Argument_PathFormatNotSupported" ) ); #endif // !PLATFORM_UNIX System.IO.Path.CheckInvalidPathChars(path); if (path.IndexOfAny( m_illegalCharacters ) != -1) throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidPathChars" ) ); } }
public static string getPageOrder(String url, String paramList, string refer) { url = AddRadomTime(url); HttpWebResponse res = null; string strResult = ""; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.KeepAlive = true; req.ContentType = "application/x-www-form-urlencoded"; req.Referer = refer; req.CookieContainer = Config.WebBrowserCookieOrder; StringBuilder UrlEncoded = new StringBuilder(); Char[] reserved = { '?', '=', '&' }; byte[] SomeBytes = null; if (paramList != null) { int i = 0, j; while (i < paramList.Length) { j = paramList.IndexOfAny(reserved, i); if (j == -1) { UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i), Encoding.GetEncoding("GB2312"))); break; } UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(paramList.Substring(i, j - i), Encoding.GetEncoding("GB2312"))); UrlEncoded.Append(paramList.Substring(j, 1)); i = j + 1; } SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString()); req.ContentLength = SomeBytes.Length; Stream newStream = req.GetRequestStream(); newStream.Write(SomeBytes, 0, SomeBytes.Length); newStream.Close(); } else { req.ContentLength = 0; } res = (HttpWebResponse)req.GetResponse(); Stream ReceiveStream = res.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("GB2312"); StreamReader sr = new StreamReader(ReceiveStream, encode); Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); strResult += str; count = sr.Read(read, 0, 256); } } catch (Exception e) { strResult = e.ToString(); } finally { if (res != null) { res.Close(); } } return strResult; }
/// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteAttribute"]/*' /> public override void WriteAttribute(String attribute, String value, bool encode) { // If in analyze mode, we don't actually have to perform the conversion, because // it's not getting written anyway. // If the value is null, we return without writing anything. This is different // from HtmlTextWriter, which writes the name of the attribute, but no value at all. // A name with no value is illegal in Wml. if (value == null) { return; } if (AnalyzeMode) { encode = false; } if (encode) { // Unlike HTML encoding, we need to replace $ with $$, and <> with < and >. // We can't do this by piggybacking HtmlTextWriter.WriteAttribute, because it // would translate the & in < or > to &. So we more or less copy the // ASP.NET code that does similar encoding. Write(' '); Write(attribute); Write("=\""); int cb = value.Length; int pos = value.IndexOfAny(_attributeCharacters); if (pos == -1) { Write(value); } else { char[] s = value.ToCharArray(); int startPos = 0; while (pos < cb) { if (pos > startPos) { Write(s, startPos, pos - startPos); } char ch = s[pos]; switch (ch) { case '\"': Write("""); break; case '&': Write("&"); break; case '<': Write("<"); break; case '>': Write(">"); break; case '$': Write("$$"); break; } startPos = pos + 1; pos = value.IndexOfAny(_attributeCharacters, startPos); if (pos == -1) { Write(s, startPos, cb - startPos); break; } } } Write('\"'); } else { base.WriteAttribute(attribute, value, encode); } }
public static bool IsValidTag( String tag ) { if (tag == null) return false; return tag.IndexOfAny( s_tagIllegalCharacters ) == -1; }