public ClientHost(Transport tsp, string endpointData, string endpointCtl, string subscription, DirectoryInfo downloadDirectory, bool testMode, GetClientNAKStateDelegate getClientState, int networkHWM, int diskHWM, int pgmRate) { this.tsp = tsp; this.subscription = subscription; this.downloadDirectory = downloadDirectory; this.testMode = testMode; this.getClientState = getClientState; this.pgmRate = pgmRate; this.Completed = false; this.doLogging = new BooleanSwitch("doLogging", "Log client events", "0"); this.portData = 12198; this.deviceData = endpointData; int idx = endpointData.LastIndexOf(':'); if (idx >= 0) { this.deviceData = endpointData.Substring(0, idx); UInt32.TryParse(endpointData.Substring(idx + 1), out portData); } this.portCtl = portData + 1; this.deviceCtl = endpointCtl; idx = endpointCtl.LastIndexOf(':'); if (idx >= 0) { this.deviceCtl = endpointCtl.Substring(0, idx); UInt32.TryParse(endpointCtl.Substring(idx + 1), out portCtl); if (portCtl == portData) portCtl = portData + 1; } this.networkHWM = networkHWM; this.diskHWM = diskHWM; }
static WorkflowTrace() { runtime.Switch = new SourceSwitch("System.Workflow.Runtime", SourceLevels.Off.ToString()); tracking = new TraceSource("System.Workflow.Runtime.Tracking"); tracking.Switch = new SourceSwitch("System.Workflow.Runtime.Tracking", SourceLevels.Off.ToString()); host = new TraceSource("System.Workflow.Runtime.Hosting"); host.Switch = new SourceSwitch("System.Workflow.Runtime.Hosting", SourceLevels.Off.ToString()); BooleanSwitch switch2 = new BooleanSwitch("System.Workflow LogToFile", "Log traces to file"); if (switch2.Enabled) { TextWriterTraceListener listener = new TextWriterTraceListener("WorkflowTrace.log"); Trace.Listeners.Add(listener); runtime.Listeners.Add(listener); host.Listeners.Add(listener); } BooleanSwitch switch3 = new BooleanSwitch("System.Workflow LogToTraceListeners", "Trace to listeners in Trace.Listeners", "0"); if (switch3.Enabled) { foreach (TraceListener listener2 in Trace.Listeners) { if (!(listener2 is DefaultTraceListener)) { runtime.Listeners.Add(listener2); tracking.Listeners.Add(listener2); host.Listeners.Add(listener2); } } } }
static void Main() { if (!EventLog.SourceExists("SelfMailer")) { EventLog.CreateEventSource("SelfMailer", "Mes applications"); } EventLog eventLog = new EventLog("Mes applications", ".", "SelfMailer"); eventLog.WriteEntry("Mon message", EventLogEntryType.Warning); BooleanSwitch booleanSwitch = new BooleanSwitch("BooleanSwitch", "Commutateur booléen."); TraceSwitch traceSwitch = new TraceSwitch("TraceSwitch", "Commutateur complexe."); TextWriterTraceListener textListener = new TextWriterTraceListener(@".\Trace.txt"); Trace.Listeners.Add(textListener); Trace.AutoFlush = true; Trace.WriteLineIf(booleanSwitch.Enabled, "Démarrage de l'application SelfMailer"); Project = new Library.Project(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Forms.Main()); Trace.WriteLineIf(traceSwitch.TraceInfo, "Arrêt de l'application SelfMailer"); }
public static void Write(BooleanSwitch bs, string msg) { #if TRACE Trace.WriteLine(bs.DisplayName + ": " + Thread.CurrentThread.Name + ": " + msg); #elif BRUNET_NUNIT System.Console.WriteLine(msg); #endif }
public static bool TryGetBooleanSwitch(string name, out BooleanSwitch bs) { Type type = typeof(ProtocolLog); FieldInfo field = type.GetField(name, BindingFlags.Public | BindingFlags.Static); if(field == null) { bs = null; return false; } bs = field.GetValue(null) as BooleanSwitch; return bs != null; }
protected void LogToTrace(string message, string category, LogType type, int stackFrameNo = 3) { Debug.WriteLine(message, category); try { BooleanSwitch traceSwitch = new BooleanSwitch("TraceEnabled", "Enable System Diagnostics Trace"); var stackFrameLog = GetStackFrameLog(message, category, stackFrameNo); Trace.WriteLineIf(traceSwitch.Enabled, stackFrameLog.Item1, type.ToString() + " : " + stackFrameLog.Item2); } catch { } // ignore }
/// <summary> /// Statically set up trace sources /// /// To enable logging to a file, add lines like the following to your app config file. /* <system.diagnostics> <switches> <add name="System.Workflow LogToFile" value="1" /> </switches> </system.diagnostics> */ /// To enable tracing to default trace listeners, add lines like the following /* <system.diagnostics> <switches> <add name="System.Workflow LogToTraceListener" value="1" /> </switches> </system.diagnostics> */ /// </summary> static WorkflowTrace() { runtime = new TraceSource("System.Workflow.Runtime"); runtime.Switch = new SourceSwitch("System.Workflow.Runtime", SourceLevels.Off.ToString()); // we'll use ID of 1 for the scheduler, 0 for rest of runtime tracking = new TraceSource("System.Workflow.Runtime.Tracking"); tracking.Switch = new SourceSwitch("System.Workflow.Runtime.Tracking", SourceLevels.Off.ToString()); host = new TraceSource("System.Workflow.Runtime.Hosting"); host.Switch = new SourceSwitch("System.Workflow.Runtime.Hosting", SourceLevels.Off.ToString()); BooleanSwitch logToFile = new BooleanSwitch("System.Workflow LogToFile", "Log traces to file"); if (logToFile.Enabled) { TextWriterTraceListener fileLog = new TextWriterTraceListener("WorkflowTrace.log"); // add to global Listeners list Trace.Listeners.Add(fileLog); // don't add to tracking (which probably has its own log) runtime.Listeners.Add(fileLog); host.Listeners.Add(fileLog); } BooleanSwitch traceToDefault = new BooleanSwitch("System.Workflow LogToTraceListeners", "Trace to listeners in Trace.Listeners", "0"); if (traceToDefault.Enabled) { foreach (TraceListener listener in Trace.Listeners) { if (!(listener is DefaultTraceListener)) { runtime.Listeners.Add(listener); tracking.Listeners.Add(listener); host.Listeners.Add(listener); } } } }
/// <summary> /// 构造函数. /// </summary> public TestTraceLog() { // BooleanSwitch 类型的开关, 只有 一个 Enabled 的 开关定义. // 构造 跟踪开关. dataSwitch = new BooleanSwitch("DataMessagesSwitch", "开关定义在配置文件中..."); Console.WriteLine("当前 BooleanSwitch 开关配置:"); Console.WriteLine(" Enabled: {0}", dataSwitch.Enabled); Console.WriteLine(); // TraceSwitch 类型的开关, 有 Error、Warning、Info、Verbose 四个层次的 开关定义. // 构造 跟踪开关. appSwitch = new TraceSwitch("TraceLevelSwitch", "开关定义在配置文件中..."); Console.WriteLine("当前 TraceSwitch 开关配置:"); Console.WriteLine(" TraceError:{0}", appSwitch.TraceError); Console.WriteLine(" TraceWarning:{0}", appSwitch.TraceWarning); Console.WriteLine(" TraceInfo:{0}", appSwitch.TraceInfo); Console.WriteLine(" TraceVerbose:{0}", appSwitch.TraceVerbose); }
private static bool GetSwitchValue(string switchName, string switchDescription, bool defaultValue) { BooleanSwitch theSwitch = new BooleanSwitch(switchName, switchDescription); new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { if (theSwitch.Enabled) { return true; } string environmentVar = Environment.GetEnvironmentVariable(switchName); defaultValue = environmentVar!=null && environmentVar.Trim()=="1"; } catch (ConfigurationException) { } finally { EnvironmentPermission.RevertAssert(); } return defaultValue; }
static PackWebResponse() { #if DEBUG _forceWebResponseLengthFailureSwitch = new BooleanSwitch("PackWebResponseBadServerLength", "Simulate PackWebResponse handling of server that returns bogus content length"); #endif }
public void AutoRestore() { if (readStream == null) return; lock (readStream) { readStream.Seek(0, SeekOrigin.Begin); //Seek to start byte[] buffer = new byte[4]; //Container for header size readStream.Read(buffer, 0, 4); //Read header size uint numRecords = BitConverter.ToUInt32(buffer, 0); //Get header count if (numRecords == 0) return; //Stop processing if count is 0 Console.WriteLine("Welcome to the automatic restore utility."); Console.WriteLine("Restore-points detected: {0}", numRecords); Console.WriteLine("The server will now automaticlly restore characters last-known configuration."); BooleanSwitch mswitch2 = new BooleanSwitch("SkipPreviousHandledRestorePoints", "Skips restore points that have been treated earlier", "1"); byte[] headingBuffer = new byte[64]; //buffer container while (numRecords > 0) { numRecords--; long posStart = readStream.Position; readStream.Read(headingBuffer, 0, 64); //read data segment 1 uint size = ReadAsUint32(headingBuffer, 0); //read size DateTime date = ReadAsDate(headingBuffer, 4); //read datetime int countA = ReadAsInt32(headingBuffer, 16); //read numberOfRestoreTries int countB = ReadAsInt32(headingBuffer, 20); //read succeeded int countC = ReadAsInt32(headingBuffer, 24); //read exceptions string name = ReadAsString(headingBuffer, 32, 32); //read name if (countA > 10) { WriteInformation("RestorePointCentre", "Skipping segement {0} {1} reason: failed to be processed for 10x already", name, date); readStream.Seek(size, SeekOrigin.Current); //skip rest of data continue; } if (countB > 0 && mswitch2.Enabled) { WriteInformation("RestorePointCentre", "Skipping segement {0} {1} reason: was restored earlier", name, date); readStream.Seek(size, SeekOrigin.Current); //skip rest of data continue; } if (countC > 0) { WriteInformation("RestorePointCentre", "Skipping segement {0} {1} reason: had exceptions last time", name, date); readStream.Seek(size, SeekOrigin.Current); //skip rest of data continue; } WriteInformation("RestorePointCentre", "Process segement {0} {1}", name, date); MemoryStream stream = null; GZipStream gzip = null; BinaryFormatter formatter = new BinaryFormatter(); try { byte[] value = new byte[size]; readStream.Read(value, 0, (int)size); Character restoredCharacter = null; stream = new MemoryStream(value); gzip = new GZipStream(stream, CompressionMode.Decompress); restoredCharacter = formatter.Deserialize(gzip) as Character; gzip.Close(); if (!Singleton.Database.TransSave(restoredCharacter)) { WriteWarning("RestorePointCentre", "segement {0} {1} failed to save", name, date); //Go back the size of data readStream.Seek(posStart, SeekOrigin.Begin); CopyTo(headingBuffer, 16, ++countA); //Adjust header for failed readStream.Write(headingBuffer, 0, 64); readStream.Seek(size, SeekOrigin.Current); } else { WriteLine("RestorePointCentre", "segement {0} {1} was saved", name, date); //Go back the size of data readStream.Seek(posStart, SeekOrigin.Begin); CopyTo(headingBuffer, 20, ++countB); //Adjust header for success readStream.Write(headingBuffer, 0, 64); readStream.Seek(size, SeekOrigin.Current); } } catch (Exception e) { Console.WriteLine("Failed for unknown reason."); WriteWarning("RestorePointCentre", "segement {0} {1} failed to deserialize reason: {2}", name, date, e.Message); //Go back the size of data readStream.Seek(posStart, SeekOrigin.Begin); CopyTo(headingBuffer, 24, ++countC); //Adjust header for success readStream.Write(headingBuffer, 0, 64); readStream.Seek(size, SeekOrigin.Current); } finally { if (stream != null) stream.Dispose(); } } } BooleanSwitch mswitch = new BooleanSwitch("AutoMoveRestorePoints", "Moves restores points file on restart of the server", "1"); if (mswitch.Enabled) reopenRestorePoints(); }
private X10Comm() { #if DEBUG //trace timings to a logfile timingPerformance = new BooleanSwitch("X10Timings","Turn timings on or off."); traceX10Comm = new BooleanSwitch("X10Comm","Turn X10 communication tracing on or off."); FileStream txtTraceLog = new FileStream(Environment.CurrentDirectory + @"\X10TimerTraceLog.txt", FileMode.OpenOrCreate); TextWriterTraceListener traceListener = new TextWriterTraceListener(txtTraceLog); Trace.Listeners.Clear(); Trace.Listeners.Add(traceListener); Trace.AutoFlush = true; //test the tracelog if (timingPerformance.Enabled) Trace.WriteLine(DateTime.Now.ToString() + ": Time tracing is ON"); else Trace.WriteLine(DateTime.Now.ToString() + ": Time tracing is OFF"); if (traceX10Comm.Enabled) Trace.WriteLine(DateTime.Now.ToString() + ": Comm tracing is ON"); else Trace.WriteLine(DateTime.Now.ToString() + ": Comm tracing is OFF"); #endif //X10 commands that are to be sent to the CM11 are stored in an ArrayList arX10ToSend = new ArrayList(10); //CM11 talks to the serial port cm11 = new CM11(); }
static void Main(string[] args) { testa te = new testa(); te.faccio(3); #region opertori PippoTest pippoTest = new PippoTest(1); PippoTest pippoTest1 = new PippoTest(2); PippoTest pippoTest2 = new PippoTest(2); //implicit int testt = pippoTest2; //explicit PippoTest testtt = (PippoTest)3; //somma tra pippotest var rrrr = pippoTest1 + pippoTest; var ssss = pippoTest2++; //somma tra int e pippotest var ressss = 3 + testtt; #endregion #region TraceSource /* * LISTNER * * ConsoleTraceListener Standard output or error stream * DelimitedListTraceListener TextWriter * EventLogTraceListener EventLog * EventSchemaTraceListener XML-encoded, schema-compliant log file * TextWriterTraceListener TextWriter * XmlWriterTraceListener XML-encoded data to a TextWriter or stream. */ //configuro da codice Stream outfile = File.Create("log.txt"); //creo listner TextWriterTraceListener textWriterTraceListener = new TextWriterTraceListener(outfile); TraceSource traceSource = new TraceSource("myT", SourceLevels.All); //cancello quello di default traceSource.Listeners.Clear(); //aggiungo mio traceSource.Listeners.Add(textWriterTraceListener); traceSource.TraceInformation(""); traceSource.TraceEvent(TraceEventType.Critical, 0, ""); traceSource.TraceData(TraceEventType.Information, 1, ""); traceSource.Flush(); traceSource.Close(); //TraceSource configuro da appsetting mySource.TraceEvent(TraceEventType.Error, 1, "Error message."); mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message."); #endregion #region BooleanSwitch var sw = new System.Diagnostics.BooleanSwitch("QueryLogger", "QueryLogger"); if (sw.Enabled) { Console.WriteLine("Booleanswitchenabled"); } #endregion #region TraceSwitch /* * SourceSwitch e TraceSwitch sono altri due tipi di switch che servono a controllare * la verbosità del trace e la “sorgente” del trace. * Ovvero, se usi il tracing in maniera seria puoi, grazie al SourceSwitch, * definire varie sorgenti di tracing e regolarle a tua discrezione con il TraceSwitch. */ ////Define this in the web config TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); string msgText = "1"; // Write INFO type message, if switch is set to Verbose, type 4 Trace.WriteIf(generalSwitch.TraceVerbose, msgText); msgText = "A2MC"; // Write INFO type message, if switch is set to Verbose or Warning 4 0r 2 Trace.WriteIf(generalSwitch.TraceWarning, msgText); // Write ERROR type message, if switch is set to Verbose, Warning, info or Error // 0 (off), 1 (error), 2 (warning), 3 (info), OR 4 (verbose) //If General switch in WEB CONFIG = 0 then it will not get into the if below if (generalSwitch.TraceError) { //Trace type, inthis case error will define how it will appear in the event log Trace.TraceError("Error"); //Use your imagination to switch it on and off properly. //You can really imagine and apply. } #endregion #region EventLog if (!EventLog.SourceExists("Mysource")) { EventLog.CreateEventSource("MySource", "MyLog"); } EventLog eventLog = new EventLog(); eventLog.Source = "MySource"; eventLog.WriteEntry("Ciao J0n"); #endregion #region PerformanceCounter /* CounterCreationDataCollection * CounterCreationData (PerformanceCounterType) * PerformanceCounterCategory (si prende il collection che si prende il data) (PerformanceCounterCategoryType) * PerformanceCounter */ var performanceCounterCategories = PerformanceCounterCategory.GetCategories(); var first = performanceCounterCategories.FirstOrDefault(category => category.CategoryName == "Processor"); var performanceCounters = first.GetCounters("_Total"); Console.WriteLine("Displaying performance counters for Processor category:--\n"); foreach (PerformanceCounter performanceCounter in performanceCounters) { Console.WriteLine(performanceCounter.CounterName); } //v2custom String customCategoryName = "Custom Performance Counter Category"; string counterNameCustom = "pippo"; if (!PerformanceCounterCategory.Exists(customCategoryName)) { CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection(); counterCreationDataCollection.Add(new CounterCreationData(counterNameCustom, "Sample Counter 1", PerformanceCounterType.ElapsedTime)); //counterCreationDataCollection.Add(new CounterCreationData("Counter 2", "Sample Counter 2", PerformanceCounterType.SampleCounter)); PerformanceCounterCategory.Create(customCategoryName, "This is just an example", PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection); var counter = new PerformanceCounter(customCategoryName, counterNameCustom, false); counter.Increment(); } using (var counter = new PerformanceCounter(customCategoryName, counterNameCustom, false)) { counter.Increment(); } //v2custom string counterName = "countername"; string categoryName = "categoryname"; if (!PerformanceCounterCategory.Exists("categoryname")) { CounterCreationDataCollection datacollection = new CounterCreationDataCollection(); CounterCreationData numberOfItems = new CounterCreationData(); numberOfItems.CounterType = PerformanceCounterType.NumberOfItems32; numberOfItems.CounterName = counterName; datacollection.Add(numberOfItems); // Create the category. PerformanceCounterCategory.Create(categoryName, "Demonstrates usage of the AverageTimer32 performance counter type", PerformanceCounterCategoryType.SingleInstance, datacollection); var counter = new PerformanceCounter(categoryName, counterName, false); counter.RawValue = 0; counter.Increment(); } using (var counter = new PerformanceCounter(categoryName, counterName, false)) { counter.Increment(); } #endregion #region OOP MyMethodCond(); string main = "Main"; Trace.Write("trace"); Debug.Write("debug"); Debug.Assert(main == "Main"); Ciccio c = new Ciccio(); c.Prova(); ICiccio s = (ICiccio)c; s.Prova(); ICiccio1 s1 = (ICiccio1)c; s1.Prova(); c.Nano(); double xxx = 0.0; double yyy = 0.0; //var reszzzz = xxx / yyy;NAN IIbabbo babbo11 = new Figliolo(); babbo11.MioMetodo(); Mio("ciao"); Mio("ciao", paperino: 1); Mio("ciao", pluto: true, paperino: 1); //Mio("ciao",pluto:false,1);ERRORE //Pippo pippos = new Pippo(); //pippos.DoSOmething(); #endregion #region GENERZIONE DINAMICA CODICE /* * * //System.Reflection.Emit * //creazione , lancio e salvataggoi IL a runtime * AssemblyName nameAss = new AssemblyName("DynamicAss"); * AssemblyBuilder assemblyBuilder = * AppDomain.CurrentDomain.DefineDynamicAssembly(nameAss, AssemblyBuilderAccess.RunAndSave); * ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicMod", "DynamicAss.dll"); * //classe * TypeBuilder tb = moduleBuilder.DefineType("HelloClass", TypeAttributes.Class | TypeAttributes.Public); * //metodo * MethodBuilder mb = * tb.DefineMethod("PrintHello", MethodAttributes.Public, null, new Type[] { typeof(string) }); * ILGenerator myGenerator = mb.GetILGenerator(); * myGenerator.Emit(OpCodes.Ldstr, "Hello"); * myGenerator.Emit(OpCodes.Ldarg_1); * MethodInfo concatMetod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }); * myGenerator.Emit(OpCodes.Call, concatMetod); * MethodInfo wrMethodInfo = typeof(Console).GetMethod("Write", new Type[] { typeof(string) }); * myGenerator.Emit(OpCodes.Call, wrMethodInfo); * myGenerator.Emit(OpCodes.Ret); * * //istanzio ogetto * Type helloType = tb.CreateType(); * object helloobj = Activator.CreateInstance(helloType); * MethodInfo hellMethodInfo = helloType.GetMethod("PrintHello", new[] { typeof(string) }); * * //invoco metodo passando parametro * hellMethodInfo.Invoke(helloobj, new object[] { "J0n" }); * * //salvo dll * assemblyBuilder.Save("DynamicAss.dll"); #endregion * * HelloClass helloClass = new HelloClass(); * helloClass.PrintHello("ciao"); */ //System.CodeDom //creare salvare e compilare codice sorgente e runtime CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace("CodeDOM"); codeNamespace.Imports.Add(new CodeNamespaceImport("System")); //classe CodeTypeDeclaration myclass = new CodeTypeDeclaration("Pippo"); //metodo CodeMemberMethod codeMemberMethod = new CodeMemberMethod(); codeMemberMethod.Name = "DoSOmething"; codeMemberMethod.Attributes = MemberAttributes.Public; CodeMethodInvokeExpression codeMethodInvokeExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Ciao Ciccio")); CodeMethodInvokeExpression codeMethodInvokeExpression1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "ReadLine"); codeCompileUnit.Namespaces.Add(codeNamespace); codeNamespace.Types.Add(myclass); myclass.Members.Add(codeMemberMethod); codeMemberMethod.Statements.Add(codeMethodInvokeExpression); codeMemberMethod.Statements.Add(codeMethodInvokeExpression1); //salva codice sorgente CSharpCodeProvider provider = new CSharpCodeProvider(); string pathSource = @"../../bin/Debug/Pippo.cs"; string pathOut = @"../../bin/Debug/Pippos.dll"; //string pathSource = @"../../autogenerated/Pippo.cs"; //string pathOut = @"../../autogenerated/Pippos.exe"; using (StreamWriter stream = new StreamWriter(pathSource, false)) { IndentedTextWriter tw = new IndentedTextWriter(stream, " "); provider.GenerateCodeFromCompileUnit(codeCompileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } CompileCSharpCode(pathSource, pathOut); #endregion #region reflection //REFLECTION System.Assembly //assembly (IL codice compilato) exe/dll //carico in memoria assembly //PLUGIN //caricamento dinamico assembly da path Assembly assm = Assembly.LoadFrom(@"C:\Users\rob\source\repos\Exam\Plugin1\bin\Debug\Plugin1.dll"); Type[] tips = assm.GetTypes(); foreach (var item in tips) { //var objectType = Type.GetType(objectToInstantiate); Type objectType = assm.GetType(item.FullName); var instantiatedObject = Activator.CreateInstance(objectType); } //carica solo metadati dei tipi SENZA instanziare i tipi Assembly ass2 = Assembly.ReflectionOnlyLoadFrom("ClassLibrary1.dll"); //var instantiatedObject1 = Activator.CreateInstance(typeof(Tipo)); //var instantiatedObject2 = Activator.CreateInstance<Tipo>; string sss = new String(new char[3]); //assembly attualmente in esecuzione Assembly ass = Assembly.GetExecutingAssembly(); Assembly ass1 = Assembly.GetAssembly(typeof(string)); Assembly ass12 = Assembly.GetAssembly(sss.GetType()); var mytype = ass.GetType("ConsoleApp1.Program"); var fullname = ass.FullName; var nome = mytype.Name; var mytypeNamespace = mytype.Namespace; var typeinfo = typeof(MiaclasseProva).GetTypeInfo(); var name = typeinfo.FullName; //ottengo tipo classe MiaclasseProva miaclasseProva = new MiaclasseProva(); var typeinfo1 = miaclasseProva.GetType().GetTypeInfo(); //ottengo interafccia var interfaccie = typeinfo1.GetInterfaces(); //ottengo metodi e parametri MethodInfo[] metodi = typeinfo1.GetMethods(BindingFlags.Instance); foreach (var metodo in metodi) { var pi = metodo.GetParameters(); foreach (var parinfo in pi) { Console.WriteLine($" parametro : {parinfo.ParameterType.Name}"); } } //ottengo membri MemberInfo[] membri = typeinfo1.GetMembers(BindingFlags.Public | BindingFlags.NonPublic); foreach (var mambro in membri) { var mi = mambro.MemberType; } #endregion #region IComparable //confrontare oggetti ComparableMoto comparableMoto = new ComparableMoto(); comparableMoto.Targa = "pippo"; ComparableMoto comparableMoto1 = new ComparableMoto(); comparableMoto1.Targa = "pluto"; int ord = comparableMoto.CompareTo(comparableMoto1); List <ComparableMoto> comparableMotos = new List <ComparableMoto>(); comparableMotos.Add(new ComparableMoto() { Targa = "A" }); comparableMotos.Add(new ComparableMoto() { Targa = "B" }); comparableMotos.Add(new ComparableMoto() { Targa = "C" }); comparableMotos.Sort(); //AppDomain.CurrentDomain.UnhandledException += OnUnhandleException; //ManageException manage = new ManageException(); //manage.GeneroEccezioneNonGestita(); #endregion #region ref out static class Figlio figlio1 = new Figlio(); Figlio figlio = new Figlio("as"); Macchina macchina = new Macchina("320", "bmw"); macchina.Parti(); SmartPhone.Battery battery = new SmartPhone.Battery(); ConstructorStaticClass constructorStaticClass = new ConstructorStaticClass(); ConstructorStaticClass miaclasse2 = new ConstructorStaticClass(); Console.WriteLine(ConstructorStaticClass.contatore); ClassTest1 babbo = new ClassTest1(); var testref = 0; double resp2; double resp3; //ref babbo.cambiaNumero(ref testref); //out scarta valore resp3 babbo.potenza(2, out resp2, out _); var media = babbo.CalcolaMedia(18, 27, 27, 27); babbo.ParametriNome(nome: "rob", anni: 43); //c#7 //double xresp2; //double xresp3; //babbo.potenza1(2, xresp2, xresp3); int x1 = 0; //block if (x1 == 0)//expression { //codice } int? nullable = null; var cliente = new { nome = "rob" }; Mesi giorno = Mesi.febbraio; int mese = (int)Mesi.febbraio; Mesi mese1 = (Mesi)1; Pippolo pippo; pippo.a = 1; #endregion #region cast box unbox //cast int i = 123; object box = i; int n = (int)box;//unbox dynamic dd = 1; int inc = dd + 1; var ssss1 = Convert.ToString(1); dynamic dy = new ExpandoObject(); #endregion #region type //OTTENGO IL TIPO //GetType var ti = typeof(string).GetTypeInfo(); Type ts = Type.GetType("System.String");//se si trova in Mscorelib.dll TestClass tc = new TestClass(); Type tipo = tc.GetType(); //typeof Type type = typeof(Type); //CONTROLLO IL TIPO //is tipo | as tipo string obj = ""; if (obj is string) { //cast () string a = (string)obj; //se obj non è compatibile con string cast exception string a1 = obj as string; //se obj non compatobole con string ritorna null } #endregion #region array Console.WriteLine($"metodo {nameof(Main)}"); /* * stack => vet * heap 1 * heap 2 * heap 3 * * ARRAY MULTID: * -array rettangoli * 1234 * 1234 * * -array jagged (irregolare) * 123456 * 234 * 2343434343 */ //array int[] vet = new[] { 1, 2, 3 }; //array regolari matrici int[,] matrix = new int[3, 4]; matrix[0, 0] = 1; int[,] matrix1 = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; //jagged array irregolari int[][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[4] { 1, 2, 3, 4 }; #endregion #region c7 PATTERN MATCHING /* * type => espr is tipo v * const => espr is constante * var * * */ //type object obj1 = ""; if (obj1 is string str) { Console.WriteLine(str); } //invece che if (obj1 is string) { string str1 = (string)obj; Console.WriteLine(str1); } //const Mesi giornomese = Mesi.febbraio; bool feb = giornomese is Mesi.febbraio;//true se giorno di febbraio #endregion #region Event //Event Pub pub = new Pub(); //mi iscrivo e gli dico di fare questo quando viene sollevato evento evento pub.OnChange += () => Console.WriteLine("lambda"); pub.OnChange += delegate { Console.WriteLine("delegate"); }; //sollevo evento pub.Raise(); Pub1 p1 = new Pub1(); p1.OnChange += () => Console.WriteLine("lambda"); p1.Raise(); Pub2 p2 = new Pub2(); p2.CreateAndRaise(); Car car = new Car(); CarMonitor cm = new CarMonitor(car); car.Decelerate(); #endregion #region Expression Tree //Expression Tree Expression <Func <int, bool> > exp1 = x => x % 2 == 0; Func <int, bool> isPari = exp1.Compile();//dopo che l'ho compliat posso eseguirla, prima era solo un albero di espressopmo if (isPari(4)) { Console.WriteLine("pari"); } #endregion #region delegate //assegno lambda (anonyous method) myDelegate myd = (x) => 1; Console.WriteLine(myd("0ciao")); //assegno metodo myDelegate myd1 = MethodForDel; Console.WriteLine(myd1("1ciao")); //assegno delegate myDelegate myd2 = delegate { return(1); }; Console.WriteLine(myd2("2ciao")); #endregion #region VARIANZA //COVARIANZA OUT //ti faccio assegnare sia metodo che ritorna stringa //ma anche metodo che torna object perchè stringa deriva //da object (è piu specifica) Del d1 = new Del(); Cov <string> cov = d1.Cov1; Cov <object> cov1 = d1.Cov2; Cov <object> cov3 = d1.Cov2; //Cov<string> cov2 = d1.Cov2;//no object non deriva da stringa //CONTROVARIANZA IN //ti faccio assegnare sia metodo che prende ingresso //classe piu generica object ma ache classe piu specifica string Con <object> con = d1.Con1; Con <string> con3 = d1.Con1; Con <string> con1 = d1.Con2; //Con<object> con2 = d1.Con2;//no var res3 = d1.MyCon(Convert.ToInt32, "5"); var res4 = d1.MyCon1(Convert.ToInt32, "5"); var res5 = d1.MyConGen(Convert.ToInt32, "5"); var res6 = d1.MyConGen(Convert.ToBoolean, 0); var res7 = d1.MyConGen(Convert.ToString, 5); Console.WriteLine(res3); Console.WriteLine(res4); d1.UseMulticast(); #endregion #region generics Task tx1 = Task.Run(() => { Console.WriteLine("ciao"); }); Task[] tasksarr = new Task[1]; tasksarr[0] = tx1; Gen1 gen1 = new Gen1(); if (gen1.GetDefault <ConstructorStaticClass, Task>(tx1) != null) { gen1.ContinueTaskOrDefault(tx1, Console.WriteLine); Console.WriteLine("start task generic"); } var mytaskList = gen1.ContinueTasksOrDefault(tasksarr, Console.WriteLine); if (mytaskList != null) { Console.WriteLine("starts tasks generic"); } Gen2 <Constructor> gen2 = new Gen2 <Constructor>(); Gen2Figlia <Constructor> gen2figlia = new Gen2Figlia <Constructor>(); Gen1Figlia <Constructor, Task> tesFiglia = new Gen1Figlia <Constructor, Task>(); //variabile statico è diverso per tipo TestStaticGen <string> .Status = "rob"; TestStaticGen <int> .Status = 1; Console.WriteLine(TestStaticGen <string> .Status); Console.WriteLine(TestStaticGen <int> .Status); TestStatic.Status = "ciao"; TestStatic.Status = "ciau"; Console.WriteLine(TestStatic.Status); // Generica <string, int, DateTime, bool> gen = new Generica <string, int, DateTime, bool>(); List <Lista <string> > genericiInnestati = new List <Lista <string> >(); genericiInnestati.Add(new Lista <string>(5)); genericiInnestati[0][0] = "ciao"; genericiInnestati[0][1] = "come "; genericiInnestati[0][2] = "stai"; genericiInnestati[0][3] = "rob"; genericiInnestati[0][4] = "?"; foreach (var item in genericiInnestati) { for (int j = 0; j < 5; j++) { Console.WriteLine(item[j]); } } Lista <string> lista = new Lista <string>(5); lista[0] = ""; #endregion #region programmazione parallela //PLINQ solo linq to onject NO linq to sql //prende base dati la divide in segmenti e fa query in parallelo su questi segmentie pio unisce iriaultati // se i lavori nonn sono complessi e la base dati è minima la programmazione parallela non da buoni risultati var qy = from num in Enumerable.Range(1, 8).AsParallel() select Math.Pow(2, num); //stampa da 1 a 9 (9 numeri NON in ordine) //iterazioni indipendenti l'una dall altra quindi per tutti e due ordine non è sequnziale Parallel.For(1, 10, g => Console.WriteLine("g-{0}", g)); var result = Parallel.For(0, 50, (g, parallelLoopState) => { if (g > 5) { parallelLoopState.Break(); } }); if (!result.IsCompleted) { var o = result.LowestBreakIteration; } //non è sequnziale List <string> list = new List <string>() { "ciao", "come", "va?" }; Parallel.ForEach(list, word => Console.WriteLine("{0}", word, word.Length)); #endregion #region async await var res1 = DoCurlAsync(); //net 4.5 //await salva lo stato del contesto del caller e quando il metodo await si conclude //il contesto ritorna allo stato del chimante che puo eseguire il codice successivo //questo nel caso di ui permette di modiicare la ui che proprieta nella app gui del thread //della ui e viene eseguito nel ui syncronization context (dispatchercontext nella ui) //DAL C#7 TUTTO PUO ESSERE AWAITABLE ED ESEGUITO AINCRONO E NON SOLO ISTANZA DI TASK //QUALSIAIS OGGETTO CHE ESPONE METODO GETAWAITER INFATTI LA CLASSE TASK ESPONE METODO GETAWAITER //await non puo essere usato su unsafe, lock, main MetodoAsyn(); Console.WriteLine("codice prima fine await)"); Task <string> res = GetAsync(); List <string> files = new List <string>() { "pippo.txt", "pippo1.txt" }; files.ForEach(async file => await ReadFileAsync(file)); //all block //.Wait() //.Result //.GetAwaiter() //.GetResult() #endregion #region task tpl //manca continuewhenall //continuewheany //task figli innestati //Task.WaitAll blocks the current thread until everything has completed. //Task.WhenAll returns a task which represents the action of waiting until everything has completed. //That means that from an async method, you can use: // A DIFFERENZA DI WAIT ALL TORNA SOLO LA PRIMA ECCEZIONE NON AGGREGATE Task[] tasksArray = new Task[3]; tasksArray[0] = Task.Run(() => { Thread.Sleep(4000); }); tasksArray[1] = Task.Run(() => { Thread.Sleep(4000); }); tasksArray[2] = Task.Run(() => { Thread.Sleep(4000); }); var ry = MyAsyncWhenAll(tasksArray); Console.WriteLine("tornato da MyAsyncWhenAll"); Task tx = Task.Run(() => { Thread.Sleep(1000); }); Task ty = Task.Run(() => { Thread.Sleep(1000); }); Task taskall = Task.WhenAll((new Task[] { tx, ty })); //Task taskall = Task.WhenAny((new Task[] { t1, t2 })); taskall.Wait(); Task <String> webtask = Task.Run(() => { string url = "http://www.google.it"; WebClient wc = new WebClient(); return(wc.DownloadString(url)); }); Task <String> headhtml = webtask.ContinueWith <string>(x => { var res2 = x.Result; //fai qualcosa con res return(res2); }); var tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task cancellabletask = null; try { cancellabletask = Task.Run(() => { token.ThrowIfCancellationRequested(); for (int d = 0; d < 2; d++) { Thread.Sleep(100); if (token.IsCancellationRequested) { //eseguo altre cose token.ThrowIfCancellationRequested(); } } }, token); tokenSource.CancelAfter(1000); cancellabletask.Wait(); } catch (AggregateException aggregateException) { if (aggregateException.InnerException is OperationCanceledException) { Console.WriteLine("OperationCanceledException£"); } if (cancellabletask != null && (cancellabletask.IsCanceled && cancellabletask.Status == TaskStatus.Canceled)) { Console.WriteLine(aggregateException.ToString()); } } Task <String> task = Task.Run(() => { string url = "http://www.google.it"; WebClient wc = new WebClient(); return(wc.DownloadString(url)); }); var htmlUrl = task.Result;//blocco List <Task> tasks = new List <Task>(); for (int r = 0; r < 5; r++) { int number = r; tasks.Add( Task.Run(() => { Console.WriteLine(number); Thread.Sleep(1000); })); } //Task.WaitAll(tasks.ToArray()); Task.WaitAny(tasks.ToArray()); Console.WriteLine("all task complete"); Task longtask = Task.Run(() => { Thread.Sleep(1000); }); longtask.Wait(1000); Task verylong = Task.Factory.StartNew(() => { Thread.Sleep(2000); }, TaskCreationOptions.LongRunning); #endregion tpl #region thread for (int w = 0; w < 5; w++) { ThreadPool.QueueUserWorkItem(LongOperation); } Thread threada = new Thread(IncrMon); Thread threadb = new Thread(IncrMon); threada.Start(); threadb.Start(); threada.Join(); threadb.Join(); Console.WriteLine("n={0}", n2); Thread thread1 = new Thread(Incr); Thread thread2 = new Thread(Incr); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); Console.WriteLine("n={0}", n1); Thread t = new Thread(() => { Console.WriteLine(Thread.CurrentThread.Name); Thread.Sleep(1000); }); Thread t1 = new Thread(() => { Console.WriteLine(Thread.CurrentThread.Name); for (int z = 0; z < 10; z++) { lock (lockobj) { n = n + 1; Thread.Sleep(1); Console.WriteLine("n={0}", n); } } }); Thread t2 = new Thread(() => { Console.WriteLine(Thread.CurrentThread.Name); for (int x = 0; x < 10; x++) { lock (lockobj) { n = n + 1; Thread.Sleep(1); Console.WriteLine("n={0}", n); } } }); t.IsBackground = true; //termina appena finisce la app t.Priority = ThreadPriority.AboveNormal; //determinata quantita di cpu destinata al thread ma non è deterministico t.Start(); t1.Start(); t2.Start(); t.Join();//il codice si blocca e attende che t finisce #endregion Console.ReadLine(); }
internal static void InitializeSockets() { if (!s_Initialized) { lock(InternalSyncObject){ if (!s_Initialized) { WSAData wsaData = new WSAData(); SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.WSAStartup( (short)0x0202, // we need 2.2 out wsaData ); if (errorCode!=SocketError.Success) { // // failed to initialize, throw // // WSAStartup does not set LastWin32Error throw new SocketException(errorCode); } #if !FEATURE_PAL // // we're on WinNT4 or greater, we could use CompletionPort if we // wanted. check if the user has disabled this functionality in // the registry, otherwise use CompletionPort. // #if DEBUG BooleanSwitch disableCompletionPortSwitch = new BooleanSwitch("DisableNetCompletionPort", "System.Net disabling of Completion Port"); // // the following will be true if they've disabled the completionPort // UseOverlappedIO = disableCompletionPortSwitch.Enabled; #endif bool ipv4 = true; bool ipv6 = true; SafeCloseSocket.InnerSafeCloseSocket socketV4 = UnsafeNclNativeMethods.OSSOCK.WSASocket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0, (SocketConstructorFlags) 0); if (socketV4.IsInvalid) { errorCode = (SocketError) Marshal.GetLastWin32Error(); if (errorCode == SocketError.AddressFamilyNotSupported) ipv4 = false; } socketV4.Close(); SafeCloseSocket.InnerSafeCloseSocket socketV6 = UnsafeNclNativeMethods.OSSOCK.WSASocket( AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0, (SocketConstructorFlags) 0); if (socketV6.IsInvalid) { errorCode = (SocketError) Marshal.GetLastWin32Error(); if (errorCode == SocketError.AddressFamilyNotSupported) ipv6 = false; } socketV6.Close(); // < #if COMNET_DISABLEIPV6 // // Turn off IPv6 support // ipv6 = false; #else // // Now read the switch as the final check: by checking the current value for IPv6 // support we may be able to avoid a painful configuration file read. // if (ipv6) { s_OSSupportsIPv6 = true; ipv6 = SettingsSectionInternal.Section.Ipv6Enabled; } #endif // // Update final state // s_SupportsIPv4 = ipv4; s_SupportsIPv6 = ipv6; #else //!FEATURE_PAL s_SupportsIPv4 = true; s_SupportsIPv6 = false; #endif //!FEATURE_PAL // Cache some settings locally. #if !FEATURE_PAL // perfcounter s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled; #endif s_Initialized = true; } } } }
public void BooleanSwitchValidDefaultValue () { BooleanSwitch s = new BooleanSwitch ("test", "", "2"); Assert.IsTrue (s.Enabled, "#1"); s = new BooleanSwitch ("test", "", "0"); Assert.IsTrue (!s.Enabled, "#2"); s = new BooleanSwitch ("test", "", "true"); Assert.IsTrue (s.Enabled, "#3"); s = new BooleanSwitch ("test", "", "True"); Assert.IsTrue (s.Enabled, "#4"); s = new BooleanSwitch ("test", "", "truE"); Assert.IsTrue (s.Enabled, "#5"); }
public void BooleanSwitchInvalidDefaultValue () { BooleanSwitch s = new BooleanSwitch ("test", "", "hoge"); Assert.IsTrue (!s.Enabled); }
public MediaTrace(string switchName) { _switch = new BooleanSwitch(switchName, "[" + SafeSecurityHelper.GetAssemblyPartialName(Assembly.GetCallingAssembly()) + "]"); }
static Marshaler () { marshalSwitch = new BooleanSwitch ("VirtuosoClient.Marshal", "Marshaling"); Debug.AutoFlush = true; // work around web.config ignoring autoflush }
private VtmLogger() { _bSwitch = new BooleanSwitch("Enable", "", VtmFramework.Properties.Settings.Default.Enable); }
static PackWebRequestFactory() { #if DEBUG _traceSwitch = new BooleanSwitch("PackWebRequest", "PackWebRequest/Response and NetStream trace messages"); #endif }
static int Main( string [] args ) { _runLocal = true; try { BooleanSwitch traceEnableSwitch = new BooleanSwitch("TraceEnable", "Enable trace messages"); if (traceEnableSwitch.Enabled) { // Spit all trace output to stdout if desired Console.WriteLine( "Tracing Enabled" ); Trace.Listeners.Add( new TextWriterTraceListener(Console.Out) ); } else { // By default, listen only to the "Error" trace messages // Does not work: what am I doing wrong? Console.WriteLine( "Error Tracing enabled" ); Trace.Listeners.Add( new TextWriterTraceListener(Console.Out, "Error") ); } Trace.AutoFlush = true; // Parse args: for (int i = 0; i < args.Length; i++) { if ("/client" == args[i]) { _runLocal = false; } else { _PrintUsage(); return 1; } } _SetUpRemoting(); _Trace( "Initializing" ); Application.Init (); // New: _Trace( "Creating GtkPlayer" ); gtkPlayer = new GtkPlayer(); _Trace( "Application.Run time" ); Application.Run (); } catch ( Exception e ) { _Trace( "Something is horribly wrong" ); // Deal with unexpected exception by printing a message. Note // that it is possible to generate an excption while printing // the exception, so wrap that sucker too! string errorMsg = null; errorMsg = e.ToString(); Console.WriteLine( "Unexpected Exception: {0}", errorMsg); Console.WriteLine( "Exiting" ); return 1; // ** quick exit ** } _Trace( "exiting" ); // If any stray threads are around, deal with it here. if (_runLocal) _backendInterface.ShutDown(); _scanner = null; _backendProxy = null; _backendInterface = null; return 0; // success }