mercoledì 19 dicembre 2012

How to : implement Internal property

Giusto per non perdere il vizio di scrivere due righe di codice ecco che mi capita sotto mano, una di quelle "non troppo" rare occasioni per cui implementare una proprietà Ineternal.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace propTest
{
    public class entityTest
    {
        public int id { get; private set; }
        public string Name { get; set; }
        public DateTime Timestamp { get; internal set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            entityTest et = new entityTest();
            /* 
             * The property or indexer 'propTest.entityTest.id' 
             * cannot be used in this context because the set accessor is inaccessible    
             */ 

            et.id = 30;
            et.Name = "Fabio";
            et.Timestamp = DateTime.Now;
        }
    }
}

et.id = 30 non è fattibile perchè la proprietà è privata e quindi di pertinenza di entityTest, il suo scope ( in valorizzazione ) è soltanto nella classe.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace propTest
{
    public class entityTest
    {
        public virtual int id { get; set; }
        public virtual string Name { get; set; }
        public virtual DateTime Timestamp { get; internal set; }
    }

    public class entityTestWrapper : entityTest 
    {
        public new int id { get; private set; }
        public override string Name { get; set; }
        public override DateTime Timestamp { get; internal set; }

        public entityTestWrapper(int newId)
        {
            id = newId;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            entityTestWrapper et = new entityTestWrapper(30);

            et.Name = "Fabio";
            et.Timestamp = DateTime.Now;

            entityTest etx = new entityTest();
            etx.id = 31;
            etx.Name = "Fabio";
            etx.Timestamp = DateTime.Now;

        }
    }
}

E in questo esempio ci inventiamo come valorizzare l'id privato wrappando l'originale. Ora come otteniamo la valorizzazione di un internal da un name space diverso ?? Semplice non si può...

Seguendo l'esempio è necessario creare un secondo progetto e referenziarlo dal primo  e poi provare a scrivere quanto segue:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace propTestA
{
    public class entityTest
    {
        public virtual int id { get; private set; }
        public virtual string Name { get; set; }
        public virtual DateTime Timestamp { get; internal set; }
    }
}

e quindi:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace propTest
{
    using propTestA;
    class Program
    {        
        static void Main(string[] args)
        {
            entityTest etx = new entityTest();        
            etx.Name = "Fabio";

            /*
             * Property or indexer 'propTestA.entityTest.Timestamp' cannot be assigned to -- 
             * it is read only    
             */

            etx.Timestamp = DateTime.Now;

        }
    }
}

Morale ... le proprietà internal sono tali per namespace e progetto...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace propTestA
{
    public class entityTest
    {
        public virtual int id { get; private set; }
        public virtual string Name { get; set; }
        public virtual DateTime Timestamp { get; internal set; }
    }
}

namespace propTest
{
    using propTestA;
    class Program
    {        
        static void Main(string[] args)
        {
            entityTest etx = new entityTest();        
            etx.Name = "Fabio";
            etx.Timestamp = DateTime.Now;
        }
    }
}
In questo modo funziona anche se il namespace è differente, vince il fatto che appartengono allo stesso progetto.

martedì 18 dicembre 2012

Merry 250 BYTE !!!

Siamo a Natale e perchè non dimostrare ancora una volta quanto siamo forti e creativi ???

Nella precedente edizione ci siamo divertiti a scrivere codice in modo "quasi roccambolesco" questa volta secondo me arriviamo a scriverlo in modo ancora più fantasioso.

Ricodo Simone che al tempo era stato uno dei più forti interpreti delle sfida. ma questa volta spero di raccogliere molte più partecipazioni.

Come al solito si scrive nei commenti il numero di byte, e si manda via mail il sorgente...

E andiamo a cominciare...


SFIDA HTML A 250 byte...

A) l'applicazione deve mostrare una pagina web renderizzata *
B) la pagina web deve essere scritta dall'applicazione **
C) la pagina web deve contenere il testo "POI"
D) la pagina web deve contenere e applicare  lo stile font-size:30

L'applicazione deve essere fatta con o VB.NET o in C# ...


Vale più o meno tutto ...
Gli editor di http://csharplight.blogspot.it/ potranno partecipare e vagliare eventualmene la soluzione...

* Libera intrepretazione si può scegliere di utillizzare un browswer interno oppure richiamare uno esterno..

** L'applicazione scrive il codice html, in un file.


La sfida termina venrdì 21 / 12/ 2012 ( pena la fine del mondo ) !!!


Ed ecco il primo .. naturalmente .. io ...

241.. so che si può fare di meglio !!

Qualche tiratina d'orecchie a me stesso ma ecco .. che arriva già la seconda release...

ops.. ( qualcuno ha già detto che me la meno ... ) VERISSIMO !!!


216 sempre io .. !!

Ed ecco Simone.. che stacca un 188... da paura...

