/// <summary> /// Creates a relative path from one file or folder to another. /// </summary> /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param> /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param> /// <returns>The relative path from the start directory to the end path.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> public static string RelativePathTo(string fromDirectory, string toPath) { if(fromDirectory == null) throw new ArgumentNullException("fromDirectory"); if(toPath == null) throw new ArgumentNullException("fromDirectory"); if(System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath)) { if(string.Compare(System.IO.Path.GetPathRoot(fromDirectory), System.IO.Path.GetPathRoot(toPath), true) != 0) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' have different path roots.", fromDirectory, toPath)); } } StringCollection relativePath = new StringCollection(); string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar); string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar); int length = Math.Min(fromDirectories.Length, toDirectories.Length); int lastCommonRoot = -1; // find common root for(int x = 0; x < length; x++) { if(string.Compare(fromDirectories[x], toDirectories[x], true) != 0) break; lastCommonRoot = x; } if(lastCommonRoot == -1) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' do not have a common prefix path.", fromDirectory, toPath)); } // add relative folders in from path for(int x = lastCommonRoot + 1; x < fromDirectories.Length; x++) if(fromDirectories[x].Length > 0) relativePath.Add(".."); // add to folders to path for(int x = lastCommonRoot + 1; x < toDirectories.Length; x++) relativePath.Add(toDirectories[x]); // create relative path string[] relativeParts = new string[relativePath.Count]; relativePath.CopyTo(relativeParts, 0); string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts); return newPath; }
static void Main(string[] args) { if (args.Length != 2) Environment.Exit(1); string ip = args[0]; string hostname = args[1]; try { String hosts = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\drivers\etc\hosts"); string[] lines = File.ReadAllLines(hosts); StringCollection linesToSave = new StringCollection(); foreach (string l in lines) { if (!l.Contains(hostname) && !l.Contains(ip)) { linesToSave.Add(l); } } if (!".".Equals(ip)) linesToSave.Add(ip + "\t" + hostname); lines = new String[linesToSave.Count]; linesToSave.CopyTo(lines, 0); File.WriteAllLines(hosts, lines); } catch (Exception e) { Console.WriteLine("{0}", e); } }
public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[data.Length - 1], 0)); } // As explicit interface implementation Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0)); } }
/// <summary> /// Creates a relative path from one file or folder to another. /// </summary> /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param> /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param> /// <returns>The relative path from the start directory to the end path.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> public static string RelativePathTo(string fromDirectory, string toPath) { if (fromDirectory == null) { throw new ArgumentNullException("fromDirectory"); } if (toPath == null) { throw new ArgumentNullException("fromDirectory"); } if (System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath)) { if (string.Compare(System.IO.Path.GetPathRoot(fromDirectory), System.IO.Path.GetPathRoot(toPath), true) != 0) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' have different path roots.", fromDirectory, toPath)); } } StringCollection relativePath = new StringCollection(); string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar); string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar); int length = Math.Min(fromDirectories.Length, toDirectories.Length); int lastCommonRoot = -1; // find common root for (int x = 0; x < length; x++) { if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0) { break; } lastCommonRoot = x; } if (lastCommonRoot == -1) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' do not have a common prefix path.", fromDirectory, toPath)); } // add relative folders in from path for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++) { if (fromDirectories[x].Length > 0) { relativePath.Add(".."); } } // add to folders to path for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++) { relativePath.Add(toDirectories[x]); } // create relative path string[] relativeParts = new string[relativePath.Count]; relativePath.CopyTo(relativeParts, 0); string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts); return(newPath); }
// Start a process. public bool Start() { ProcessStartInfo.ProcessStartFlags flags; // Validate the start information. if (startInfo == null || startInfo.FileName == String.Empty) { throw new InvalidOperationException (S._("Invalid_ProcessStartInfo")); } flags = startInfo.flags; if ((flags & ProcessStartInfo.ProcessStartFlags.UseShellExecute) != 0) { if ((flags & (ProcessStartInfo.ProcessStartFlags .RedirectStdin | ProcessStartInfo.ProcessStartFlags .RedirectStdout | ProcessStartInfo.ProcessStartFlags .RedirectStderr)) != 0) { // Cannot redirect if using shell execution. throw new InvalidOperationException (S._("Invalid_ProcessStartInfo")); } } // Close the current process information, if any. Close(); // If attempting to start using the current process, // then we want to do "execute over the top" instead, // replacing the current process with a new one. if (IsCurrentProcess(this)) { flags |= ProcessStartInfo.ProcessStartFlags.ExecOverTop; } // Get the environment to use in the new process if it // was potentially modified by the programmer. String[] env = null; if (startInfo.envVars != null) { StringCollection coll = new StringCollection(); IDictionaryEnumerator e = (IDictionaryEnumerator) (startInfo.envVars.GetEnumerator()); while (e.MoveNext()) { coll.Add(((String)(e.Key)).ToUpper(CultureInfo.InvariantCulture) + "=" + ((String)(e.Value))); } env = new String [coll.Count]; coll.CopyTo(env, 0); } // Get the pathname of the program to be executed. String program; if (startInfo.UseShellExecute && startInfo.WorkingDirectory != String.Empty && !Path.IsPathRooted(startInfo.FileName)) { program = Path.Combine(startInfo.WorkingDirectory, startInfo.FileName); } else { program = startInfo.FileName; } // Parse the arguments into a local argv array. String[] args = ProcessStartInfo.ArgumentsToArgV (startInfo.Arguments); argv = new String [args.Length + 1]; argv[0] = program; Array.Copy(args, 0, argv, 1, args.Length); // Start the process. IntPtr stdinHandle; IntPtr stdoutHandle; IntPtr stderrHandle; if (!StartProcess(program, startInfo.Arguments, startInfo.WorkingDirectory, argv, (int)flags, (int)(startInfo.WindowStyle), env, startInfo.Verb, startInfo.ErrorDialogParentHandle, out processHandle, out processID, out stdinHandle, out stdoutHandle, out stderrHandle)) { // Checking errno for error Errno errno = Process.GetErrno(); if (errno != Errno.Success) { throw new Win32Exception(Process.GetErrnoMessage(errno)); } } // Wrap up the redirected I/O streams. if (stdinHandle != SocketMethods.GetInvalidHandle()) { stdin = new StreamWriter (new FileStream(stdinHandle, FileAccess.Write, true)); stdin.AutoFlush = true; } if (stdoutHandle != SocketMethods.GetInvalidHandle()) { stdout = new StreamReader (new FileStream(stdoutHandle, FileAccess.Read, true)); } if (stderrHandle != SocketMethods.GetInvalidHandle()) { stderr = new StreamReader (new FileStream(stderrHandle, FileAccess.Read, true)); } // Add the process to the list of active children. lock (typeof(Process)) { if (children == null) { children = new ArrayList(); } children.Add(this); } return(true); }
private void usingKeyWord(List <string> splitedLine) { // foreach(string s in splitedLine) //MessageBox.Show(splitedLine[0]); if (splitedLine[0] == "using") { string str = ""; for (int i = 1; i < splitedLine.Count; i++) { if (i == 1) { str += splitedLine[1]; } else { str += " " + splitedLine[i]; } } string path = ""; bool flag1 = false; bool flag2 = false; if (str != "" && str[0] == '(' && str[1] == '\'') { for (int i = 2; i < str.Length - 2; i++) { path += str[i]; flag1 = true; } if (str[str.Length - 2] == '\'' && str[str.Length - 1] == ')') { flag2 = true; } //check flags try { if (flag1 == true && flag2 == true) { chosenFile = path; //MessageBox.Show("path is exist:" + chosenFile); StringCollection linesCollection = ReadFileIntoStringCollection(); fileLines = new string[linesCollection.Count]; linesCollection.CopyTo(fileLines, 0); this.richTextBox2.Lines = fileLines; get_tokens(this.fileLines); resultUsingFlag = true; } } catch (FileNotFoundException) { MessageBox.Show("The file is not found in the specified location !"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Error1 in writing sytax of 'using' keyword! "); } } else { MessageBox.Show("Error2 in writing sytax of 'using' keyword! "); } }
public MDL LoadMDL(string path) { StringCollection MATERIALS = new StringCollection(); int offset = 0; int INT_SIZE = sizeof(int); int CHAR_SIZE = sizeof(char); int FLOAT_SIZE = sizeof(float); int VECTOR_SIZE = 12; int MDL_SIZE = 0; if (!File.Exists(path)) { throw new FileNotFoundException(); } byte[] bytes = File.ReadAllBytes(path); MDL_SIZE = bytes.Length; byte[] bID = new byte[INT_SIZE], bVERSION = new byte[INT_SIZE], bCHECKSUM = new byte[INT_SIZE], bNAME = new byte[64], bFLAGS = new byte[INT_SIZE], bBONE_COUNT = new byte[INT_SIZE], bBONE_OFFSET = new byte[INT_SIZE], bBONE_CONTROLLER_COUNT = new byte[INT_SIZE], bBONE_CONTROLLER_OFFSET = new byte[INT_SIZE], bHITBOX_COUNT = new byte[INT_SIZE], bHITBOX_OFFSET = new byte[INT_SIZE], bLOCALANIM_COUNT = new byte[INT_SIZE], bLOCALANIM_OFFSET = new byte[INT_SIZE], bLOCALSEQ_COUNT = new byte[INT_SIZE], bLOCALSEQ_OFFSET = new byte[INT_SIZE], bACTIVITY_LIST_VERSION = new byte[INT_SIZE], bEVENTS_INDEXED = new byte[INT_SIZE], bTEXTURE_COUNT = new byte[INT_SIZE], bTEXTURE_OFFSET = new byte[INT_SIZE]; Array.ConstrainedCopy(bytes, offset, bID, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bVERSION, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bCHECKSUM, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bNAME, 0, 64); offset += CHAR_SIZE * 64; //Skip on the vetrors offset += VECTOR_SIZE; Array.ConstrainedCopy(bytes, offset, bFLAGS, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bBONE_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bBONE_OFFSET, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bBONE_CONTROLLER_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bBONE_CONTROLLER_OFFSET, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bHITBOX_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bHITBOX_OFFSET, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bLOCALANIM_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bLOCALANIM_OFFSET, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bLOCALSEQ_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bLOCALSEQ_OFFSET, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bACTIVITY_LIST_VERSION, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bEVENTS_INDEXED, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bTEXTURE_COUNT, 0, INT_SIZE); offset += INT_SIZE; Array.ConstrainedCopy(bytes, offset, bTEXTURE_OFFSET, 0, INT_SIZE); offset += INT_SIZE; int ID = BitConverter.ToInt32(bID, 0); int VERSION = BitConverter.ToInt32(bVERSION, 0); int CHECKSUM = BitConverter.ToInt32(bCHECKSUM, 0); string NAME = System.Text.Encoding.UTF8.GetString(bNAME); int FLAGS = BitConverter.ToInt32(bFLAGS, 0); int bone_count = BitConverter.ToInt32(bBONE_COUNT, 0); int bone_offset = BitConverter.ToInt32(bBONE_OFFSET, 0); int bonecontroller_count = BitConverter.ToInt32(bBONE_CONTROLLER_COUNT, 0); int bonecontroller_offset = BitConverter.ToInt32(bBONE_CONTROLLER_OFFSET, 0); int hitbox_count = BitConverter.ToInt32(bHITBOX_COUNT, 0); int hitbox_offset = BitConverter.ToInt32(bHITBOX_OFFSET, 0); int localanim_count = BitConverter.ToInt32(bLOCALANIM_COUNT, 0); int localanim_offset = BitConverter.ToInt32(bLOCALANIM_OFFSET, 0); int localseq_count = BitConverter.ToInt32(bLOCALSEQ_COUNT, 0); int localseq_offset = BitConverter.ToInt32(bLOCALSEQ_OFFSET, 0); int activitylistversion = BitConverter.ToInt32(bACTIVITY_LIST_VERSION, 0); int eventsindexed = BitConverter.ToInt32(bEVENTS_INDEXED, 0); int texture_count = BitConverter.ToInt32(bTEXTURE_COUNT, 0); int texture_offset = BitConverter.ToInt32(bTEXTURE_OFFSET, 0); if (verbose) { Console.WriteLine("--------------------[MDL INFO]--------------------"); Console.WriteLine($"Name:{NAME}"); Console.WriteLine($"ID:{ID}"); Console.WriteLine($"Version:{VERSION}"); Console.WriteLine($"Checksum:{CHECKSUM}"); Console.WriteLine($"Flags:{FLAGS}"); Console.WriteLine(); Console.WriteLine("--------------------[MATERIALS]-------------------"); } byte[] btnoffset = new byte[INT_SIZE]; Array.ConstrainedCopy(bytes, texture_offset, btnoffset, 0, INT_SIZE); int texture_names_offset = BitConverter.ToInt32(btnoffset, 0); int texture_names_position = texture_offset + texture_names_offset; int texture_names_size = MDL_SIZE - (texture_offset + texture_names_offset); byte[] texturenames = new byte[texture_names_size]; Array.ConstrainedCopy(bytes, texture_names_position, texturenames, 0, texture_names_size); string[] names = System.Text.Encoding.UTF8.GetString(texturenames).Split('\0'); string materialsPath = "materials\\"; foreach (string name in names.Reverse())//Reversed to get the materials folder first { if (name != "") { if (name.Contains('\\') || name.Contains('/')) { materialsPath = materialsPath + name; } else { MATERIALS.Add(materialsPath + name + ".vmt"); } } } if (verbose) { Console.WriteLine("--------------------------------------------------"); Console.WriteLine(); } var loadedMDL = new MDL(); loadedMDL.name = NAME; loadedMDL.version = VERSION; loadedMDL.checksum = CHECKSUM; loadedMDL.flags = FLAGS; loadedMDL.materials = new string[MATERIALS.Count]; MATERIALS.CopyTo(loadedMDL.materials, 0); return(loadedMDL); }
private DbCommand CrearComandoSelectConFiltroPorId(object dataObject, bool conFiltros) { Type t = dataObject.GetType(); DbCommand cmd = _dbProviderFactory.CreateCommand(); StringCollection fields = new StringCollection(); StringBuilder sbWhere = new StringBuilder(" WHERE "); bool hasCondition = false; //Indicates that there is a WHERE Condition string tableName = ""; IDbDataParameter[] parametros = null; if (conFiltros) { parametros = CrearParametrosParaComando(dataObject, true); } // Get instance of the attribute. Tabla atributoTabla = (Tabla)Attribute.GetCustomAttribute(t, typeof(Tabla)); if (atributoTabla != null) { tableName = atributoTabla.Nombre; } foreach (MethodInfo mi in t.GetMethods()) //Go thru each method of the object { foreach (Attribute att in Attribute.GetCustomAttributes(mi)) //Go thru the attributes for the method { if (typeof(Columna).IsAssignableFrom(att.GetType())) //Checks that the Attribute is of the right type { var dao = (Columna)att; fields.Add(dao.NombreColumna); //Append the Fields if (parametros != null) { foreach (IDbDataParameter parametro in parametros) { if (parametro.Value != null) { if (parametro.ParameterName.Equals(dao.NombreColumna)) { if (hasCondition) { sbWhere.Append(" AND "); } if (parametro.DbType == DbType.String) { sbWhere.AppendFormat("{0} LIKE '%{1}%'", parametro.ParameterName, parametro.Value.ToString().Replace("'", "")); } else { sbWhere.AppendFormat("{0} = {1}", parametro.ParameterName, parametro.Value); } hasCondition = true; //Set the HasCondition flag to true } } } } } } } string[] arrField = new string[fields.Count]; fields.CopyTo(arrField, 0); cmd.CommandText = "SELECT " + string.Join(",", arrField) + " FROM " + tableName + (hasCondition ? sbWhere.ToString() : " "); return(cmd); }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); // Split the xoml files from cs/vb files. StringCollection xomlFiles = new StringCollection(); StringCollection userCodeFiles = new StringCollection(); foreach (string file in allFiles) { if (file.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) { xomlFiles.Add(file); } else { userCodeFiles.Add(file); } } string[] files = new string[xomlFiles.Count]; xomlFiles.CopyTo(files, 0); string[] codeFiles = new string[userCodeFiles.Count]; userCodeFiles.CopyTo(codeFiles, 0); string mscorlibPath = typeof(object).Assembly.Location; ServiceContainer serviceContainer = new ServiceContainer(); MultiTargetingInfo mtInfo = parameters.MultiTargetingInformation; if (mtInfo == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string mscorlibName = Path.GetFileName(mscorlibPath); // Add assembly resolver. ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += resolver.ResolveEventHandler; // prepare service container TypeProvider typeProvider = new TypeProvider(new ServiceContainer()); int mscorlibIndex = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string assemblyPath = parameters.ReferencedAssemblies[i]; if ((mscorlibIndex == -1) && (string.Compare(mscorlibName, Path.GetFileName(assemblyPath), StringComparison.OrdinalIgnoreCase) == 0)) { mscorlibIndex = i; mscorlibPath = assemblyPath; } typeProvider.AddAssemblyReference(assemblyPath); } } // a note about references to mscorlib: // If we found mscorlib in the list of reference assemblies, we should remove it prior to sending it to the CodeDOM compiler. // The CodeDOM compiler would add the right mscorlib [based on the version of the provider we use] and the duplication would // cause a compilation error. // If we didn't found a reference to mscorlib we need to add it to the type-provider, though, so we will support exposing // those known types. if (mscorlibIndex != -1) { parameters.ReferencedAssemblies.RemoveAt(mscorlibIndex); if (string.IsNullOrEmpty(parameters.CoreAssemblyFileName)) { parameters.CoreAssemblyFileName = mscorlibPath; } } else { typeProvider.AddAssemblyReference(mscorlibPath); } serviceContainer.AddService(typeof(ITypeProvider), typeProvider); TempFileCollection intermediateTempFiles = null; string localAssemblyPath = string.Empty; string createdDirectoryName = null; try { using (WorkflowCompilationContext.CreateScope(serviceContainer, parameters)) { parameters.LocalAssembly = GenerateLocalAssembly(files, codeFiles, parameters, results, out intermediateTempFiles, out localAssemblyPath, out createdDirectoryName); if (parameters.LocalAssembly != null) { // WinOE resolver.SetLocalAssembly(parameters.LocalAssembly); // Work around HERE!!! // prepare type provider typeProvider.SetLocalAssembly(parameters.LocalAssembly); typeProvider.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(files, codeFiles, parameters, results, localAssemblyPath); } } } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(String.Empty, -1, -1, ErrorNumbers.Error_UnknownCompilerException.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); } finally { // Delate the temp files. if (intermediateTempFiles != null && parameters.TempFiles.KeepFiles == false) { foreach (string file in intermediateTempFiles) { try { System.IO.File.Delete(file); } catch { } } try { // GenerateLocalAssembly may have created a directory, so let's try to delete it // We can't just delete Path.GetDirectoryName(localAssemblyPath) because it might be the Temp directory. if (createdDirectoryName != null) { Directory.Delete(createdDirectoryName, true); } } catch { } } } return(results); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; string[] destination; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. Copy empty collection into empty array"); iCountTestcases++; destination = new string[values.Length]; for (int i = 0; i < values.Length; i++) { destination[i] = ""; } sc.CopyTo(destination, 0); if( destination.Length != values.Length) { iCountErrors++; Console.WriteLine("Err_0001a, altered array after copying empty collection"); } if (destination.Length == values.Length) { for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (String.Compare(destination[i], "", false) != 0) { iCountErrors++; Console.WriteLine("Err_0001_{0}b, item = \"{1}\" insteead of \"{2}\" after copying empty collection", i, destination[i], ""); } } } Console.WriteLine("2. Copy empty collection into non-empty array"); iCountTestcases++; destination = values; sc.CopyTo(destination, 0); if( destination.Length != values.Length) { iCountErrors++; Console.WriteLine("Err_0002a, altered array after copying empty collection"); } if (destination.Length == values.Length) { for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (String.Compare(destination[i], values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, altered item {0} after copying empty collection", i); } } } Console.WriteLine("3. add simple strings and CopyTo([], 0)"); strLoc = "Loc_003oo"; iCountTestcases++; cnt = sc.Count; sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, values.Length); } destination = new string[values.Length]; sc.CopyTo(destination, 0); for (int i = 0; i < values.Length; i++) { iCountTestcases++; if ( String.Compare(sc[i], destination[i], false) != 0 ) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]); } } Console.WriteLine("4. add simple strings and CopyTo([], {0})", values.Length); sc.Clear(); strLoc = "Loc_004oo"; iCountTestcases++; cnt = sc.Count; sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, values.Length); } destination = new string[values.Length * 2]; sc.CopyTo(destination, values.Length); for (int i = 0; i < values.Length; i++) { iCountTestcases++; if ( String.Compare(sc[i], destination[i+values.Length], false) != 0 ) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, copied \"{1}\" instead of \"{2}\"", i, destination[i+values.Length], sc[i]); } } Console.WriteLine("5. add intl strings and CopyTo([], 0)"); strLoc = "Loc_005oo"; iCountTestcases++; string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } iCountTestcases++; sc.Clear(); sc.AddRange(intlValues); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", sc.Count, intlValues.Length); } destination = new string[intlValues.Length]; sc.CopyTo(destination, 0); for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; if ( String.Compare(sc[i], destination[i], false) != 0 ) { iCountErrors++; Console.WriteLine("Err_0005_{0}b, copied \"{1}\" instead of \"{2}\"", i, destination[i], sc[i]); } } Console.WriteLine("6. add intl strings and CopyTo([], {0})", intlValues.Length); strLoc = "Loc_006oo"; iCountTestcases++; sc.Clear(); sc.AddRange(intlValues); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0006a, count is {0} instead of {1}", sc.Count, intlValues.Length); } destination = new string[intlValues.Length*2]; sc.CopyTo(destination, intlValues.Length); for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; if ( String.Compare(sc[i], destination[i+intlValues.Length], false) != 0 ) { iCountErrors++; Console.WriteLine("Err_0006_{0}b, copied \"{1}\" instead of \"{2}\"", i, destination[i+intlValues.Length], sc[i]); } } Console.WriteLine("7. CopyTo(null, int)"); strLoc = "Loc_007oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0007a, count is {0} instead of {1}", sc.Count, intlValues.Length); } destination = null; try { sc.CopyTo(destination, 0); iCountErrors++; Console.WriteLine("Err_0007b: no exception "); } catch (ArgumentNullException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0007c, unexpected exception: {0}", e.ToString()); } Console.WriteLine("8. CopyTo(string[], -1)"); strLoc = "Loc_008oo"; iCountTestcases++; if (sc.Count != values.Length ) { sc.Clear(); sc.AddRange(values); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0008a, count is {0} instead of {1}", sc.Count, intlValues.Length); } } destination = new string[values.Length]; try { sc.CopyTo(destination, -1); iCountErrors++; Console.WriteLine("Err_0008b: no exception "); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0008c, unexpected exception: {0}", e.ToString()); } Console.WriteLine("9. CopyTo(string[], upperBound+1)"); strLoc = "Loc_009oo"; iCountTestcases++; if (sc.Count != values.Length ) { sc.Clear(); sc.AddRange(values); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0009a, count is {0} instead of {1}", sc.Count, intlValues.Length); } } destination = new string[values.Length]; try { sc.CopyTo(destination, values.Length); iCountErrors++; Console.WriteLine("Err_0009b: no exception "); } catch (ArgumentException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0009c, unexpected exception: {0}", e.ToString()); } Console.WriteLine("10. CopyTo(string[], upperBound+2)"); strLoc = "Loc_010oo"; iCountTestcases++; if (sc.Count != values.Length ) { sc.Clear(); sc.AddRange(values); if ( sc.Count != (intlValues.Length+1) ) { iCountErrors++; Console.WriteLine("Err_0010a, count is {0} instead of {1}", sc.Count, intlValues.Length); } } destination = new string[values.Length]; try { sc.CopyTo(destination, values.Length); iCountErrors++; Console.WriteLine("Err_0010b: no exception "); } catch (ArgumentException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0009c, unexpected exception: {0}", e.ToString()); } Console.WriteLine("11. CopyTo(string[], not_enough_space)"); strLoc = "Loc_011oo"; iCountTestcases++; if (sc.Count != values.Length ) { sc.Clear(); sc.AddRange(values); if ( sc.Count != (intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0011a, count is {0} instead of {1}", sc.Count, intlValues.Length); } } destination = new string[values.Length]; try { sc.CopyTo(destination, values.Length / 2); iCountErrors++; Console.WriteLine("Err_0011b: no exception "); } catch (ArgumentException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0011c, unexpected exception: {0}", e.ToString()); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
private void deleteBookmark(int num) { StringCollection sc = new StringCollection(); FileStream aFile = new FileStream(bookmarkFile, FileMode.Open); StreamReader sr = new StreamReader(aFile); string strLine = sr.ReadLine(); while(strLine != null) { sc.Add(strLine); strLine = sr.ReadLine(); } sr.Close(); aFile.Close(); if (num - 1 > -1) { sc.RemoveAt(num - 1); String[] bookmarks = new String[sc.Count]; sc.CopyTo(bookmarks, 0); File.WriteAllLines(bookmarkFile, bookmarks); } }
/// <summary> /// This is implemented to handle properties related to VEvent items /// </summary> /// <param name="propertyName">The name of the property</param> /// <param name="parameters">A string collection containing the parameters and their values. If empty, /// there are no parameters.</param> /// <param name="propertyValue">The value of the property.</param> protected virtual void VEventParser(string propertyName, StringCollection parameters, string propertyValue) { StringCollection sc; string[] parts, parms; int idx; // The last entry is always CustomProperty so scan for length minus one for(idx = 0; idx < ntvEvent.Length - 1; idx++) if(ntvEvent[idx].IsMatch(propertyName)) break; // An opening BEGIN:VEVENT property must have been seen if(vEvent == null) throw new PDIParserException(this.LineNumber, LR.GetString("ExParseNoBeginProp", "BEGIN:VEVENT", propertyName)); // Handle or create the property switch(ntvEvent[idx].EnumValue) { case PropertyType.Begin: // Handle nested objects priorState.Push(currentState); // Is it an alarm? if(String.Compare(propertyValue.Trim(), "VALARM", StringComparison.OrdinalIgnoreCase) == 0) { vAlarm = new VAlarm(); vEvent.Alarms.Add(vAlarm); currentState = VCalendarParserState.VAlarm; } else { // Unknown/custom object currentState = VCalendarParserState.Custom; CustomObjectParser(propertyName, parameters, propertyValue); } break; case PropertyType.End: // For this, the value must be VEVENT if(String.Compare(propertyValue.Trim(), "VEVENT", StringComparison.OrdinalIgnoreCase) != 0) throw new PDIParserException(this.LineNumber, LR.GetString("ExParseUnrecognizedTagValue", ntvEvent[idx].Name, propertyValue)); // The event is added to the collection when created so we don't have to rely on an END tag // to add it. vEvent = null; currentState = priorState.Pop(); break; case PropertyType.Class: vEvent.Classification.EncodedValue = propertyValue; break; case PropertyType.Categories: // If this is seen more than once, just add the new stuff to the existing property CategoriesProperty cp = new CategoriesProperty(); cp.DeserializeParameters(parameters); cp.EncodedValue = propertyValue; foreach(string s in cp.Categories) vEvent.Categories.Categories.Add(s); break; case PropertyType.Resources: // If this is seen more than once, just add the new stuff to the existing property ResourcesProperty rp = new ResourcesProperty(); rp.DeserializeParameters(parameters); rp.EncodedValue = propertyValue; foreach(string s in rp.Resources) vEvent.Resources.Resources.Add(s); break; case PropertyType.Url: vEvent.Url.DeserializeParameters(parameters); vEvent.Url.EncodedValue = propertyValue; break; case PropertyType.UniqueId: vEvent.UniqueId.EncodedValue = propertyValue; break; case PropertyType.LastModified: vEvent.LastModified.DeserializeParameters(parameters); vEvent.LastModified.EncodedValue = propertyValue; break; case PropertyType.GeographicPosition: vEvent.GeographicPosition.EncodedValue = propertyValue; break; case PropertyType.DateCreated: vEvent.DateCreated.DeserializeParameters(parameters); vEvent.DateCreated.EncodedValue = propertyValue; break; case PropertyType.StartDateTime: vEvent.StartDateTime.DeserializeParameters(parameters); vEvent.StartDateTime.EncodedValue = propertyValue; break; case PropertyType.EndDateTime: vEvent.EndDateTime.DeserializeParameters(parameters); vEvent.EndDateTime.EncodedValue = propertyValue; break; case PropertyType.TimeStamp: vEvent.TimeStamp.DeserializeParameters(parameters); vEvent.TimeStamp.EncodedValue = propertyValue; break; case PropertyType.Summary: vEvent.Summary.DeserializeParameters(parameters); vEvent.Summary.EncodedValue = propertyValue; break; case PropertyType.Description: vEvent.Description.DeserializeParameters(parameters); vEvent.Description.EncodedValue = propertyValue; break; case PropertyType.Location: vEvent.Location.DeserializeParameters(parameters); vEvent.Location.EncodedValue = propertyValue; break; case PropertyType.Priority: vEvent.Priority.DeserializeParameters(parameters); vEvent.Priority.EncodedValue = propertyValue; break; case PropertyType.Sequence: vEvent.Sequence.DeserializeParameters(parameters); vEvent.Sequence.EncodedValue = propertyValue; break; case PropertyType.Transparency: vEvent.Transparency.DeserializeParameters(parameters); vEvent.Transparency.EncodedValue = propertyValue; break; case PropertyType.RecurrenceCount: vEvent.RecurrenceCount.DeserializeParameters(parameters); vEvent.RecurrenceCount.EncodedValue = propertyValue; break; case PropertyType.Comment: // If this is seen more than once, just add the new stuff to the existing property if(vEvent.Comment.Value != null) { vEvent.Comment.EncodedValue += "\r\n"; vEvent.Comment.EncodedValue += propertyValue; } else { vEvent.Comment.DeserializeParameters(parameters); vEvent.Comment.EncodedValue = propertyValue; } break; case PropertyType.Contact: ContactProperty c = new ContactProperty(); c.DeserializeParameters(parameters); c.EncodedValue = propertyValue; vEvent.Contacts.Add(c); break; case PropertyType.Organizer: vEvent.Organizer.DeserializeParameters(parameters); vEvent.Organizer.EncodedValue = propertyValue; break; case PropertyType.Attendee: AttendeeProperty ap = new AttendeeProperty(); ap.DeserializeParameters(parameters); ap.EncodedValue = propertyValue; vEvent.Attendees.Add(ap); break; case PropertyType.RelatedTo: RelatedToProperty rt = new RelatedToProperty(); rt.DeserializeParameters(parameters); rt.EncodedValue = propertyValue; vEvent.RelatedTo.Add(rt); break; case PropertyType.Attachment: AttachProperty att = new AttachProperty(); att.DeserializeParameters(parameters); att.EncodedValue = propertyValue; vEvent.Attachments.Add(att); break; case PropertyType.RecurrenceId: vEvent.RecurrenceId.DeserializeParameters(parameters); vEvent.RecurrenceId.EncodedValue = propertyValue; break; case PropertyType.Status: vEvent.Status.DeserializeParameters(parameters); vEvent.Status.EncodedValue = propertyValue; break; case PropertyType.RequestStatus: RequestStatusProperty rs = new RequestStatusProperty(); rs.DeserializeParameters(parameters); rs.EncodedValue = propertyValue; vEvent.RequestStatuses.Add(rs); break; case PropertyType.Duration: vEvent.Duration.DeserializeParameters(parameters); vEvent.Duration.EncodedValue = propertyValue; break; case PropertyType.AudioAlarm: case PropertyType.DisplayAlarm: case PropertyType.EMailAlarm: case PropertyType.ProcedureAlarm: // These are converted to a VAlarm object vAlarm = new VAlarm(); ParseVCalendarAlarm(ntvEvent[idx].EnumValue, parameters, propertyValue); vEvent.Alarms.Add(vAlarm); vAlarm = null; break; case PropertyType.RecurrenceRule: RRuleProperty rr = new RRuleProperty(); rr.DeserializeParameters(parameters); rr.EncodedValue = propertyValue; vEvent.RecurrenceRules.Add(rr); break; case PropertyType.RecurDate: // There may be more than one date in the value. If so, split them into separate ones. This // makes it easier to manage. They'll get written back out as individual properties but // that's okay. parts = propertyValue.Split(',', ';'); // It's important that we retain the same parameters for each one parms = new string[parameters.Count]; parameters.CopyTo(parms, 0); foreach(string s in parts) { sc = new StringCollection(); sc.AddRange(parms); RDateProperty rd = new RDateProperty(); rd.DeserializeParameters(sc); rd.EncodedValue = s; vEvent.RecurDates.Add(rd); } break; case PropertyType.ExceptionRule: ExRuleProperty er = new ExRuleProperty(); er.DeserializeParameters(parameters); er.EncodedValue = propertyValue; vEvent.ExceptionRules.Add(er); break; case PropertyType.ExceptionDate: // There may be more than one date in the value. If so, split them into separate ones. This // makes it easier to manage. They'll get written back out as individual properties but // that's okay. parts = propertyValue.Split(',', ';'); // It's important that we retain the same parameters for each one parms = new string[parameters.Count]; parameters.CopyTo(parms, 0); foreach(string s in parts) { sc = new StringCollection(); sc.AddRange(parms); ExDateProperty ed = new ExDateProperty(); ed.DeserializeParameters(sc); ed.EncodedValue = s; vEvent.ExceptionDates.Add(ed); } break; case PropertyType.ExcludeStartDateTime: // This is a custom property not defined by the spec vEvent.ExcludeStartDateTime = (propertyValue[0] == '1'); break; default: // Anything else is a custom property CustomProperty cust = new CustomProperty(propertyName); cust.DeserializeParameters(parameters); cust.EncodedValue = propertyValue; vEvent.CustomProperties.Add(cust); break; } }
/// <summary> /// This is implemented to handle properties related to observance rule items in VTimeZone objects /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="parameters">A string collection containing the parameters and their values. If empty, /// there are no parameters.</param> /// <param name="propertyValue">The value of the property.</param> protected virtual void ObservanceRuleParser(string propertyName, StringCollection parameters, string propertyValue) { StringCollection sc; string[] parts, parms; int idx; // The last entry is always CustomProperty so scan for length minus one for(idx = 0; idx < ntvORule.Length - 1; idx++) if(ntvORule[idx].IsMatch(propertyName)) break; // An opening BEGIN:STANDARD or BEGIN:DAYLIGHT property must have been seen. if(obsRule == null) throw new PDIParserException(this.LineNumber, LR.GetString("ExParseNoBeginProp", "BEGIN:STANDARD/BEGIN:DAYLIGHT", propertyName)); // Handle or create the property switch(ntvORule[idx].EnumValue) { case PropertyType.Begin: // Handle unknown nested objects priorState.Push(currentState); currentState = VCalendarParserState.Custom; CustomObjectParser(propertyName, parameters, propertyValue); break; case PropertyType.End: // For this, the value must be STANDARD or DAYLIGHT depending on the rule type if((obsRule.RuleType == ObservanceRuleType.Standard && String.Compare(propertyValue.Trim(), "STANDARD", StringComparison.OrdinalIgnoreCase) != 0) || (obsRule.RuleType == ObservanceRuleType.Daylight && String.Compare(propertyValue.Trim(), "DAYLIGHT", StringComparison.OrdinalIgnoreCase) != 0)) { throw new PDIParserException(this.LineNumber, LR.GetString("ExParseUnrecognizedTagValue", ntvORule[idx].Name, propertyValue)); } // The rule is added to the collection when created so we don't have to rely on an END tag to // add it. obsRule = null; currentState = priorState.Pop(); break; case PropertyType.StartDateTime: obsRule.StartDateTime.DeserializeParameters(parameters); obsRule.StartDateTime.EncodedValue = propertyValue; break; case PropertyType.TimeZoneOffsetFrom: obsRule.OffsetFrom.DeserializeParameters(parameters); obsRule.OffsetFrom.EncodedValue = propertyValue; break; case PropertyType.TimeZoneOffsetTo: obsRule.OffsetTo.DeserializeParameters(parameters); obsRule.OffsetTo.EncodedValue = propertyValue; break; case PropertyType.Comment: // If this is seen more than once, just add the new stuff to the existing property if(obsRule.Comment.Value != null) { obsRule.Comment.EncodedValue += "\r\n"; obsRule.Comment.EncodedValue += propertyValue; } else { obsRule.Comment.DeserializeParameters(parameters); obsRule.Comment.EncodedValue = propertyValue; } break; case PropertyType.RecurrenceRule: RRuleProperty rr = new RRuleProperty(); rr.DeserializeParameters(parameters); rr.EncodedValue = propertyValue; obsRule.RecurrenceRules.Add(rr); break; case PropertyType.RecurDate: // There may be more than one date in the value. If so, split them into separate ones. This // makes it easier to manage. They'll get written back out as individual properties but // that's okay. parts = propertyValue.Split(',', ';'); // It's important that we retain the same parameters for each one parms = new string[parameters.Count]; parameters.CopyTo(parms, 0); foreach(string s in parts) { sc = new StringCollection(); sc.AddRange(parms); RDateProperty rd = new RDateProperty(); rd.DeserializeParameters(sc); rd.EncodedValue = s; obsRule.RecurDates.Add(rd); } break; case PropertyType.TimeZoneName: TimeZoneNameProperty tzn = new TimeZoneNameProperty(); tzn.DeserializeParameters(parameters); tzn.EncodedValue = propertyValue; obsRule.TimeZoneNames.Add(tzn); break; default: // Anything else is a custom property CustomProperty cust = new CustomProperty(propertyName); cust.DeserializeParameters(parameters); cust.EncodedValue = propertyValue; obsRule.CustomProperties.Add(cust); break; } }
/// <summary> /// This is implemented to handle properties related to VFreeBusy items /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="parameters">A string collection containing the parameters and their values. If empty, /// there are no parameters.</param> /// <param name="propertyValue">The value of the property.</param> protected virtual void VFreeBusyParser(string propertyName, StringCollection parameters, string propertyValue) { StringCollection sc; string[] parts, parms; int idx; // The last entry is always CustomProperty so scan for length minus one for(idx = 0; idx < ntvFreeBusy.Length - 1; idx++) if(ntvFreeBusy[idx].IsMatch(propertyName)) break; // An opening BEGIN:VFREEBUSY property must have been seen if(vFreeBusy == null) throw new PDIParserException(this.LineNumber, LR.GetString("ExParseNoBeginProp", "BEGIN:VFREEBUSY", propertyName)); // Handle or create the property switch(ntvFreeBusy[idx].EnumValue) { case PropertyType.Begin: // Handle unknown nested objects priorState.Push(currentState); currentState = VCalendarParserState.Custom; CustomObjectParser(propertyName, parameters, propertyValue); break; case PropertyType.End: // For this, the value must be VFREEBUSY if(String.Compare(propertyValue.Trim(), "VFREEBUSY", StringComparison.OrdinalIgnoreCase) != 0) throw new PDIParserException(this.LineNumber, LR.GetString("ExParseUnrecognizedTagValue", ntvFreeBusy[idx].Name, propertyValue)); // The free/busy item is added to the collection when created so we don't have to rely on an // END tag to add it. vFreeBusy = null; currentState = priorState.Pop(); break; case PropertyType.Url: vFreeBusy.Url.DeserializeParameters(parameters); vFreeBusy.Url.EncodedValue = propertyValue; break; case PropertyType.UniqueId: vFreeBusy.UniqueId.EncodedValue = propertyValue; break; case PropertyType.StartDateTime: vFreeBusy.StartDateTime.DeserializeParameters(parameters); vFreeBusy.StartDateTime.EncodedValue = propertyValue; break; case PropertyType.EndDateTime: vFreeBusy.EndDateTime.DeserializeParameters(parameters); vFreeBusy.EndDateTime.EncodedValue = propertyValue; break; case PropertyType.Duration: vFreeBusy.Duration.DeserializeParameters(parameters); vFreeBusy.Duration.EncodedValue = propertyValue; break; case PropertyType.TimeStamp: vFreeBusy.TimeStamp.DeserializeParameters(parameters); vFreeBusy.TimeStamp.EncodedValue = propertyValue; break; case PropertyType.Comment: // If this is seen more than once, just add the new stuff to the existing property if(vFreeBusy.Comment.Value != null) { vFreeBusy.Comment.EncodedValue += "\r\n"; vFreeBusy.Comment.EncodedValue += propertyValue; } else { vFreeBusy.Comment.DeserializeParameters(parameters); vFreeBusy.Comment.EncodedValue = propertyValue; } break; case PropertyType.Contact: vFreeBusy.Contact.DeserializeParameters(parameters); vFreeBusy.Contact.EncodedValue = propertyValue; break; case PropertyType.Organizer: vFreeBusy.Organizer.DeserializeParameters(parameters); vFreeBusy.Organizer.EncodedValue = propertyValue; break; case PropertyType.Attendee: AttendeeProperty ap = new AttendeeProperty(); ap.DeserializeParameters(parameters); ap.EncodedValue = propertyValue; vFreeBusy.Attendees.Add(ap); break; case PropertyType.RequestStatus: RequestStatusProperty rs = new RequestStatusProperty(); rs.DeserializeParameters(parameters); rs.EncodedValue = propertyValue; vFreeBusy.RequestStatuses.Add(rs); break; case PropertyType.FreeBusy: // There may be more than one period in the value. If so, split them into separate ones. // This makes it easier to manage. They'll get written back out as individual properties but // that's okay. parts = propertyValue.Split(',', ';'); // It's important that we retain the same parameters for each one parms = new string[parameters.Count]; parameters.CopyTo(parms, 0); foreach(string s in parts) { sc = new StringCollection(); sc.AddRange(parms); FreeBusyProperty fb = new FreeBusyProperty(); fb.DeserializeParameters(sc); fb.EncodedValue = s; vFreeBusy.FreeBusy.Add(fb); } break; default: // Anything else is a custom property CustomProperty cust = new CustomProperty(propertyName); cust.DeserializeParameters(parameters); cust.EncodedValue = propertyValue; vFreeBusy.CustomProperties.Add(cust); break; } }
/// <summary> /// Gets the fields within the requested dataset. If dataset is null then the first /// dataset is used. /// </summary> /// <param name="dataSetName"></param> /// <param name="asExpression">When true names are returned as expressions.</param> /// <returns></returns> internal string[] GetFields(string dataSetName, bool asExpression) { XmlNode nodes = DesignXmlDraw.FindNextInHierarchy(_doc.LastChild, "DataSets"); if (nodes == null || !nodes.HasChildNodes) { return(null); } // Find the right dataset XmlNode dataSet = null; foreach (XmlNode ds in nodes.ChildNodes) { if (ds.Name != "DataSet") { continue; } XmlAttribute xAttr = ds.Attributes["Name"]; if (xAttr == null) { continue; } if (xAttr.Value == dataSetName || dataSetName == null || dataSetName == "") { dataSet = ds; break; } } if (dataSet == null) { return(null); } // Find the fields XmlNode fields = DesignXmlDraw.FindNextInHierarchy(dataSet, "Fields"); if (fields == null || !fields.HasChildNodes) { return(null); } StringCollection st = new StringCollection(); foreach (XmlNode f in fields.ChildNodes) { XmlAttribute xAttr = f.Attributes["Name"]; if (xAttr == null) { continue; } if (asExpression) { st.Add(string.Format("=Fields!{0}.Value", xAttr.Value)); } else { st.Add(xAttr.Value); } } if (st.Count <= 0) { return(null); } string[] result = new string[st.Count]; st.CopyTo(result, 0); return(result); }
public static string[] StringCollectionToStringArray(StringCollection collection) { string[] output = new string[collection.Count]; collection.CopyTo(output, 0); return(output); }
public override string[] GetRolesForUser(string username) { SecUtility.CheckParameter(ref username, true, false, true, 255, "username"); if (username.Length < 1) { return(new string[0]); } AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; SqlDataReader reader = null; try { try { int appId = GetApplicationId(holder); int userId = MyConnectionHelper.GetUserID(connection, appId, username, false); if (userId == 0) { return(new string[0]); } SqlCommand command; StringCollection sc = new StringCollection(); String[] strReturn; command = new SqlCommand(@"SELECT RoleName FROM UsersInRoles ur, Roles r " + @"WHERE ur.UserId = @UserId AND ur.RoleId = r.RoleId " + @"ORDER BY RoleName", connection); command.Parameters.Add(new SqlParameter("@UserId", userId)); reader = command.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { sc.Add(reader.GetString(0)); } strReturn = new String[sc.Count]; sc.CopyTo(strReturn, 0); return(strReturn); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { if (reader != null) { reader.Close(); } holder.Close(); } } catch { throw; } }
static void Main(string[] args) { Console.WriteLine("============StringCollection==========="); String[] myArr = new String[] { "red", "orange", "yellow", "green", "blue", "indigo", "violet" }; StringCollection myCol = new StringCollection(); myCol.Add("Apple"); myCol.Add("Orange"); myCol.Add("Mango"); myCol.AddRange(myArr); foreach (var item2 in myCol) { Console.WriteLine(item2); } Console.WriteLine("count of string collection: " + myCol.Count); Console.WriteLine("CopyTo:====="); string[] str1 = new string[myCol.Count]; myCol.CopyTo(str1, 0); foreach (var item1 in str1) { Console.WriteLine(item1); } Console.WriteLine("contains method"); Console.WriteLine(myCol.Contains("Mango")); Console.WriteLine("Insert: dear"); myCol.Insert(5, "dear"); StringEnumerator myEnumerator = myCol.GetEnumerator(); while (myEnumerator.MoveNext()) { Console.WriteLine("{0}", myEnumerator.Current); } Console.WriteLine(); Console.WriteLine("============StringDictionary==========="); StringDictionary myCol1 = new StringDictionary(); myCol1.Add("red", "rojo"); myCol1.Add("green", "verde"); myCol1.Add("blue", "azul"); Console.WriteLine("contains key red :{0}", myCol1.ContainsKey("red")); Console.WriteLine("containe value 'azul': {0}", myCol1.ContainsValue("azul")); Console.WriteLine("remove key------"); myCol1.Remove("red"); IEnumerator myEnumerator1 = myCol1.GetEnumerator(); foreach (DictionaryEntry de in myCol1) { Console.WriteLine("{0} {1}", de.Key, de.Value); } Console.WriteLine(); Console.WriteLine("============ListDictionary==========="); ListDictionary myCol2 = new ListDictionary(); myCol2.Add("Braeburn Apples", "1.49"); myCol2.Add("Fuji Apples", "1.29"); myCol2.Add("Gala Apples", "1.49"); myCol2.Add("Golden Delicious Apples", "1.29"); myCol2.Add("Granny Smith Apples", "0.89"); myCol2.Add("Red Delicious Apples", "0.99"); Console.WriteLine("CopyTo==============="); DictionaryEntry[] myArr1 = new DictionaryEntry[myCol2.Count]; myCol2.CopyTo(myArr1, 0); foreach (var arr1 in myArr1) { Console.WriteLine("{0}-->{1}", arr1.Key, arr1.Value); } Console.WriteLine("Printing the element list using GetEnumerator method-----"); IEnumerator myEnumerator2 = myCol2.GetEnumerator(); foreach (DictionaryEntry de in myCol2) { Console.WriteLine("{0} {1}", de.Key, de.Value); } Console.WriteLine(); Console.WriteLine("============HybridDictionary==========="); HybridDictionary myCol3 = new HybridDictionary(); myCol3.Add("Braeburn Apples", "1.49"); myCol3.Add("Fuji Apples", "1.29"); myCol3.Add("Gala Apples", "1.49"); myCol3.Add("Golden Delicious Apples", "1.29"); myCol3.Add("Granny Smith Apples", "0.89"); myCol3.Add("Red Delicious Apples", "0.99"); myCol3.Add("Plantain Bananas", "1.49"); myCol3.Add("Yellow Bananas", "0.79"); foreach (DictionaryEntry de in myCol3) { Console.WriteLine(" {0,-25} {1}", de.Key, de.Value); } Console.WriteLine(); Console.WriteLine("Number of elements in myDict are :{0} ", myCol3.Count); Console.WriteLine("After Remove======="); myCol3.Remove("Gala Apples"); foreach (DictionaryEntry de in myCol3) { Console.WriteLine(" {0,-25} {1}", de.Key, de.Value); } }
private static WordList Analyze(string input, Regex regex, EncodeMethod encodeMethod) { // analyse // retreive all words in the script MatchCollection all = regex.Matches(input); WordList rtrn; rtrn.Sorted = new StringCollection(); // list of words sorted by frequency rtrn.Protected = new HybridDictionary(); // dictionary of word->encoding rtrn.Encoded = new HybridDictionary(); // instances of "protected" words if (all.Count > 0) { StringCollection unsorted = new StringCollection(); // same list, not sorted HybridDictionary Protected = new HybridDictionary(); // "protected" words (dictionary of word->"word") HybridDictionary values = new HybridDictionary(); // dictionary of charCode->encoding (eg. 256->ff) HybridDictionary count = new HybridDictionary(); // word->count int i = all.Count, j = 0; string word; // count the occurrences - used for sorting later do { word = "$" + all[--i].Value; if (count[word] == null) { count[word] = 0; unsorted.Add(word); // make a dictionary of all of the protected words in this script // these are words that might be mistaken for encoding Protected["$" + (values[j] = encodeMethod(j))] = j++; } // increment the word counter count[word] = (int)count[word] + 1; } while (i > 0); /* prepare to sort the word list, first we must protect * words that are also used as codes. we assign them a code * equivalent to the word itself. * e.g. if "do" falls within our encoding range * then we store keywords["do"] = "do"; * this avoids problems when decoding */ i = unsorted.Count; string[] sortedarr = new string[unsorted.Count]; do { word = unsorted[--i]; if (Protected[word] != null) { sortedarr[(int)Protected[word]] = word.Substring(1); rtrn.Protected[(int)Protected[word]] = true; count[word] = 0; } } while (i > 0); string[] unsortedarr = new string[unsorted.Count]; unsorted.CopyTo(unsortedarr, 0); // sort the words by frequency Array.Sort(unsortedarr, new CountComparer(count)); j = 0; /*because there are "protected" words in the list * we must add the sorted words around them */ do { if (sortedarr[i] == null) { sortedarr[i] = unsortedarr[j++].Substring(1); } rtrn.Encoded[sortedarr[i]] = values[i]; } while (++i < unsortedarr.Length); rtrn.Sorted.AddRange(sortedarr); } return(rtrn); }
/// <summary> /// Convert a path to relative path /// </summary> /// <param name="fromDirectory">Convert from path</param> /// <param name="toPath">To relative path</param> /// <returns>Relative path of the conversion path given</returns> public static string GetRelativePath(string fromDirectory, string toPath) { if (fromDirectory == null) { throw new ArgumentNullException(nameof(fromDirectory)); } if (toPath == null) { throw new ArgumentNullException(nameof(toPath)); } bool flag = Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath); string result; if (flag) { bool flag2 = string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true, CultureInfo.CurrentCulture) != 0; if (flag2) { result = toPath; return(result); } } StringCollection stringCollection = new StringCollection(); string[] array = fromDirectory.Split(new char[] { Path.DirectorySeparatorChar, }); string[] array2 = toPath.Split(new char[] { Path.DirectorySeparatorChar, }); int num = Math.Min(array.Length, array2.Length); int num2 = -1; for (int i = 0; i < num; i++) { if (string.Compare(array[i], array2[i], true, CultureInfo.CurrentCulture) != 0) { break; } num2 = i; } if (num2 == -1) { result = toPath; } else { for (int i = num2 + 1; i < array.Length; i++) { if (array[i].Length > 0) { stringCollection.Add(".."); } } for (int i = num2 + 1; i < array2.Length; i++) { stringCollection.Add(array2[i]); } string[] array3 = new string[stringCollection.Count]; stringCollection.CopyTo(array3, 0); string text = string.Join(Path.DirectorySeparatorChar.ToString(), array3); result = text; } return(result); }
////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// public override string[] FindUsersInRole(string roleName, string usernameToMatch) { SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName"); SecUtility.CheckParameter(ref usernameToMatch, true, true, false, 256, "usernameToMatch"); try { SqlConnectionHolder holder = null; try { holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true); CheckSchemaVersion(holder.Connection); SqlCommand cmd = new SqlCommand("dbo.aspnet_UsersInRoles_FindUsersInRole", holder.Connection); SqlDataReader reader = null; SqlParameter p = new SqlParameter("@ReturnValue", SqlDbType.Int); StringCollection sc = new StringCollection(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = CommandTimeout; p.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(p); cmd.Parameters.Add(CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName)); cmd.Parameters.Add(CreateInputParam("@RoleName", SqlDbType.NVarChar, roleName)); cmd.Parameters.Add(CreateInputParam("@UserNameToMatch", SqlDbType.NVarChar, usernameToMatch)); try { reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { sc.Add(reader.GetString(0)); } } catch { throw; } finally { if (reader != null) { reader.Close(); } } if (sc.Count < 1) { switch (GetReturnValue(cmd)) { case 0: return(new string[0]); case 1: throw new ProviderException(SR.GetString(SR.Provider_role_not_found, roleName)); default: throw new ProviderException(SR.GetString(SR.Provider_unknown_failure)); } } String[] strReturn = new String[sc.Count]; sc.CopyTo(strReturn, 0); return(strReturn); } finally { if (holder != null) { holder.Close(); holder = null; } } } catch { throw; } }
public override string[] GetRolesForUser(string username) { string[] strArray2; SecUtility.CheckParameter(ref username, true, false, true, 0x100, "username"); if (username.Length < 1) { return(new string[0]); } try { SqlConnectionHolder connection = null; try { connection = SqlConnectionHelper.GetConnection(this._sqlConnectionString, true); SqlCommand cmd = new SqlCommand("dbo.aspnet_UsersInRoles_GetRolesForUser", connection.Connection); SqlParameter parameter = new SqlParameter("@ReturnValue", SqlDbType.Int); SqlDataReader reader = null; StringCollection strings = new StringCollection(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = this.CommandTimeout; parameter.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(parameter); cmd.Parameters.Add(this.CreateInputParam("@UserName", SqlDbType.NVarChar, username)); try { reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { strings.Add(reader.GetString(0)); } } catch { throw; } finally { if (reader != null) { reader.Close(); } } if (strings.Count > 0) { string[] array = new string[strings.Count]; strings.CopyTo(array, 0); return(array); } switch (this.GetReturnValue(cmd)) { case 0: return(new string[0]); case 1: return(new string[0]); } throw new ProviderException(Hidistro.Membership.ASPNETProvider.SR.GetString("Stored procedure call failed.")); } finally { if (connection != null) { connection.Close(); connection = null; } } } catch { throw; } return(strArray2); }
private void CopySelectedText() { Point start = new Point(); Point stop = new Point(); Boolean FoundStart = false; Boolean FoundStop = false; // find coordinates of Highlighted Text for (Int32 row = 0; row < this._rows; row++) { for (Int32 col = 0; col < this._cols; col++) { if (FoundStart == false && this.AttribGrid[row][col].IsInverse) { start.X = col; start.Y = row; FoundStart = true; } // this next check will first find the first non-inverse coord with a // character in it. If it happens to be at the beginning of a line, // then we'll back up and stop at the last char in the prev line if (FoundStart && FoundStop == false && this.AttribGrid[row][col].IsInverse == false && this.CharGrid[row][col] != '\0' ) { stop.X = col - 1; stop.Y = row; FoundStop = true; // here we back up if col == 0 if (col == 0) { // make sure we don't have a null row // this shouldn't throw row--; while (this.CharGrid[row][0] == '\0') { row--; } for (col = 0; col < this._cols; col++) // parse the row { if (this.CharGrid[row][col] == '\0') // we found the end { stop.X = col - 1; stop.Y = row; } } } break; } if (FoundStop && FoundStart) { break; } } // column parse // if we get to this point without finding a match, and we're on the last row // we should include the last row and stop here if (FoundStart && FoundStop == false && row == this._rows - 1) { for (Int32 col = 0; col < this._cols; col++) // parse the row { if (this.CharGrid[row][col] == '\0') // we found the end { stop.X = col - 1; stop.Y = row; } } } } // row parse ////Console.WriteLine("start.Y " + Convert.ToString(start.Y) + //// " start.X " + Convert.ToString(start.X) + //// " stop.Y " + Convert.ToString(stop.Y) + //// " stop.X " + Convert.ToString(stop.X)); StringCollection sc = this.ScreenScrape(start.Y, start.X, stop.Y, stop.X); if (sc != null && sc.Count > 0) { string[] lines = new string[sc.Count]; sc.CopyTo(lines, 0); try { Clipboard.SetDataObject(string.Join("\n", lines), false, 5, 10); } catch (Exception) { //MessageBox.Show("Copy Error occured: " + err.ToString()); } } }
static void Main(string[] args) { Console.WriteLine("Dictionary Parts......"); Dictionary <string, string> dt = new Dictionary <string, string>(); // Using Add() method dt.Add("1", "My"); dt.Add("2", "Naame"); dt.Add("3", "Is"); dt.Add("4", "Subhojit"); dt.Add("5", "Paul"); foreach (KeyValuePair <string, string> item in dt) { Console.WriteLine("Key:- {0} and Value:- {1}", item.Key, item.Value); } Console.WriteLine("***********************"); Console.WriteLine("Hashtable Parts...."); Hashtable ht = new Hashtable(); // Using Add() method ht.Add("A1", "to"); ht.Add(2, "score"); ht.Add('C', "70%"); foreach (DictionaryEntry item in ht) { Console.WriteLine("Key:- {0} & Value:- {1} ", item.Key, item.Value); } StringCollection myCol = new StringCollection(); String[] myArr1 = new String[] { "A", "B", "C", "D", "E" }; myCol.AddRange(myArr1); String[] myArr2 = new String[myCol.Count]; myCol.CopyTo(myArr2, 0); Console.WriteLine("*******StringCollection********"); foreach (var item in myArr2) { Console.WriteLine(item); } Console.WriteLine("***********************"); StringDictionary myDict = new StringDictionary(); myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); myDict.Add("E", "Elephant"); Console.WriteLine("*************String Dictionary*******"); foreach (DictionaryEntry dic in myDict) { Console.WriteLine(dic.Key + " " + dic.Value); } Console.WriteLine("***********************"); ListDictionary myDict1 = new ListDictionary(); myDict1.Add("Australia", "Canberra"); myDict1.Add("Belgium", "Brussels"); myDict1.Add("Netherlands", "Amsterdam"); myDict1.Add("China", "Beijing"); myDict1.Add("Russia", "Moscow"); myDict1.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in myDict1 are : " + myDict1.Count); // Displaying the key/value pairs in myDict Console.WriteLine("**********ListDictionary************"); foreach (DictionaryEntry de in myDict1) { Console.WriteLine(de.Key + " " + de.Value); } Console.WriteLine("***********************"); HybridDictionary myDict2 = new HybridDictionary(); myDict2.Add("A", "Hi"); myDict2.Add("B", "Good"); myDict2.Add("C", "Morning"); myDict2.Add("D", "Everyone"); myDict2.Add("E", "How are"); myDict2.Add("F", "you"); DictionaryEntry[] arr = new DictionaryEntry[myDict2.Count]; myDict2.CopyTo(arr, 0); Console.WriteLine("***********HybridDictionary*************"); foreach (DictionaryEntry de in myDict2) { Console.WriteLine(de.Key + " " + de.Value); } //foreach (var item in arr) //{ // Console.WriteLine(item); //} Console.Read(); }
public static void Main() { // Create and initializes a new StringCollection. StringCollection myCol = new StringCollection(); // Add a range of elements from an array to the end of the StringCollection. String[] myArr = new String[] { "RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED" }; myCol.AddRange(myArr); // Display the contents of the collection using foreach. This is the preferred method. Console.WriteLine("Displays the elements using foreach:"); PrintValues1(myCol); // Display the contents of the collection using the enumerator. Console.WriteLine("Displays the elements using the IEnumerator:"); PrintValues2(myCol); // Display the contents of the collection using the Count and Item properties. Console.WriteLine("Displays the elements using the Count and Item properties:"); PrintValues3(myCol); // Add one element to the end of the StringCollection and insert another at index 3. myCol.Add("* white"); myCol.Insert(3, "* gray"); Console.WriteLine("After adding \"* white\" to the end and inserting \"* gray\" at index 3:"); PrintValues1(myCol); // Remove one element from the StringCollection. myCol.Remove("yellow"); Console.WriteLine("After removing \"yellow\":"); PrintValues1(myCol); // Remove all occurrences of a value from the StringCollection. int i = myCol.IndexOf("RED"); while (i > -1) { myCol.RemoveAt(i); i = myCol.IndexOf("RED"); } // Verify that all occurrences of "RED" are gone. if (myCol.Contains("RED")) { Console.WriteLine("*** The collection still contains \"RED\"."); } Console.WriteLine("After removing all occurrences of \"RED\":"); PrintValues1(myCol); // Copy the collection to a new array starting at index 0. String[] myArr2 = new String[myCol.Count]; myCol.CopyTo(myArr2, 0); Console.WriteLine("The new array contains:"); for (i = 0; i < myArr2.Length; i++) { Console.WriteLine(" [{0}] {1}", i, myArr2[i]); } Console.WriteLine(); // Clears the entire collection. myCol.Clear(); Console.WriteLine("After clearing the collection:"); PrintValues1(myCol); }
public override string[] GetRolesForUser(string userName) { string[] strArrays; Util.CheckParameter(ref userName, true, false, true, 256, "userName"); if (userName.Length < 1) { return(new string[0]); } OracleConnectionHolder connection = null; OracleCommand oracleCommand = null; OracleDataReader oracleDataReader = null; try { try { StringCollection stringCollections = new StringCollection(); connection = OracleConnectionHelper.GetConnection(this.m_OracleConnectionString); oracleCommand = new OracleCommand("ora_aspnet_UIR_GetRolesForUser", connection.Connection) { CommandTimeout = this.m_CommandTimeout, CommandType = CommandType.StoredProcedure }; OracleParameter oracleParameter = oracleCommand.Parameters.Add("OutResult", OracleDbType.Int32, ParameterDirection.ReturnValue); oracleParameter.DbType = DbType.Int32; OracleParameter mApplicationName = oracleCommand.Parameters.Add("ApplicationName_", OracleDbType.NVarchar2); mApplicationName.Value = this.m_ApplicationName; oracleCommand.Parameters.Add("UserName_", OracleDbType.NVarchar2).Value = userName; oracleCommand.Parameters.Add("RoleCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output; oracleDataReader = oracleCommand.ExecuteReader(); int value = (int)oracleCommand.Parameters[0].Value; while (oracleDataReader.Read()) { stringCollections.Add(oracleDataReader.GetString(0)); } if (stringCollections.Count >= 1) { string[] strArrays1 = new string[stringCollections.Count]; stringCollections.CopyTo(strArrays1, 0); strArrays = strArrays1; } else { strArrays = new string[0]; } } catch { throw; } } finally { if (oracleDataReader != null) { oracleDataReader.Dispose(); } if (oracleCommand != null) { oracleCommand.Dispose(); } if (connection != null) { connection.Close(); connection = null; } } return(strArrays); }
/// <summary> /// Computes relative path, where path is relative to reference_path /// </summary> /// <param name="reference_path"></param> /// <param name="path"></param> /// <returns></returns> public static string GetRelativePath(string reference_path, string path) { if (reference_path == null) { throw new ArgumentNullException("reference_path"); } if (path == null) { throw new ArgumentNullException("path"); } //reference_path = reference_path.Replace('/', '\\'); //path = path.Replace('/', '\\'); bool isRooted = Path.IsPathRooted(reference_path) && Path.IsPathRooted(path); if (isRooted) { bool isDifferentRoot = string.Compare(Path.GetPathRoot(reference_path), Path.GetPathRoot(path), true) != 0; if (isDifferentRoot) { return(path); } } var relativePath = new StringCollection(); string[] fromDirectories = Regex.Split(reference_path, @"[/\\]+"); string[] toDirectories = Regex.Split(path, @"[/\\]+"); int length = Math.Min(fromDirectories.Length, toDirectories.Length); int lastCommonRoot = -1; // find common root for (int x = 0; x < length; x++) { if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0) { break; } lastCommonRoot = x; } if (lastCommonRoot == -1) { return(string.Join(Path.DirectorySeparatorChar.ToString(), toDirectories)); } // add relative folders in from path for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++) { if (fromDirectories[x].Length > 0) { relativePath.Add(".."); } } // add to folders to path for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++) { relativePath.Add(toDirectories[x]); } // create relative path string[] relativeParts = new string[relativePath.Count]; relativePath.CopyTo(relativeParts, 0); string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts); return(newPath); }
public override string[] GetUsersInRole(string roleName) { string[] strArrays; Util.CheckParameter(ref roleName, true, true, true, 256, "roleName"); OracleConnectionHolder connection = null; OracleCommand oracleCommand = null; OracleDataReader oracleDataReader = null; try { try { StringCollection stringCollections = new StringCollection(); connection = OracleConnectionHelper.GetConnection(this.m_OracleConnectionString); oracleCommand = new OracleCommand("ora_aspnet_UIR_GetUsersInRoles", connection.Connection) { CommandTimeout = this.m_CommandTimeout, CommandType = CommandType.StoredProcedure }; OracleParameter oracleParameter = oracleCommand.Parameters.Add("OutResult", OracleDbType.Int32, ParameterDirection.ReturnValue); oracleParameter.DbType = DbType.Int32; OracleParameter mApplicationName = oracleCommand.Parameters.Add("ApplicationName_", OracleDbType.NVarchar2); mApplicationName.Value = this.m_ApplicationName; oracleCommand.Parameters.Add("RoleName_", OracleDbType.NVarchar2).Value = roleName; oracleCommand.Parameters.Add("UserCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output; oracleDataReader = oracleCommand.ExecuteReader(); int value = (int)oracleCommand.Parameters[0].Value; while (oracleDataReader.Read()) { stringCollections.Add(oracleDataReader.GetString(0)); } if (stringCollections.Count >= 1) { string[] strArrays1 = new string[stringCollections.Count]; stringCollections.CopyTo(strArrays1, 0); strArrays = strArrays1; } else { int num = value; if (num == -3001) { int pROVIDERROLENOTFOUND = ErrRes.PROVIDER_ROLE_NOT_FOUND; string[] strArrays2 = new string[] { roleName }; throw new ProviderException(MsgManager.GetMsg(pROVIDERROLENOTFOUND, strArrays2)); } strArrays = (num != 0 ? new string[0] : new string[0]); } } catch { throw; } } finally { if (oracleDataReader != null) { oracleDataReader.Dispose(); } if (oracleCommand != null) { oracleCommand.Dispose(); } if (connection != null) { connection.Close(); connection = null; } } return(strArrays); }
public static void CopyToTest(StringCollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } }
public void TestLogTransfaseDataTable(FileInfo chosenFile, List <Tlog> tlogs, string zipName) { string fileNameArr = chosenFile.Name.Split('_').First(); List <Tlog> tlogsTest = new List <Tlog>(); LogFileType test; try { if (chosenFile.Name.ToUpper().EndsWith("HTML")) { test = LogFileType.HTML; } else { test = fileNameArr.ToUpper().CastTo <LogFileType>(); } } catch (Exception) { test = LogFileType.OTHER; } try { StringCollection linesCollection = ReadFileIntoStringCollection(chosenFile.FullName); string[] linesArray = new string[linesCollection.Count]; linesCollection.CopyTo(linesArray, 0); int testDate = DateTime.Now.ToString("yyyyMMdd").CastTo <int>(); string sn; switch (test) { case LogFileType.MAIN: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[2]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS")?TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.MAIN, TestReslut = reslut }); } break; case LogFileType.RECEIVERAMPL: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[2]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.RECEIVERAMPL, TestReslut = reslut }); } break; case LogFileType.SEC: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[2]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.SEC, TestReslut = reslut }); } break; case LogFileType.SPEAKERAMPL: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[2]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.SPEAKERAMPL, TestReslut = reslut }); } break; case LogFileType.副麦: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.副麦, TestReslut = reslut }); } break; case LogFileType.听筒: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.听筒, TestReslut = reslut }); } break; case LogFileType.扬声器: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.扬声器, TestReslut = reslut }); } break; case LogFileType.扬声器右: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.扬声器右, TestReslut = reslut }); } break; case LogFileType.扬声器左: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.扬声器左, TestReslut = reslut }); } break; case LogFileType.主麦: foreach (var line in linesArray.Skip(3)) { sn = line.Split('\t')[4]; TestReslut reslut = line.Split('\t')[5].ToUpper().Equals("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.主麦, TestReslut = reslut }); } break; case LogFileType.HTML: sn = fileNameArr; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.HTML, TestReslut = TestReslut.Pass }); break; case LogFileType.OTHER: { sn = fileNameArr; TestReslut reslut = chosenFile.Name.ToUpper().Contains("PASS") ? TestReslut.Pass : TestReslut.Fail; tlogsTest.Add(new Tlog() { Sn = sn, TestDate = testDate, ZipFileName = zipName, LogFileName = chosenFile.Name, Path = chosenFile.FullName, LogFileType = LogFileType.OTHER, TestReslut = reslut }); } break; } } catch (Exception) { throw new Exception("解析文件错误:" + chosenFile.Name); } tlogs.AddRange(tlogsTest); }
public static string BuildColumnFilter(string filterExpression, StringCollection columns) { string[] columnNames = new string[columns.Count]; columns.CopyTo(columnNames, 0); return(BuildColumnFilter(filterExpression, columnNames)); }
/// <summary> /// Parse the arguments for options using the given settings /// </summary> /// <param name="optStyle">What type of options to parse</param> /// <param name="unixShortOption">How to parse unix short options (ignored /// if not unix style parsing)</param> /// <param name="dupOptHandleType">How to handle un-expected duplicate option /// definitions</param> /// <param name="unknownOptHandleType">How to handle options that were not /// defined</param> /// <param name="caseSesitive">If the parsing of options /// should consider the case of the options</param> /// <param name="args">The command-line arguments to parse</param> /// <returns>Arguments from the command-line that were not options</returns> public string[] Parse(OptStyle optStyle, UnixShortOption unixShortOption, DupOptHandleType dupOptHandleType, UnknownOptHandleType unknownOptHandleType, bool caseSesitive, string[] args) { ArrayList foundDefinitions = new ArrayList(); Group grp; Match m; Regex re; StringCollection arguments; bool isShort; bool unknown; string name; string value; string[] results; if (args == null || args.Length == 0) { if (this.SearchEnvironment) { ParseEnvironment(foundDefinitions, caseSesitive); } return(new string[0]); } arguments = new StringCollection(); re = BuildRegEx(optStyle, unixShortOption); for (int i = 0; i < args.Length; i++) { m = re.Match(args[i]); if (m.Success) { // see if there is a value grp = m.Groups["shortname"]; if (grp != null && grp.Value != string.Empty) { isShort = true; name = grp.Value; value = m.Groups["shortvalue"].Value; } else { isShort = false; name = m.Groups["longname"].Value; value = m.Groups["longvalue"].Value; // remove the '=' or ':' at the beginning of the value if (value != null && value.Length > 0) { value = value.Substring(1); } } if (optStyle == OptStyle.Unix) { if (isShort == false) { ParseLongOption(args, name, value, caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknown); } // see if the value is just concatinated short options else if (unixShortOption == UnixShortOption.CollapseShort) { // name is the first option ParseShortOption(args, name[0], null, caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknown); // parse the rest of the options that lie in the 'value' variable if (value != null) { char[] unknownOptions; ParseShortOptions(args, value.ToLower().ToCharArray(), caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknownOptions); // don't do anything with unknown concatinated short options, // they should not be considered options or arguments } } else { // name is the first option ParseShortOption(args, name[0], value, caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknown); } } else { if (name.Length == 1) { ParseShortOption(args, name[0], value, caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknown); } else { ParseLongOption(args, name, value, caseSesitive, ref i, dupOptHandleType, unknownOptHandleType, foundDefinitions, out unknown); } } // consider unknown options to be arguments if (unknown) { arguments.Add(args[i]); } } else { arguments.Add(args[i]); } } // parse the environment if (this.SearchEnvironment) { ParseEnvironment(foundDefinitions, caseSesitive); } results = new string[arguments.Count]; arguments.CopyTo(results, 0); return(results); }
/// <summary> /// Получение списка комманд определенных в сборке /// </summary> /// <param name="asm"></param> /// <param name="markedOnly"></param> /// <returns></returns> private static string[] GetCommands(Assembly asm, bool markedOnly) { StringCollection sc = new StringCollection(); object[] objs = asm.GetCustomAttributes( typeof(Rtm.CommandClassAttribute), true ); Type[] tps; int numTypes = objs.Length; if (numTypes > 0) { tps = new Type[numTypes]; for (int i = 0; i < numTypes; i++) { Rtm.CommandClassAttribute cca = objs[i] as Rtm.CommandClassAttribute; if (cca != null) { tps[i] = cca.Type; } } } else { // If we're only looking for specifically // marked CommandClasses, then use an // empty list if (markedOnly) { tps = new Type[0]; } else { tps = asm.GetExportedTypes(); } } foreach (Type tp in tps) { MethodInfo[] meths = tp.GetMethods(); foreach (MethodInfo meth in meths) { objs = meth.GetCustomAttributes( typeof(Rtm.CommandMethodAttribute), true ); foreach (object obj in objs) { Rtm.CommandMethodAttribute attb = (Rtm.CommandMethodAttribute)obj; sc.Add(attb.GlobalName); } } } string[] ret = new string[sc.Count]; sc.CopyTo(ret, 0); return(ret); }
} // FormatSafeInvariant // ---------------------------------------------------------------------- /// <summary> /// Splits a string in the same way as the System.String.Split() method but /// with support for special treatment for escaped characters and for quoted /// sections which won't be split. /// </summary> /// <remarks> /// Escaping supports the following special treatment: /// <list type="bullet"> /// <item>escape is followed by 'n': a new line character is inserted</item> /// <item>escape is followed by 'r': a form feed character is inserted</item> /// <item>escape is followed by 't': a tabulator character is inserted</item> /// <item>escape is followed by 'x': the next two characters are interpreted /// as a hex code of the character to be inserted</item> /// <item>any other character after the escape is inserted literally</item> /// </list> /// Escaping is applied within and outside of quoted sections. /// </remarks> /// <param name="toSplit">the string to split</param> /// <param name="quote">the quoting character, e.g. '"'</param> /// <param name="escape">an escaping character to use both within and outside /// of quoted sections, e.g. '\\'</param> /// <param name="includeEmptyUnquotedSections">whether to return zero-length sections /// outside of quotations or not. empty sections adjacent to a quoted section are /// never returned.</param> /// <param name="separator">the separator character(s) which will be used to /// split the string outside of quoted sections</param> /// <returns>the array of sections into which the string has been split up. /// never null but possibly empty.</returns> public static string[] SplitQuoted(string toSplit, char quote, char escape, bool includeEmptyUnquotedSections, params char[] separator) { if (toSplit == null) { throw new ArgumentNullException("toSplit"); } if (separator == null || separator.Length == 0) { throw new ArgumentNullException("separator"); } string separators = new string( separator ); if (separators.IndexOf(quote) >= 0 || separators.IndexOf(escape) >= 0) { throw new ArgumentException(Strings.StringToolSeparatorIncludesQuoteOrEscapeChar, "separator"); } StringCollection sections = new StringCollection(); StringBuilder section = null; int length = toSplit.Length; bool inQuotedSection = false; for (int i = 0; i < length; i++) { char c = toSplit[i]; if (c == escape) { if (i < length - 1) { if (section == null) { section = new StringBuilder(); } i++; c = toSplit[i]; switch (c) { case 'n': section.Append('\n'); break; case 'r': section.Append('\r'); break; case 't': section.Append('\t'); break; case 'x': if (i < length - 2) { int upperHexNibble = GetHexValue(toSplit[i + 1]) * 16; int lowerHexNibble = GetHexValue(toSplit[i + 2]); char hexChar = (char)(upperHexNibble + lowerHexNibble); section.Append(hexChar); i += 2; } else { throw new ArgumentException(Strings.StringToolMissingEscapedHexCode, "toSplit"); } break; default: section.Append(c); break; } } else { throw new ArgumentException(Strings.StringToolMissingEscapedChar, "toSplit"); } } else if (c == quote) { if (section != null) { sections.Add(section.ToString()); section = null; } else if (inQuotedSection) { sections.Add(string.Empty); } inQuotedSection = !inQuotedSection; } else if (separators.IndexOf(c) >= 0) { if (inQuotedSection) { if (section == null) { section = new StringBuilder(); } section.Append(c); } else { if (section != null) { sections.Add(section.ToString()); section = null; } else if (includeEmptyUnquotedSections) { if (i == 0 || separators.IndexOf(toSplit[i - 1]) >= 0) { sections.Add(string.Empty); } } } } else { if (section == null) { section = new StringBuilder(); } section.Append(c); } } if (inQuotedSection) { throw new ArgumentException(Strings.StringToolUnbalancedQuotes, "toSplit"); } if (section != null) { sections.Add(section.ToString()); } string[] sectionArray = new string[sections.Count]; sections.CopyTo(sectionArray, 0); return(sectionArray); } // SplitQuoted
/// <summary></summary> public string BuildSelectWithFilters(List <Attribute> inList, string searchSql) { // validate the input list if (inList == null || inList.Count < 1) { return(null); } StringCollection fields = new StringCollection(); StringCollection joins = new StringCollection(); StringCollection tables = new StringCollection(); //parse search sql ParseJoinsFromSql(ref joins, ref tables, searchSql); // iterate all the attributes foreach (Attribute attr in inList) { Entity curPar = attr.Parent; // get all the table names above this attribute while (curPar != null) { if (curPar.DataSource != null && !tables.Contains(curPar.DataSource)) { tables.Add(curPar.DataSource); } curPar = curPar.Parent; } // construct join strings curPar = attr.Parent; while (curPar != null && !curPar.IsRoot()) { string join = String.Format("{0}.{1} = ", curPar.DataSource, curPar.FkField); join += String.Format("{0}.{1}", curPar.Parent.DataSource, curPar.ParentIdField); joins.Add(join); curPar = curPar.Parent; } // finally add the fields //string x = @""; fields.Add(String.Format("{0}.{1} {2}", attr.Parent.DataSource, attr.DataSource, @"""" + attr.DisplayText + @"""")); //fields.Add(String.Format("{0}.{1}", attr.Parent.DataSource, attr.DataSource)); } // build the sql // select string separator = ", "; StringBuilder sql = new StringBuilder(); string sqlSelect = string.Empty; string[] sSelect = new string[fields.Count]; fields.CopyTo(sSelect, 0); sqlSelect = string.Join(separator, sSelect); sql.AppendFormat("SELECT DISTINCT {0} ", sqlSelect); //from string sqlFrom = string.Empty; string[] sFrom = new string[tables.Count]; tables.CopyTo(sFrom, 0); sqlFrom = string.Join(separator, sFrom); sql.AppendFormat("FROM {0} ", sqlFrom); //where if (joins.Count > 0) { string sqlWhere = string.Empty; separator = " AND "; string[] sWhere = new string[joins.Count]; joins.CopyTo(sWhere, 0); sqlWhere = string.Join(separator, sWhere); sql.AppendFormat("WHERE {0}", sqlWhere); } // close out and return the statement return(sql.ToString().Trim()); }
public override string[] GetUsersInRole(string roleName) { string[] strArray2; SecUtility.CheckParameter(ref roleName, true, true, true, 0x100, "roleName"); try { SqlConnectionHolder connection = null; try { connection = SqlConnectionHelper.GetConnection(this._sqlConnectionString, true); this.CheckSchemaVersion(connection.Connection); SqlCommand cmd = new SqlCommand("dbo.aspnet_UsersInRoles_GetUsersInRoles", connection.Connection); SqlDataReader reader = null; SqlParameter parameter = new SqlParameter("@ReturnValue", SqlDbType.Int); StringCollection strings = new StringCollection(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = this.CommandTimeout; parameter.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(parameter); cmd.Parameters.Add(this.CreateInputParam("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName)); cmd.Parameters.Add(this.CreateInputParam("@RoleName", SqlDbType.NVarChar, roleName)); try { reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { strings.Add(reader.GetString(0)); } } catch { throw; } finally { if (reader != null) { reader.Close(); } } if (strings.Count < 1) { switch (this.GetReturnValue(cmd)) { case 0: return(new string[0]); case 1: throw new ProviderException(System.Web.SR.GetString("Provider_role_not_found", new object[] { roleName })); } throw new ProviderException(System.Web.SR.GetString("Provider_unknown_failure")); } string[] array = new string[strings.Count]; strings.CopyTo(array, 0); strArray2 = array; } finally { if (connection != null) { connection.Close(); connection = null; } } } catch { throw; } return(strArray2); }
private DbCommand CrearComandoInsert(object dataObject) { Type type = dataObject.GetType(); DbCommand cmd = _dbProviderFactory.CreateCommand(); string tableName = ""; IDbDataParameter[] parametros = CrearParametrosParaComando(dataObject, false); StringCollection campos = new StringCollection(); StringCollection valores = new StringCollection(); Tabla atributoTabla = (Tabla)Attribute.GetCustomAttribute(type, typeof(Tabla)); if (atributoTabla != null) { tableName = atributoTabla.Nombre; } foreach (MethodInfo mi in type.GetMethods()) //Go thru each method of the object { foreach (Attribute att in Attribute.GetCustomAttributes(mi)) //Go thru the attributes for the method { if (typeof(Columna).IsAssignableFrom(att.GetType())) //Checks that the Attribute is of the right type { var dao = (Columna)att; if (dao.LlavePrimaria == false) { campos.Add(dao.NombreColumna); //Append the Fields foreach (IDbDataParameter parametro in parametros) { if (parametro.ParameterName.Equals(dao.NombreColumna)) {//////////////////////////////PREGUNTAR POR PARAMETRO TIPO STRING!!!!!!!!!!! if (parametro.Value == null) { valores.Add("''"); //sbValues.AppendFormat("{0}, ", "''"); } else { valores.Add(parametro.Value.ToString()); //sbValues.AppendFormat("{0}, ", parametro.Value); } } } } else { if (dao.Filtro == true) { campos.Add(dao.NombreColumna); //Append the Fields foreach (IDbDataParameter parametro in parametros) { if (parametro.ParameterName.Equals(dao.NombreColumna)) {//////////////////////////////PREGUNTAR POR PARAMETRO TIPO STRING!!!!!!!!!!! if (parametro.Value == null) { valores.Add("''"); } else { valores.Add(parametro.Value.ToString()); } } } } } } } } string[] arrCampos = new string[campos.Count]; string[] arrValores = new string[valores.Count]; campos.CopyTo(arrCampos, 0); valores.CopyTo(arrValores, 0); cmd.CommandText = "INSERT INTO " + tableName + "(" + string.Join(",", arrCampos) + ")" + " VALUES " + "(" + string.Join(",", arrValores) + ")"; return(cmd); }
// // Private // private void SetNativeCompilerOutput(StringCollection oNativeCompilerOutput) { m_NativeCompilerOutput = new string[oNativeCompilerOutput.Count]; oNativeCompilerOutput.CopyTo(m_NativeCompilerOutput, 0); }
/// <summary> /// Creates a relative path from one file or folder to another. /// </summary> /// <param name="toPath"> /// Contains the path that defines the endpoint of the relative path. /// </param> /// <returns> /// The relative path from the start directory to the end path. /// </returns> /// <exception cref="ArgumentNullException">Occurs when the toPath is NULL</exception> //http://weblogs.asp.net/pwelter34/archive/2006/02/08/create-a-relative-path-code-snippet.aspx public static string RelativePathTo(string toPath) { string fromDirectory = Directory.GetCurrentDirectory(); if (toPath == null) { throw new ArgumentNullException("toPath"); } if (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath)) { if (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0) { return(toPath); } } StringCollection relativePath = new StringCollection(); string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar); string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar); int length = Math.Min(fromDirectories.Length, toDirectories.Length); int lastCommonRoot = -1; // find common root for (int x = 0; x < length; x++) { if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0) { break; } lastCommonRoot = x; } if (lastCommonRoot == -1) { return(toPath); } // add relative folders in from path for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++) { if (fromDirectories[x].Length > 0) { relativePath.Add(".."); } } // add to folders to path for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++) { relativePath.Add(toDirectories[x]); } // create relative path string[] relativeParts = new string[relativePath.Count]; relativePath.CopyTo(relativeParts, 0); return(string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts)); }
private static string[] ReadResponseFile(string strFileName){ FileStream inputStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.Read); Int64 size = inputStream.Length; if (size == 0) return null; StreamReader reader = new StreamReader(inputStream); string curLineArgs = reader.ReadLine(); // This regular expression is: blank*(nonblanks|stringLiteral)+ string strReArgs = "\\s*([^\\s\\\"]|(\\\"[^\\\"\\n]*\\\"))+"; Regex re = new Regex(strReArgs); StringCollection args = new StringCollection(); while (curLineArgs != null){ if (!curLineArgs.Trim().StartsWith("#", StringComparison.Ordinal)){ MatchCollection matches = re.Matches(curLineArgs); if (matches != null && matches.Count != 0){ foreach (Match match in matches){ string arg = match.ToString().Trim(); int iQuotes = 0; while ((iQuotes = arg.IndexOf("\"", iQuotes)) != -1){ if (iQuotes == 0) arg = arg.Substring(1); else if (arg[iQuotes-1] == '\\') iQuotes += 1; else arg = arg.Remove(iQuotes, 1); } args.Add(arg); } } } curLineArgs = reader.ReadLine(); } if (args.Count == 0) return null; string[] argStrings = new string[args.Count]; args.CopyTo(argStrings, 0); return argStrings; }