Simone.. corregge il tiro !!! 160 ...

Tiziano (purpleDev) mi ha inviato il suo sorgente e si scende a 150 ... ( motivo per cui nelle proprietà c'è il mio stesso path ...)


Marco alisa Zocram arriva a 131 e come per Tiziano ho preso il sorgente e l'ho inserito nella mia soluzione..



giovedì 13 dicembre 2012

Workflow Foundation

Ammetto che non mi sono mai affacciato a questo argomento, ma avendo qualche attimo libero ho provato a comprenderne qualcosa in più.
Probabilmente più per curiosità che per altro. Ma ammetto che una volta che si entra nell'ottica, lascia spazio a tante iniziative divertenti ed edificanti.

Ammetto c'e'  parecchia letteratura sull'argomento, ma ad oggi mi sembra  una pratica poco diffusa, o per quanto ne so io l'impiego tradizionale del codice è sicuramente più efficace o più ... piacevole.

"De facto" si tratta della classica implementazione a Flowchart, ( già proprio quella che ci hanno insegnato quei dinosauri di professori negli anni 80... ) che parrebbe ritornare in voga per concretizzarsi e rendere un filo più visuale la programmazione.

Volte sapere quanto ?  tanto così:




"evito" di spiegarvi che cosa fa questo branetto di codice... ma di suo mi ha permesso di comprendere come avviene lo scambio di informazioni fra classi all'interno di una sequence.

In breve questo è il contenuto delle due classi ( BaseActivity e NextActivity ) ...


BaseActivity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

namespace WF.FirstActivity
{
    public sealed class BaseActivity : CodeActivity
    {

        public InArgument<string> Input { get; set; }

        public OutArgument<string> Output { get; set; }


        protected override void Execute(CodeActivityContext context)
        {
            if (Input.Get(context) == "Step1")
            {
                Output.Set(context, "Step2");
                return;
            }
            Output.Set(context, "Nop");
        }
    }
}


NextActivity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

namespace WF.FirstActivity
{
    public sealed class NextActivity : CodeActivity
    {

        public InArgument<string> Input { get; set; }

        public OutArgument<string> Output { get; set; }


        protected override void Execute(CodeActivityContext context)
        {
            if (Input.Get(context) == "Step2")
            {
                Output.Set(context, "Step3");
                return;
            }
            Output.Set(context, "Nop");
        }
    }
}

Il cui scopo è di "portare avanti un attività".

Tutto il resto è "imputato" manualmente da proprietà o impostazioni.


Ammetto per il momento la cosa è divertente.. ma dove mi porterà tutto questo ..


sabato 25 agosto 2012

How To Skip Linq Exception

 

Implement static IEnumerable<T> function to skip Exception when run a query.

This function return valid items only.

  1. public static class LINQException {
  2.     public static void TryExample() {
  3.         var LsWithEx = from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj");
  4.         var LsSkipEx = (from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj")).SkipExceptions();
  5.     }
  6.  
  7.     public static IEnumerable<T> SkipExceptions<T>(this IEnumerable<T> values)
  8.     {
  9.         using (var enumerator = values.GetEnumerator())
  10.         {
  11.             bool next = true;
  12.             while (next)
  13.             {
  14.                 try
  15.                 {
  16.                     next = enumerator.MoveNext();
  17.                 }
  18.                 catch
  19.                 {
  20.                     continue;
  21.                 }
  22.  
  23.                 if (next) yield return enumerator.Current;
  24.             }
  25.         }
  26.     }
  27.     
  28.     }

 

I hope this help Smile

lunedì 13 agosto 2012

WMI – Windows Management Instrumentation

 

Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management.

Classes details: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394554%28v=vs.85%29.aspx

Post related to: Win32 Classes
Schema classes included in the root\cimv2 namespace. These are the primary classes for working with Windows-based operating systems.

In this post you learn how to use Win32 OS Classes.

Usage of MgmtClassGen.exe http://msdn.microsoft.com/en-us/library/2wkebaxa%28v=vs.110%29.aspx

The Management Strongly Typed Class Generator tool enables you to quickly generate an early-bound managed class for a specified Windows Management Instrumentation (WMI) class. The generated class simplifies the code you must write to access an instance of the WMI class.

This tool is automatically installed with Visual Studio and with the Windows SDK. To run the tool, we recommend that you use the Visual Studio Command Prompt or the Windows SDK Command Prompt (CMD Shell). These utilities enable you to run the tool easily, without navigating to the installation folder. For more information, see Visual Studio and Windows SDK Command Prompts.

  • If you have Visual Studio installed on your computer: On the taskbar, click Start, click All Programs, click Visual Studio, click Visual Studio Tools, and then click Visual Studio Command Prompt.

    -or-

    If you have the Windows SDK installed on your computer: On the taskbar, click Start, click All Programs, click the folder for the Windows SDK, and then click Command Prompt (or CMD Shell).

  • At the command prompt, type the following:

    mgmtclassgen WMIClass [options]

To earn time I made a simple method which do it for you.

public void GenerateWMIClasses()
{


    string[] fileLines = {
                    "Win32_1394Controller",
                    "Win32_1394ControllerDevice",
                    "Win32_Account",
                    "Win32_AccountSID",
                    "Win32_ACE",
                    "Win32_ActionCheck",
                    "Win32_ActiveRoute",
                    "Win32_AllocatedResource",
                    "Win32_ApplicationCommandLine",
                    "Win32_ApplicationService",
                    "Win32_AssociatedBattery",
                    "Win32_AssociatedProcessorMemory",
                    "Win32_AutochkSetting",
                    "Win32_BaseBoard",
                    "Win32_BaseService",
                    "Win32_Battery",
                    "Win32_Binary",
                    "Win32_BindImageAction",
                    "Win32_BIOS",
                    "Win32_BootConfiguration",
                    "Win32_Bus",
                    "Win32_CacheMemory",
                    "Win32_CDROMDrive",
                    "Win32_CheckCheck",
                    "Win32_CIMLogicalDeviceCIMDataFile",
                    "Win32_ClassicCOMApplicationClasses",
                    "Win32_ClassicCOMClass",
                    "Win32_ClassicCOMClassSetting",
                    "Win32_ClassicCOMClassSettings",
                    "Win32_ClassInfoAction",
                    "Win32_ClientApplicationSetting",
                    "Win32_CodecFile",
                    "Win32_CollectionStatistics",
                    "Win32_COMApplication",
                    "Win32_COMApplicationClasses",
                    "Win32_COMApplicationSettings",
                    "Win32_COMClass",
                    "Win32_ComClassAutoEmulator",
                    "Win32_ComClassEmulator",
                    "Win32_CommandLineAccess",
                    "Win32_ComponentCategory",
                    "Win32_ComputerShutdownEvent",
                    "Win32_ComputerSystem",
                    "Win32_ComputerSystemEvent",
                    "Win32_ComputerSystemProcessor",
                    "Win32_ComputerSystemProduct",
                    "Win32_ComputerSystemWindowsProductActivationSetting",
                    "Win32_COMSetting",
                    "Win32_Condition",
                    "Win32_ConnectionShare",
                    "Win32_ControllerHasHub",
                    "Win32_CreateFolderAction",
                    "Win32_CurrentProbe",
                    "Win32_CurrentTime",
                    "Win32_DCOMApplication",
                    "Win32_DCOMApplicationAccessAllowedSetting",
                    "Win32_DCOMApplicationLaunchAllowedSetting",
                    "Win32_DCOMApplicationSetting",
                    "Win32_DefragAnalysis",
                    "Win32_DependentService",
                    "Win32_Desktop",
                    "Win32_DesktopMonitor",
                    "Win32_DeviceBus",
                    "Win32_DeviceChangeEvent",
                    "Win32_DeviceMemoryAddress",
                    "Win32_DeviceSettings",
                    "Win32_DFSNode",
                    "Win32_DFSNodeTarget",
                    "Win32_DFSTarget",
                    "Win32_Directory",
                    "Win32_DirectorySpecification",
                    "Win32_DiskDrive",
                    "Win32_DiskDrivePhysicalMedia",
                    "Win32_DiskDriveToDiskPartition",
                    "Win32_DiskPartition",
                    "Win32_DiskQuota",
                    "Win32_DisplayConfiguration",
                    "Win32_DisplayControllerConfiguration",
                    "Win32_DMAChannel",
                    "Win32_DriverForDevice",
                    "Win32_DriverVXD",
                    "Win32_DuplicateFileAction",
                    "Win32_Environment",
                    "Win32_EnvironmentSpecification",
                    "Win32_ExtensionInfoAction",
                    "Win32_Fan",
                    "Win32_FileSpecification",
                    "Win32_FloppyController",
                    "Win32_FloppyDrive",
                    "Win32_FontInfoAction",
                    "Win32_Group",
                    "Win32_GroupInDomain",
                    "Win32_GroupUser",
                    "Win32_HeatPipe",
                    "Win32_IDEController",
                    "Win32_IDEControllerDevice",
                    "Win32_ImplementedCategory",
                    "Win32_InfraredDevice",
                    "Win32_IniFileSpecification",
                    "Win32_InstalledSoftwareElement",
                    "Win32_IP4PersistedRouteTable",
                    "Win32_IP4RouteTable",
                    "Win32_IP4RouteTableEvent",
                    "Win32_IRQResource",
                    "Win32_JobObjectStatus",
                    "Win32_Keyboard",
                    "Win32_LaunchCondition",
                    "Win32_LoadOrderGroup",
                    "Win32_LoadOrderGroupServiceDependencies",
                    "Win32_LoadOrderGroupServiceMembers",
                    "Win32_LocalTime",
                    "Win32_LoggedOnUser",
                    "Win32_LogicalDisk",
                    "Win32_LogicalDiskRootDirectory",
                    "Win32_LogicalDiskToPartition",
                    "Win32_LogicalFileAccess",
                    "Win32_LogicalFileAuditing",
                    "Win32_LogicalFileGroup",
                    "Win32_LogicalFileOwner",
                    "Win32_LogicalFileSecuritySetting",
                    "Win32_LogicalMemoryConfiguration",
                    "Win32_LogicalProgramGroup",
                    "Win32_LogicalProgramGroupDirectory",
                    "Win32_LogicalProgramGroupItem",
                    "Win32_LogicalProgramGroupItemDataFile",
                    "Win32_LogicalShareAccess",
                    "Win32_LogicalShareAuditing",
                    "Win32_LogicalShareSecuritySetting",
                    "Win32_LogonSession",
                    "Win32_LogonSessionMappedDisk",
                    "Win32_LUID",
                    "Win32_LUIDandAttributes",
                    "Win32_ManagedSystemElementResource",
                    "Win32_MappedLogicalDisk",
                    "Win32_MemoryArray",
                    "Win32_MemoryArrayLocation",
                    "Win32_MemoryDevice",
                    "Win32_MemoryDeviceArray",
                    "Win32_MemoryDeviceLocation",
                    "Win32_MethodParameterClass",
                    "Win32_MIMEInfoAction",
                    "Win32_ModuleLoadTrace",
                    "Win32_ModuleTrace",
                    "Win32_MotherboardDevice",
                    "Win32_MountPoint",
                    "Win32_MoveFileAction",
                    "Win32_MSIResource",
                    "Win32_NamedJobObject",
                    "Win32_NamedJobObjectActgInfo",
                    "Win32_NamedJobObjectLimit",
                    "Win32_NamedJobObjectLimitSetting",
                    "Win32_NamedJobObjectProcess",
                    "Win32_NamedJobObjectSecLimit",
                    "Win32_NamedJobObjectSecLimitSetting",
                    "Win32_NamedJobObjectStatistics",
                    "Win32_NetworkAdapter",
                    "Win32_NetworkAdapterConfiguration",
                    "Win32_NetworkAdapterSetting",
                    "Win32_NetworkClient",
                    "Win32_NetworkConnection",
                    "Win32_NetworkLoginProfile",
                    "Win32_NetworkProtocol",
                    "Win32_NTDomain",
                    "Win32_NTEventlogFile",
                    "Win32_NTLogEvent",
                    "Win32_NTLogEventComputer",
                    "Win32_NTLogEventLog",
                    "Win32_NTLogEventUser",
                    "Win32_ODBCAttribute",
                    "Win32_ODBCDataSourceAttribute",
                    "Win32_ODBCDataSourceSpecification",
                    "Win32_ODBCDriverAttribute",
                    "Win32_ODBCDriverSoftwareElement",
                    "Win32_ODBCDriverSpecification",
                    "Win32_ODBCSourceAttribute",
                    "Win32_ODBCTranslatorSpecification",
                    "Win32_OnBoardDevice",
                    "Win32_OperatingSystem",
                    "Win32_OperatingSystemAutochkSetting",
                    "Win32_OperatingSystemQFE",
                    "Win32_OptionalFeature",
                    "Win32_OSRecoveryConfiguration",
                    "Win32_PageFile",
                    "Win32_PageFileElementSetting",
                    "Win32_PageFileSetting",
                    "Win32_PageFileUsage",
                    "Win32_ParallelPort",
                    "Win32_Patch",
                    "Win32_PatchFile",
                    "Win32_PatchPackage",
                    "Win32_PCMCIAController",
                    "Win32_Perf",
                    "Win32_PerfFormattedData",
                    "Win32_PerfFormattedData_ASP_ActiveServerPages",
                    "Win32_PerfFormattedData_ContentFilter_IndexingServiceFilter",
                    "Win32_PerfFormattedData_ContentIndex_IndexingService",
                    "Win32_PerfFormattedData_InetInfo_InternetInformationServicesGlobal",
                    "Win32_PerfFormattedData_ISAPISearch_HttpIndexingService",
                    "Win32_PerfFormattedData_MSDTC_DistributedTransactionCoordinator",
                    "Win32_PerfFormattedData_NTFSDRV_SMTPNTFSStoreDriver",
                    "Win32_PerfFormattedData_PerfDisk_LogicalDisk",
                    "Win32_PerfFormattedData_PerfDisk_PhysicalDisk",
                    "Win32_PerfFormattedData_PerfNet_Browser",
                    "Win32_PerfFormattedData_PerfNet_Redirector",
                    "Win32_PerfFormattedData_PerfNet_Server",
                    "Win32_PerfFormattedData_PerfNet_ServerWorkQueues",
                    "Win32_PerfFormattedData_PerfOS_Cache",
                    "Win32_PerfFormattedData_PerfOS_Memory",
                    "Win32_PerfFormattedData_PerfOS_Objects",
                    "Win32_PerfFormattedData_PerfOS_PagingFile",
                    "Win32_PerfFormattedData_PerfOS_Processor",
                    "Win32_PerfFormattedData_PerfOS_System",
                    "Win32_PerfFormattedData_PerfProc_FullImage_Costly",
                    "Win32_PerfFormattedData_PerfProc_Image_Costly",
                    "Win32_PerfFormattedData_PerfProc_JobObject",
                    "Win32_PerfFormattedData_PerfProc_JobObjectDetails",
                    "Win32_PerfFormattedData_PerfProc_Process",
                    "Win32_PerfFormattedData_PerfProc_ProcessAddressSpace_Costly",
                    "Win32_PerfFormattedData_PerfProc_Thread",
                    "Win32_PerfFormattedData_PerfProc_ThreadDetails_Costly",
                    "Win32_PerfFormattedData_PSched_PSchedFlow",
                    "Win32_PerfFormattedData_PSched_PSchedPipe",
                    "Win32_PerfFormattedData_RemoteAccess_RASPort",
                    "Win32_PerfFormattedData_RemoteAccess_RASTotal",
                    "Win32_PerfFormattedData_RSVP_ACSRSVPInterfaces",
                    "Win32_PerfFormattedData_RSVP_ACSRSVPService",
                    "Win32_PerfFormattedData_SMTPSVC_SMTPServer",
                    "Win32_PerfFormattedData_Spooler_PrintQueue",
                    "Win32_PerfFormattedData_TapiSrv_Telephony",
                    "Win32_PerfFormattedData_Tcpip_ICMP",
                    "Win32_PerfFormattedData_Tcpip_IP",
                    "Win32_PerfFormattedData_Tcpip_NBTConnection",
                    "Win32_PerfFormattedData_Tcpip_NetworkInterface",
                    "Win32_PerfFormattedData_Tcpip_TCP",
                    "Win32_PerfFormattedData_Tcpip_UDP",
                    "Win32_PerfFormattedData_TermService_TerminalServices",
                    "Win32_PerfFormattedData_TermService_TerminalServicesSession",
                    "Win32_PerfFormattedData_W3SVC_WebService",
                    "Win32_PerfRawData",
                    "Win32_PerfRawData_ASP_ActiveServerPages",
                    "Win32_PerfRawData_ContentFilter_IndexingServiceFilter",
                    "Win32_PerfRawData_ContentIndex_IndexingService",
                    "Win32_PerfRawData_InetInfo_InternetInformationServicesGlobal",
                    "Win32_PerfRawData_ISAPISearch_HttpIndexingService",
                    "Win32_PerfRawData_MSDTC_DistributedTransactionCoordinator",
                    "Win32_PerfRawData_NTFSDRV_SMTPNTFSStoreDriver",
                    "Win32_PerfRawData_PerfDisk_LogicalDisk",
                    "Win32_PerfRawData_PerfDisk_PhysicalDisk",
                    "Win32_PerfRawData_PerfNet_Browser",
                    "Win32_PerfRawData_PerfNet_Redirector",
                    "Win32_PerfRawData_PerfNet_Server",
                    "Win32_PerfRawData_PerfNet_ServerWorkQueues",
                    "Win32_PerfRawData_PerfOS_Cache",
                    "Win32_PerfRawData_PerfOS_Memory",
                    "Win32_PerfRawData_PerfOS_Objects",
                    "Win32_PerfRawData_PerfOS_PagingFile",
                    "Win32_PerfRawData_PerfOS_Processor",
                    "Win32_PerfRawData_PerfOS_System",
                    "Win32_PerfRawData_PerfProc_FullImage_Costly",
                    "Win32_PerfRawData_PerfProc_Image_Costly",
                    "Win32_PerfRawData_PerfProc_JobObject",
                    "Win32_PerfRawData_PerfProc_JobObjectDetails",
                    "Win32_PerfRawData_PerfProc_Process",
                    "Win32_PerfRawData_PerfProc_ProcessAddressSpace_Costly",
                    "Win32_PerfRawData_PerfProc_Thread",
                    "Win32_PerfRawData_PerfProc_ThreadDetails_Costly",
                    "Win32_PerfRawData_PSched_PSchedFlow",
                    "Win32_PerfRawData_PSched_PSchedPipe",
                    "Win32_PerfRawData_RemoteAccess_RASPort",
                    "Win32_PerfRawData_RemoteAccess_RASTotal",
                    "Win32_PerfRawData_RSVP_ACSRSVPInterfaces",
                    "Win32_PerfRawData_RSVP_ACSRSVPService",
                    "Win32_PerfRawData_SMTPSVC_SMTPServer",
                    "Win32_PerfRawData_Spooler_PrintQueue",
                    "Win32_PerfRawData_TapiSrv_Telephony",
                    "Win32_PerfRawData_Tcpip_ICMP",
                    "Win32_PerfRawData_Tcpip_IP",
                    "Win32_PerfRawData_Tcpip_NBTConnection",
                    "Win32_PerfRawData_Tcpip_NetworkInterface",
                    "Win32_PerfRawData_Tcpip_TCP",
                    "Win32_PerfRawData_Tcpip_UDP",
                    "Win32_PerfRawData_TermService_TerminalServices",
                    "Win32_PerfRawData_TermService_TerminalServicesSession",
                    "Win32_PerfRawData_W3SVC_WebService",
                    "Win32_PhysicalMedia",
                    "Win32_PhysicalMemory",
                    "Win32_PhysicalMemoryArray",
                    "Win32_PhysicalMemoryLocation",
                    "Win32_PingStatus",
                    "Win32_PnPAllocatedResource",
                    "Win32_PnPDevice",
                    "Win32_PnPEntity",
                    "Win32_PnPSignedDriver",
                    "Win32_PnPSignedDriverCIMDataFile",
                    "Win32_PointingDevice",
                    "Win32_PortableBattery",
                    "Win32_PortConnector",
                    "Win32_PortResource",
                    "Win32_POTSModem",
                    "Win32_POTSModemToSerialPort",
                    "Win32_PowerManagementEvent",
                    "Win32_Printer",
                    "Win32_PrinterConfiguration",
                    "Win32_PrinterController",
                    "Win32_PrinterDriver",
                    "Win32_PrinterDriverDll",
                    "Win32_PrinterSetting",
                    "Win32_PrinterShare",
                    "Win32_PrintJob",
                    "Win32_PrivilegesStatus",
                    "Win32_Process",
                    "Win32_Processor",
                    "Win32_ProcessStartTrace",
                    "Win32_ProcessStartup",
                    "Win32_ProcessStopTrace",
                    "Win32_ProcessTrace",
                    "Win32_Product",
                    "Win32_ProductCheck",
                    "Win32_ProductResource",
                    "Win32_ProductSoftwareFeatures",
                    "Win32_ProgIDSpecification",
                    "Win32_ProgramGroup",
                    "Win32_ProgramGroupContents",
                    "Win32_ProgramGroupOrItem",
                    "Win32_Property",
                    "Win32_ProtocolBinding",
                    "Win32_Proxy",
                    "Win32_PublishComponentAction",
                    "Win32_QuickFixEngineering",
                    "Win32_QuotaSetting",
                    "Win32_Refrigeration",
                    "Win32_Registry",
                    "Win32_RegistryAction",
                    "Win32_ReliabilityRecords",
                    "Win32_ReliabilityStabilityMetrics",
                    "Win32_RemoveFileAction",
                    "Win32_RemoveIniAction",
                    "Win32_ReserveCost",
                    "Win32_ScheduledJob",
                    "Win32_SCSIController",
                    "Win32_SCSIControllerDevice",
                    "Win32_SecurityDescriptor",
                    "Win32_SecurityDescriptorHelper",
                    "Win32_SecuritySetting",
                    "Win32_SecuritySettingAccess",
                    "Win32_SecuritySettingAuditing",
                    "Win32_SecuritySettingGroup",
                    "Win32_SecuritySettingOfLogicalFile",
                    "Win32_SecuritySettingOfLogicalShare",
                    "Win32_SecuritySettingOfObject",
                    "Win32_SecuritySettingOwner",
                    "Win32_SelfRegModuleAction",
                    "Win32_SerialPort",
                    "Win32_SerialPortConfiguration",
                    "Win32_SerialPortSetting",
                    "Win32_ServerConnection",
                    "Win32_ServerFeature",
                    "Win32_ServerSession",
                    "Win32_Service",
                    "Win32_ServiceControl",
                    "Win32_ServiceSpecification",
                    "Win32_ServiceSpecificationService",
                    "Win32_Session",
                    "Win32_SessionConnection",
                    "Win32_SessionProcess",
                    "Win32_SettingCheck",
                    "Win32_ShadowBy",
                    "Win32_ShadowContext",
                    "Win32_ShadowCopy",
                    "Win32_ShadowDiffVolumeSupport",
                    "Win32_ShadowFor",
                    "Win32_ShadowOn",
                    "Win32_ShadowProvider",
                    "Win32_ShadowStorage",
                    "Win32_ShadowVolumeSupport",
                    "Win32_Share",
                    "Win32_ShareToDirectory",
                    "Win32_ShortcutAction",
                    "Win32_ShortcutFile",
                    "Win32_ShortcutSAP",
                    "Win32_SID",
                    "Win32_SIDandAttributes",
                    "Win32_SMBIOSMemory",
                    "Win32_SoftwareElement",
                    "Win32_SoftwareElementAction",
                    "Win32_SoftwareElementCheck",
                    "Win32_SoftwareElementCondition",
                    "Win32_SoftwareElementResource",
                    "Win32_SoftwareFeature",
                    "Win32_SoftwareFeatureAction",
                    "Win32_SoftwareFeatureCheck",
                    "Win32_SoftwareFeatureParent",
                    "Win32_SoftwareFeatureSoftwareElements",
                    "Win32_SoundDevice",
                    "Win32_StartupCommand",
                    "Win32_SubDirectory",
                    "Win32_SystemAccount",
                    "Win32_SystemBIOS",
                    "Win32_SystemBootConfiguration",
                    "Win32_SystemConfigurationChangeEvent",
                    "Win32_SystemDesktop",
                    "Win32_SystemDevices",
                    "Win32_SystemDriver",
                    "Win32_SystemDriverPnPEntity",
                    "Win32_SystemEnclosure",
                    "Win32_SystemLoadOrderGroups",
                    "Win32_SystemLogicalMemoryConfiguration",
                    "Win32_SystemMemoryResource",
                    "Win32_SystemNetworkConnections",
                    "Win32_SystemOperatingSystem",
                    "Win32_SystemPartitions",
                    "Win32_SystemProcesses",
                    "Win32_SystemProgramGroups",
                    "Win32_SystemResources",
                    "Win32_SystemServices",
                    "Win32_SystemSetting",
                    "Win32_SystemSlot",
                    "Win32_SystemSystemDriver",
                    "Win32_SystemTimeZone",
                    "Win32_SystemTrace",
                    "Win32_SystemUsers",
                    "Win32_TapeDrive",
                    "Win32_TCPIPPrinterPort",
                    "Win32_TemperatureProbe",
                    "Win32_Thread",
                    "Win32_ThreadStartTrace",
                    "Win32_ThreadStopTrace",
                    "Win32_ThreadTrace",
                    "Win32_TimeZone",
                    "Win32_TokenGroups",
                    "Win32_TokenPrivileges",
                    "Win32_Trustee",
                    "Win32_TypeLibraryAction",
                    "Win32_UninterruptiblePowerSupply",
                    "Win32_USBController",
                    "Win32_USBControllerDevice",
                    "Win32_USBHub",
                    "Win32_UserAccount",
                    "Win32_UserDesktop",
                    "Win32_UserInDomain",
                    "Win32_UserProfile",
                    "Win32_UTCTime",
                    "Win32_VideoConfiguration",
                    "Win32_VideoController",
                    "Win32_VideoSettings",
                    "Win32_VoltageProbe",
                    "Win32_Volume",
                    "Win32_VolumeChangeEvent",
                    "Win32_VolumeQuota",
                    "Win32_VolumeQuotaSetting",
                    "Win32_VolumeUserQuota",
                    "Win32_WindowsProductActivation",
                    "Win32_WMIElementSetting",
                    "Win32_WMISetting" };


    foreach (string p in fileLines)
    {
        System.Diagnostics.Process pr = new System.Diagnostics.Process();
        System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\MgmtClassGen.exe", string.Format("{0} /l cs /p {1}", p.Trim(), ".\\" + p.Trim() + ".cs"));
    }

}

public List<object> GetWMIobject(string wmi_class_name, string pathclasses)
{
    List<object> lsreturn = new List<object>();

    CSharpCodeProvider c = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters() { GenerateInMemory = true };
    cp.ReferencedAssemblies.Add("system.dll");
    cp.ReferencedAssemblies.Add("system.core.dll");
    cp.ReferencedAssemblies.Add("system.management.dll");


    CompilerResults cr1 = c.CompileAssemblyFromFile(cp, string.Format("{0}\\{1}.cs", pathclasses, wmi_class_name));
    System.Reflection.Assembly a = cr1.CompiledAssembly;


    ManagementClass MC = new ManagementClass(wmi_class_name);
    var items = MC.GetInstances();
    foreach (var item in items)
    {
        try
        {
            object[] objt = new object[1];
            objt[0] = item;
            object o = a.CreateInstance("ROOT.CIMV2.win32." + wmi_class_name.Replace("Win32_", string.Empty), true, BindingFlags.Default, null, objt, System.Globalization.CultureInfo.CurrentCulture, null);
            lsreturn.Add(o);
        }
        catch (Exception)
        { }


    }
    return lsreturn;
}

       

Retrieving info from OS is now simple…

     Utils.Utils Utility = new Utils.Utils();
     
     //Eseguire una sola volta per la generazione dei file .cs contenenti le classi Win32_*
     Utility.GenerateWMIClasses();
     
     //Ricevo le informazioni per la batteria
     var Battery = Utility.GetWMIobject("Win32_Battery", ".\\");

     //o per esempio le schede di rete
     var Networks = Utility.GetWMIobject("Win32_NetworkAdapter", ".\\");

 

I hope this post help you Sorriso

giovedì 14 giugno 2012

How To : Dynamic Lambda C#

Non è la prima volta che mi affanno sull'argomento, ma ammetto che in precedenza mi sono arreso, abbandonando l'intento. Ammetto questa volta ho probabilmente "aggirato" il problema, ma credo che la soluzione definitiva sia sempre più vicina, non vicinissima ... ma più vicina di prima. Per provare questo sorgente vi serve sicuramente: Visual studio 2010 una soluzione due progetti Ho fatto un pò di prove per il momento il risultato mi piace. Partiamo dal primo progetto che di contro è il più semplice,ed è una class library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicLambdaTester.Entity
{

    public class entity
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public class entityList : List<entity>
    {

    }

}
bravi .. è proprio la mia solita entity.. giusto perchè non mi smentisco mai. Questo è il secondo progetto che fra le referenze annnovera per forza il primo, che naturalmente per pura praticità è una console application.
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Data;
using System.Linq;
using Microsoft.CSharp;
using DynamicLambdaTester.Entity;

namespace DynamicLambdaTester
{
   class Program
    {
        
        static void Main(string[] args)
        {

            entity e1 = new entity() 
                    {ID=1,Name="Fabio",Description="Team Leader"};
            entity e2 = new entity() 
                    {ID=3,Name="Claudio",Description="CoLeader"};
            entity e3 = new entity() 
                    {ID=3,Name="Giorgio",Description="Senior Developer"};
            entity e4 = new entity()
                    {ID=2,Name="Donato",Description="Senior Developer"};
            entity e5 = new entity() 
                    {ID=3,Name="Carlo",Description="Senior DBA"};


            entityList el = new entityList() ;
            el.Add(e1);
            el.Add(e2);
            el.Add(e3);
            el.Add(e4);
            el.Add(e5);
                      

            string prms = "entityList el";
            string body = "return el.Where " + 
                    "(c => c.Description.Contains(\"Senior\")).ToList<entity>();";
          
            
            var ed = DynamicSelect("List<entity>", prms, body, el);

            for (int i = 0; i < ed.Count(); i++)
            {
                Console.WriteLine(ed[i].Name);
            }
                       
            Console.ReadKey();
        }

        public static List<entity> DynamicSelect(
                string typeRet, 
                string parameters, 
                string body, 
                entityList tDataParams)
        {

            CSharpCodeProvider c = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.core.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.ReferencedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("system.data.linq.dll");
            cp.ReferencedAssemblies.Add("[PERCORSO DEL COMPILATO DEL PRIMO PROGETTO " +
                                        @"Es. C:\USER\..\DynamicLambdaTester.Entity.dll");
           

            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            StringBuilder sb = new StringBuilder("");
            
            sb.Append("using System;\n");
            sb.Append("using System.Collections.Generic;\n");
            sb.Append("using System.Data;\n");            
            sb.Append("using System.Linq;\n");

            sb.Append("using DynamicLambdaTester.Entity;\n");
            sb.Append("namespace DynamicLambdaTester{ \n");
            sb.Append("public class LambdaExtension{ \n");
            sb.Append("public "+ typeRet +" Select("+parameters+"){\n");            
            sb.Append("try {\n");
            sb.Append(body);
            sb.Append("}\n");
            sb.Append("catch (Exception ex ) { ");
            sb.Append("  return new "+ typeRet +"();");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("}\n");

            CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                for (int i = 0; i < cr.Errors.Count; i++)
                {
                    Console.WriteLine("ERROR: " + cr.Errors[i].ErrorText );
                }
                return null;
            }

            System.Reflection.Assembly a = cr.CompiledAssembly;
            object o = a.CreateInstance("DynamicLambdaTester.LambdaExtension");

            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("Select");

            List<entity> r = (List<entity>)mi.Invoke(o, new object[] { tDataParams });

            return r;
        }        
    }
}
Non è complesso, ma abbastanza intricato. Nel main creo le entità per cui provare ad eseguire la selezione, e di contro le aggiungo all'entityList in modo poi da effettuare l'estrazione. in body ho la bella possibilità di aggiungere la lambda ( non so perchè mi viene lambada.. ma fa nulla ). DynamicSelect che cosa fa??? Bhe crea a runtime una class library che conterrà il metodo da eseguire, guarda caso, SELECT ( che per il momento lascio così ) anche se secondo me deve cambiare in WHERE ... ma per il momento va bene. L'ultima parte è noia ( ops ) è banalmente reflection con cui andiamo a chiamare il metodo attendendoci un risultato. Che dire.. chi la dura la vince.