CodeProperty's CodeType is suddenly gone - c#

I'm busy creating an assembly that will gather CodeModel information wich in turn is used to generate code with a T4 template.
I'm struggling with CodeModel because of the lack of good information. I found a few books describing the CodeModel but only the true basics. Found no in-depth documentation.
The past week I created the mentioned assembly and the following construct worked fine for over 4 days.
/// <summary>
/// The CodeType of the property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}
Yesterday suddenly this construct no longer returns the CodeType anymore. I've now changed the code to this
/// <summary>
/// The CodeType of the property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
if (CodeProperty.IsCodeType)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
}
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}
This no longer causes an exception but the outcome is always 'null'. I'm lost. What could cause the CodeProperty to, all of a sudden, loose it's CodeType?
I really need the CodeType because a lot of code is hinging on it's information.

I was able to create a work arround like this. It's not nice but it works fine:
private FileCodeModel m_FileCodeModel;
/// <summary>
/// The FileCodeModel the entity of this property is found in.
/// </summary>
public FileCodeModel FileCodeModel
{
get
{
if (m_FileCodeModel == null)
{
m_FileCodeModel = EntityMetadata.FileCodeModel;
}
return m_FileCodeModel;
}
}
private Project m_Project;
/// <summary>
/// The project this properties entity is contained in.
/// </summary>
public Project ContainingProject
{
get
{
if (m_Project == null)
{
m_Project = FileCodeModel.Parent.ContainingProject;
}
return m_Project;
}
}
private CodeModel m_CodeModel;
/// <summary>
/// The CodeModel for the properties entity.
/// </summary>
public CodeModel CodeModel
{
get
{
if (m_CodeModel == null)
{
m_CodeModel = ContainingProject.CodeModel;
}
return m_CodeModel;
}
}
/// <summary>
/// De CodeType van de property
/// </summary>
public CodeType CodeType
{
get
{
if (!m_CodeTypeInitialized)
{
if (CodeProperty.IsCodeType)
{
CodeTypeRef codeTypeRef = CodeProperty.Type;
m_CodeType = codeTypeRef.CodeType;
}
else
{
m_CodeType = CodeModel.CodeTypeFromFullName(CodeProperty.Type.AsFullName);
}
m_CodeTypeInitialized = true;
}
return m_CodeType;
}
}

Related

StackOverFlow Exception: Could you help me about this issue? [duplicate]

This question already has answers here:
Why does Property Set throw StackOverflow exception?
(3 answers)
Closed 2 years ago.
I designed a class implementing the Builder design pattern. But creating that class using its builder, it throws System Exception that is StackOverFlow Exception. I know its builder is recursive but I only call three times its building chain. What throwing I really don't understand and it doesn't come to me logically. Below is my class that involves its own builder.
SnirgeeDosya sn = new SnirgeeDosya.SnirgeeDosyaBuilder()
.setDosyaId(0)
.setDosyaAdi("Dosya1")
.setUserId(1214)
.setDBFactory(new DatabaseFactory()).build();
public class SnirgeeDosya:ISnirgeeDosyaOracleCommands
{
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
public int userId { set { userId = value; } get { return userId; } }
public DateTime baslangicZaman { get { return DateTime.Now; } }
public String dosyaAdi { set { dosyaAdi = value; } get { return dosyaAdi; } }
private SnirgeeOracleDBWorker oracleDbWorker{ set { oracleDbWorker = value; } get { return oracleDbWorker; } }
/// <summary>
/// SnirgeeDosya olusturması sırasında kullanılır. ilgili parametreler girildikten sonra build edilip SnirgeeDosya elde edilir. Kullanım şekli aşağıdaki gibidir.
/// SnirgeeDosya sn = new SnirgeeDosya.SnirgeeDosyaBuilder().setDosyaAdi("Dosya1").setUserId(1214).setDBFactory(new DatabaseFactory()).build();
/// </summary>
public class SnirgeeDosyaBuilder
{
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
public int userId { set { userId = value; } get { return userId; } }
public String dosyaAdi { set { dosyaAdi = value; } get { return dosyaAdi; } }
public SnirgeeOracleDBWorker oracleDbWorker { set { oracleDbWorker = value; } get { return oracleDbWorker; } }
/// <summary>
/// Dosya Builder içerinde dosya adının belirlenmesi.
/// </summary>
/// <param name="dosyaadi"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDosyaAdi(String dosyaadi)
{
this.dosyaAdi = dosyaadi;
return this;
}
/// <summary>
/// Dosya Builder içerinde SnirgeeDosyasının kime ait olduğunu belirten metotdur.
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setUserId(int userid)
{
this.userId = userid;
return this;
}
/// <summary>
/// Dosya Builder içerinde SnirgeeDosyasının kime ait olduğunu belirten metotdur.
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDosyaId(int dosyaId)
{
this.dosyaId = dosyaId;
return this;
}
/// <summary>
/// Snirgee Dosyasının içerisine Veritabanı işlemleri yapan classın eklenmesi.
/// Elementlerin yazılması ve okunması sırasında bu class içerisinde kullanılacaktır.
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
public SnirgeeDosyaBuilder setDBFactory(DatabaseFactory db)
{
this.oracleDbWorker = new SnirgeeOracleDBWorker(db);
return this;
}
/// <summary>
/// dosyaAdı, kullanıcıId ve Veritabanı işlerini yapacak DatabaseFactory parametreleri atandıktan sonra Snirgee Dosyasını oluşturan methodtur.
/// Henüz veritabanı SnirgeeDosya tablosuna herhangi bir kayıt atanmaz.
/// </summary>
/// <returns></returns>
public SnirgeeDosya build()
{
return new SnirgeeDosya(this);
}
}
/// <summary>
/// SnirgeeDosya'sını oluşturan SnirgeeDosyaBuilder classı build metodu içerisinde kullanılır.
/// </summary>
/// <param name="formBuilder"></param>
private SnirgeeDosya(SnirgeeDosyaBuilder formBuilder)
{
this.dosyaId = formBuilder.dosyaId;
this.userId = formBuilder.userId;
this.dosyaAdi = formBuilder.dosyaAdi;
this.oracleDbWorker = formBuilder.oracleDbWorker;
}
}
Common mistake. Your property is calling itself in the getter/setter. So when you set dosyaId, it sets dosyaId, which sets dosyaId, which sets dosyaId, which... until the call stack is full and you get a StackOverflowException.
Change
public int dosyaId { set { dosyaId = value; } get { return dosyaId; } }
to
public int dosyaId { set; get; }
And the same for the other properties. I see no need for you to have a backing field based on what you've posted. In fact, I see no need for the set... methods either - you can just set the properties directly.
It's an infinite loop - in the property, you're setting the property, which calls the property setter, which sets the property, etc. until the exception.
Either create a member variable (with a different name, this is known as a backing field) that the property sets and gets, or, since these are very simple properties, make them auto-implemented:
public int dosyaId { get; set; }

How to read WMI data of a USB (PnP) device, in this case the hardware ids, in C#?

How can I get the hardware id from an USB device? I know how to get that id with device-manager, but I want to get it via C#. Is that possible? This is what I´ve done already, but that delivers me not the hardware if which consists of the vendor id (VID) and the product id (PID):
ManagementObjectSearcher USB = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
ManagementObjectCollection USBinfo = USB.Get();
foreach (ManagementObject MO in USBinfo)
{
serialNumber = (string)MO["DeviceID"];
name = (string)MO["Name"];
Drives.Add(new KeyValuePair<String, String>(name, serialNumber));
}
I also tried it with "PNPDeviceID" and "SerialNumber" instead of "DeviceID", but that also doesn´t replys the hardware-id that I need.
Original answer (see updated answer below)
You need to take a look at the Win32_PnPEntity WMI class. According to the mentioned description you can see, that you just need to check for HardwareID.
The following code show's that in a "quick and dirty" way, I would suggest creating a Win32_PnpEntity class which exposes the data via properties.
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
ManagementObjectCollection deviceCollection = searcher.Get();
foreach (var device in deviceCollection)
{
try
{
string caption = (string)device.GetPropertyValue("Caption");
if (caption == null)
continue;
Console.WriteLine(caption);
string[] hardwareIDs = (string[])device.GetPropertyValue("HardwareID");
if (hardwareIDs == null)
continue;
foreach (string hardwareID in hardwareIDs)
{
Console.WriteLine(hardwareID);
}
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Updated answer
As the generic question is How to read WMI data of USB (PnP) device in C#, in this case the hardware ids?, I've written a Win32_PnpEntity class (stripped of comments as the post is limited to 30000 characters? If anyone want's the commented version, drop me a line) which takes a ManageementBasObject and provides all data of that given entity as properties.
Usage:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
ManagementObjectCollection deviceCollection = searcher.Get();
foreach (var entity in deviceCollection)
{
Win32_PnPEntity device = new Win32_PnPEntity(entity);
Console.WriteLine($"Caption: {device.Caption}");
Console.WriteLine($"Description: {device.Description}");
Console.WriteLine($"Number of hardware IDs: {device.HardwareID.Length}");
foreach (string hardwareID in device.HardwareID)
{
Console.WriteLine(hardwareID);
}
Console.WriteLine();
}
The Win32_PnpEntity class:
public class Win32_PnPEntity
{
public enum AvailabilityEnum
{
/// <summary>
/// Represents the meaning "Other".
/// </summary>
Other = 0x01,
/// <summary>
/// Represents the meaning "Unknown".
/// </summary>
Unknown = 0x02,
/// <summary>
/// Represents the meaning "Running or Full Power".
/// </summary>
RunningOrFullPower = 0x03,
/// <summary>
// Represents the meaning "Warning".
/// </summary>
Warning = 0x04,
/// <summary>
/// Represents the meaning "In Test".
/// </summary>
InTest = 0x05,
/// <summary>
/// Represents the meaning "Not Applicable".
/// </summary>
NotApplicable = 0x06,
/// <summary>
/// Represents the maning "Power Off".
/// </summary>
PowerOff = 0x07,
/// <summary>
/// Represents the meaning "Off Line".
/// </summary>
OffLine = 0x08,
/// <summary>
/// Represents the meaning "Off Duty".
/// </summary>
OffDuty = 0x09,
/// <summary>
/// Represents the meaning "Degraded".
/// </summary>
Degraded = 0x0A,
/// <summary>
/// Represents the meaning "Not Installed".
/// </summary>
NotInstalled = 0x0B,
/// <summary>
/// Represents the meaning "Install Error".
/// </summary>
InstallError = 0x0C,
/// <summary>
/// Represents the meaning "Power Save - Unknown".
/// The device is known to be in a power save mode, but its exact status is unknown.
/// </summary>
PowerSave_Unknown = 0x0D,
/// <summary>
/// Represents the meaning "Power Save - Low Power Mode".
/// The device is in a power save state but still functioning, and may exhibit degraded performance.
/// </summary>
PowerSave_LowPowerMode = 0x0E,
/// <summary>
/// Represents the meaning "Power Save - Standby".
/// The device is not functioning, but could be brought to full power quickly.
/// </summary>
PowerSave_Standyby = 0x0F,
/// <summary>
/// Represents the meaning "Power Cycle".
/// </summary>
PowerCycle = 0x10,
/// <summary>
/// Represents the meaning "Power Save - Warning".
/// The device is in a warning state, though also in a power save mode.
/// </summary>
PowerSave_Warning = 0x11
}
public enum ConfigManagerErrorCodeEnum
{
/// <summary>
/// Represents the meaning "Unknown", not supported in the original WMI class.
/// </summary>
Unknown = 0xFF,
/// <summary>
/// Represents the meaning "Device is working properly.".
/// </summary>
WorkingProperly = 0x00,
/// <summary>
/// Represents the meaning "Device is not configured correctly.".
/// </summary>
DeviceNotConfiguredError = 0x01,
/// <summary>
/// Represents the meaning "Windows cannot load the driver for this device.".
/// </summary>
CannotLoadDriverError = 0x02,
/// <summary>
/// Represents the meaning "Driver for this device might be corrupted, or the system may be low on memory or other resources.".
/// </summary>
DriverCorruptedError = 0x03,
/// <summary>
/// Represents the meaning "Device is not working properly. One of its drivers or the registry might be corrupted.".
/// </summary>
NotWorkingProperlyError = 0x04,
/// <summary>
/// Represents the meaning "Driver for the device requires a resource that Windows cannot manage.".
/// </summary>
DriverResourceError = 0x05,
/// <summary>
/// Represents the meaning "Boot configuration for the device conflicts with other devices.".
/// </summary>
BootConfigurationError = 0x06,
/// <summary>
/// Represents the meaning "Cannot filter.".
/// </summary>
CannotFilterError = 0x07,
/// <summary>
/// Represents the meaning "Driver loader for the device is missing.".
/// </summary>
DriverLoaderMissingError = 0x08,
/// <summary>
/// Represents the meaning "Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.".
/// </summary>
DeviceNotWorkingProperlyFirmwareError = 0x09,
/// <summary>
/// Represents the meaning "Device cannot start.".
/// </summary>
DeviceCannotStartError = 0x0A,
/// <summary>
/// Represents the meaning "Device failed.".
/// </summary>
DeviceFailedError = 0x0B,
/// <summary>
/// Represents the meaning "Device cannot find enough free resources to use.".
/// </summary>
DeviceTooFewResourcesError = 0x0C,
/// <summary>
/// Represents the meaning "Windows cannot verify the device's resources.".
/// </summary>
VerifyDeviceResourceError = 0x0D,
/// <summary>
/// Represents the meaning "Device cannot work properly until the computer is restarted.".
/// </summary>
DeviceCannotWorkProperlyUnitlRestartError = 0x0E,
/// <summary>
/// Represents the meaning "Device is not working properly due to a possible re-enumeration problem.".
/// </summary>
DeviceNotWorkingProperlyReenumerationError = 0x0F,
/// <summary>
/// Represents the meaning "Windows cannot identify all of the resources that the device uses.".
/// </summary>
IdentifyResourcesForDeviceError = 0x10,
/// <summary>
/// Represents the meaning "Device is requesting an unknown resource type.".
/// </summary>
UnknownResourceTypeError = 0x11,
/// <summary>
/// Represents the meaning "Device drivers must be reinstalled.".
/// </summary>
DeviceDriversMustBeResinstalledError = 0x12,
/// <summary>
/// Represents the meaning "Failure using the VxD loader.".
/// </summary>
FailureUsingVxDLoaderError = 0x13,
/// <summary>
/// Represents the meaning "Registry might be corrupted.".
/// </summary>
RegistryMightBeCorruptedError = 0x14,
/// <summary>
/// Represents the meaning "System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.".
/// </summary>
SystemFailureRemovingDeviceError = 0x15,
/// <summary>
/// Represents the meaning "Device is disabled.".
/// </summary>
DeviceDisabledError = 0x16,
/// <summary>
/// Represents the meaning "System failure. If changing the device driver is ineffective, see the hardware documentation.".
/// </summary>
SystemFailureError = 0x17,
/// <summary>
/// Represents the meaning "Device is not present, not working properly, or does not have all of its drivers installed.".
/// </summary>
DeviceNotPresentError = 0x18,
/// <summary>
/// Represents the meaning "Windows is still setting up the device.".
/// </summary>
StillSettingUpTheDeviceError = 0x19,
/// <summary>
/// Represents the meaning "Windows is still setting up the device.".
/// </summary>
StillSettingUpTheDeviceError_2 = 0x1A,
/// <summary>
/// Represents the meaning "Device does not have valid log configuration.".
/// </summary>
InvalidDeviceLogConfigurationError = 0x1B,
/// <summary>
/// Represents the meaning "Device drivers are not installed.".
/// </summary>
DeviceDriversNotInstalledError = 0x1C,
/// <summary>
/// Represents the meaning "Device is disabled. The device firmware did not provide the required resources.".
/// </summary>
DeviceDisabledDueToFirmwareResourceError = 0x1D,
/// <summary>
/// Represents the meaning "Device is using an IRQ resource that another device is using.".
/// </summary>
IRQConflictError = 0x1E,
/// <summary>
/// Represents the meaning "Device is not working properly. Windows cannot load the required device drivers.".
/// </summary>
DeviceNotWorkingProperlyCannotLoadDrivers = 0x1F
}
public enum StatusInfoEnum
{
/// <summary>
/// Represents the meaning "Other".
/// </summary>
Other = 0x01,
/// <summary>
/// Represents the meaning "Unknown".
/// </summary>
Unknown = 0x02,
/// <summary>
/// Represents the meaning "Enabled".
/// </summary>
Enabled = 0x03,
/// <summary>
/// Represents the meaning "Disabled".
/// </summary>
Disabled = 0x04,
/// <summary>
/// Represents the meaning "Not Applicable".
/// </summary>
NotApplicable = 0x05
}
private ManagementBaseObject managementObject;
public Win32_PnPEntity(ManagementBaseObject managementObject)
{
if (managementObject == null)
{
throw new ArgumentNullException(nameof(managementObject));
}
this.managementObject = managementObject;
}
public AvailabilityEnum Availability
{
get
{
try
{
Int16 value = (Int16)this.managementObject.GetPropertyValue("Availability");
if (!Enum.IsDefined(typeof(AvailabilityEnum), value))
{
// Handle not supported values here
throw new NotSupportedException($"The value {value} is not supported for conversion to the {nameof(AvailabilityEnum)} enumeration.");
}
return (AvailabilityEnum)value;
}
catch
{
// Handle exception caused by accessing the property value.
return AvailabilityEnum.Unknown;
}
}
}
public string Caption
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Caption");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string ClassGuid
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("ClassGuid");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string[] CompatibleID
{
get
{
try
{
string[] value = (string[])this.managementObject.GetPropertyValue("ClassGuid");
if (value == null)
// Handle null value.
return new string[0];
return value;
}
catch
{
// Handle exception caused by accessing the property value.
return new string[0];
}
}
}
public ConfigManagerErrorCodeEnum ConfigManagerErrorCode
{
get
{
try
{
Int16 value = (Int16)this.managementObject.GetPropertyValue("ConfigManagerErrorCode");
if (!Enum.IsDefined(typeof(ConfigManagerErrorCodeEnum), value))
{
// Handle not supported values here
throw new NotSupportedException($"The value {value} is not supported for conversion to the {nameof(ConfigManagerErrorCodeEnum)} enumeration.");
}
return (ConfigManagerErrorCodeEnum)value;
}
catch
{
// Handle exception caused by accessing the property value.
return ConfigManagerErrorCodeEnum.Unknown;
}
}
}
public bool ConfigManagerUserConfig
{
get
{
try
{
return (bool)this.managementObject.GetPropertyValue("ConfigManagerUserConfig");
}
catch
{
// Handle exception caused by accessing the property value.
return false;
}
}
}
public string CreationClassName
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("CreationClassName");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string Description
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Description");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string DeviceID
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("DeviceID");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public bool ErrorCleared
{
get
{
try
{
return (bool)this.managementObject.GetPropertyValue("ErrorCleared");
}
catch
{
// Handle exception caused by accessing the property value.
return false;
}
}
}
public string ErrorDescription
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("ErrorDescription");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string[] HardwareID
{
get
{
try
{
string[] value = (string[])this.managementObject.GetPropertyValue("HardwareID");
if (value == null)
// Handle null value.
return new string[0];
return value;
}
catch
{
// Handle exception caused by accessing the property value.
return new string[0];
}
}
}
public DateTime InstallDate
{
get
{
try
{
DateTime value = (DateTime)this.managementObject.GetPropertyValue("InstallDate");
if (value == null)
// Handle null value.
return DateTime.MinValue;
return value;
}
catch
{
// Handle exception caused by accessing the property value.
return DateTime.MinValue;
}
}
}
public UInt32 LastErrorCode
{
get
{
try
{
return (UInt32)this.managementObject.GetPropertyValue("LastErrorCode");
}
catch
{
// Handle exception caused by accessing the property value.
return 0;
}
}
}
public string Manufacturer
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Manufacturer");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string Name
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Name");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string PNPClass
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("PNPClass");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string PNPDeviceID
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("PNPDeviceID");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public UInt16[] PowerManagementCapabilities
{
get
{
try
{
UInt16[] value = (UInt16[])this.managementObject.GetPropertyValue("PowerManagementCapabilities");
if (value == null)
// Handle null value.
return new UInt16[0];
return value;
}
catch
{
// Handle exception caused by accessing the property value.
return new UInt16[0];
}
}
}
public bool PowerManagementSupported
{
get
{
try
{
return (bool)this.managementObject.GetPropertyValue("PowerManagementSupported");
}
catch
{
// Handle exception caused by accessing the property value.
return false;
}
}
}
public bool Present
{
get
{
try
{
return (bool)this.managementObject.GetPropertyValue("Present");
}
catch
{
// Handle exception caused by accessing the property value.
return false;
}
}
}
public string Service
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Service");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string Status
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("Status");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public StatusInfoEnum StatusInfo
{
get
{
try
{
Int16 value = (Int16)this.managementObject.GetPropertyValue("StatusInfo");
if (!Enum.IsDefined(typeof(StatusInfoEnum), value))
{
// Handle not supported values here
throw new NotSupportedException($"The value {value} is not supported for conversion to the {nameof(StatusInfoEnum)} enumeration.");
}
return (StatusInfoEnum)value;
}
catch
{
// Handle exception caused by accessing the property value.
return StatusInfoEnum.NotApplicable;
}
}
}
public string SystemCreationClassName
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("SystemCreationClassName");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
public string SystemName
{
get
{
try
{
return (string)this.managementObject.GetPropertyValue("SystemName");
}
catch
{
// Handle exception caused by accessing the property value.
return "Unknown";
}
}
}
}
In Console application, add refrence-->.Net-->system.Management-->add
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management; // need to add System.Management to your project references.
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(#"Select * From Win32_USBHub"))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
}
}

Is there a newer way to accomplish what this article recommends?

I like the idea of this Agent Service that allows me to add jobs without affecting existing code, but the article is pretty old. Has something come along since 2005 that would be a better way of accomplishing the same thing?
I am limited to .Net, but I can use any version of the framework.
http://visualstudiomagazine.com/articles/2005/05/01/create-a-net-agent.aspx
Edit: Here is a summary of what I'm trying to do
Have a .Net service that can read a configuration file to dynamically load DLLs to perform tasks.
The service has a dynamic object loader that maps XML to classes in the DLLs to perform the tasks.
An example of the xml file and the class it maps is below. Basically, the service can read the Job from the xml, instantiate an instance of the CustomerAttendeeCreateNotificationWorker and call the Run() method. As a developer, I can make any number of these classes and implement whatever I want in the Run() method. Also note that the entry for "CustomerAttendanceNotificationTemplateName" gets assigned to a property with the same name on the instantiated object.
<?xml version="1.0" encoding="utf-8"?>
<Manager type="Task.RemotingManager, TaskClasses">
<Jobs type="Task.TaskJob, TaskBase" Name="CustomerAttendeeCreateNotificationWorker Worker">
<Worker type="TaskWorkers.CustomerAttendeeCreateNotificationWorker, TaskWorkers"
Description="Inserts records into NotificationQueue for CustomerAttendees"
CustomerAttendanceNotificationTemplateName ="CustomerAttendanceNotificationTemplateName"
/>
<Schedulers type="Task.FixedIntervalScheduler, TaskClasses"
DaysOfWeek="Everyday"
Frequency="00:05:00"
StartTime="00:00:00"
EndTime="23:55:00"
/>
</Jobs>
<Jobs type="Task.TaskJob, TaskBase" Name="SendNotificationWorker Worker">
<Worker type="TaskWorkers.SendNotificationWorker, TaskWorkers"
Description="Sends messages from NotificationQueue"
/>
<Schedulers type="Task.FixedIntervalScheduler, TaskClasses"
DaysOfWeek="Everyday"
Frequency="00:05:00"
StartTime="00:00:00"
EndTime="23:55:00"
/>
</Jobs>/>
</Manager>
/// <summary>
/// The customer attendee create notification worker.
/// </summary>
[Serializable]
public class CustomerAttendeeCreateNotificationWorker : TaskWorker
{
#region Constants
/// <summary>
/// The stat e_ critical.
/// </summary>
private const int StateCritical = 1;
/// <summary>
/// The stat e_ ok.
/// </summary>
private const int StateOk = 0;
#endregion
#region Fields
/// <summary>
/// The customer notification setting name.
/// </summary>
private string customerAttendanceNotificationTemplateName;
#endregion
#region Public Properties
/// <summary>
/// The customer notification setting name.
/// </summary>
public string CustomerAttendanceNotificationTemplateName
{
get
{
return this.customerAttendanceNotificationTemplateName;
}
set
{
this.customerAttendanceNotificationTemplateName = value;
}
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
public ILogger Logger { get; set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// The run.
/// </summary>
/// <returns>
/// The <see cref="TaskResult" />.
/// </returns>
public override TaskResult Run()
{
StringBuilder errorStringBuilder = new StringBuilder();
string errorLineTemplate = "Time: {0} Database: {1} Error Message: {2}" + Environment.NewLine;
bool isError = false;
IUnitOfWork configUnitOfWork = new GenericUnitOfWork<DCCShowConfigContext>();
TradeshowService tradeshowService = new TradeshowService(configUnitOfWork);
List<Tradeshow> tradeshows = tradeshowService.GetAll().Where(t => t.Status == "OPEN").ToList();
string connectionStringTemplate = ConfigurationManager.ConnectionStrings["DCCTradeshow"].ConnectionString;
int customerNotificationSettingGroupId = Convert.ToInt32(ConfigurationManager.AppSettings["NotificationSettingGroupId"]);
foreach (Tradeshow tradeshow in tradeshows)
{
try
{
string connectionString = string.Format(connectionStringTemplate, tradeshow.DbName);
IUnitOfWork unitOfWork = new TradeshowUnitOfWork(connectionString);
NotificationService notificationService = new NotificationService(unitOfWork);
notificationService.InsertCustomerAttendanceNotifications(tradeshow.TradeshowId, customerNotificationSettingGroupId, this.customerAttendanceNotificationTemplateName);
}
catch (Exception exception)
{
isError = true;
errorStringBuilder.AppendLine(string.Format(errorLineTemplate, DateTime.Now, tradeshow.DbName, exception.Message));
}
}
TaskResult result;
if (isError)
{
result = new TaskResult(StateOk, TaskResultStatus.Exception, "Errors Occured", errorStringBuilder.ToString());
}
else
{
result = new TaskResult(StateOk, TaskResultStatus.Ok,"All Good", "All Good");
}
return result;
}
#endregion
}`

Why does this code cause xsd.exe error, "You must implement a default accessor on System.Configuration.ConfigurationLockCollection"?

Hello StackOverFlow users,
Iam trying to create an XSD from a dll that i created, but when i try to generate the XSD i get the following error message:
You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.
(Also tried different framework version (Did not work))
Command that gets executed:
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools>xsd "J:\
Programming\C#\NightBitsLogger Library\NightBitsLogger\bin\Debug\NightBitsLogger
.dll"
Does anyone know what i have to do to have a default accessor for the ConfigurationLockCollection?
(Because it seems that this is a bug in the .NET framework)
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections;
namespace NightBitsLogger.Configuration
{
/// <summary>
/// This class is an abstract class for a Collection of Config Elements
/// </summary>
/// <typeparam name="T"></typeparam>
///
[ConfigurationCollection(typeof(ConfigurationItem), AddItemName = "ConfigurationElement" )]
public abstract class CollectionOfElements<T> : ConfigurationElementCollection
where T : ConfigurationItem, new()
{
/// <summary>
/// Default Accessor for the collections
/// </summary>
[ConfigurationProperty("ConfigurationCollection", IsRequired = true)]
public CollectionOfElements<ConfigurationItem> ConfigurationCollection
{
get
{
return base["ConfigurationCollection"] as CollectionOfElements<ConfigurationItem>;
}
}
/// <summary>
/// Create and return a new Configuration Element
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
/// <summary>
/// Return the element key.
/// </summary>
/// <param name="element"></param>
/// <returns>(ConfigurationElement)key</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((ConfigurationItem)element).Name;
}
/// <summary>
/// Return the element with the given index
/// Basic accessor for elements
/// </summary>
/// <param name="index"></param>
/// <returns>[Element]byIndex</returns>
public T this[int index]
{
get
{
return (T)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Add a element to the collection
/// </summary>
/// <param name="collectionOfLoggerElement"></param>
public void Add(T collectionOfLoggerElement)
{
BaseAdd(collectionOfLoggerElement);
}
/// <summary>
/// Return the element with the given index
/// </summary>
/// <param name="name"></param>
/// <returns>[Element]byName</returns>
public new T this[string name]
{
get
{
return (T)BaseGet(name);
}
}
}
/// <summary>
/// The CollectionOfLoggers Collection
/// </summary>
[ConfigurationCollection(typeof(CollectionOfLoggersElement), AddItemName = "CollectionOfLoggers", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class CollectionOfLoggers : CollectionOfElements<CollectionOfLoggersElement>
{
// Do nothing
}
/// <summary>
/// The FileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(FileLoggerElement), AddItemName = "fileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class FileLoggers : CollectionOfElements<FileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The RollingDateFileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(RollingDateFileLoggerElement), AddItemName = "rollingDateFileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class RollingDateFileLoggers : CollectionOfElements<RollingDateFileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The RollingSizeFileLogger Collection
/// </summary>
[ConfigurationCollection(typeof(RollingSizeFileLoggerElement), AddItemName = "rollingSizeFileLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class RollingSizeFileLoggers : CollectionOfElements<RollingSizeFileLoggerElement>
{
// Do nothing
}
/// <summary>
/// The EmailLogger Collection
/// </summary>
[ConfigurationCollection(typeof(EmailLoggerElement), AddItemName = "emailLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class EmailLoggers : CollectionOfElements<EmailLoggerElement>
{
// Do nothing
}
/// <summary>
/// The SocketLogger Collection
/// </summary>
[ConfigurationCollection(typeof(SocketLoggerElement), AddItemName = "socketLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class SocketLoggers : CollectionOfElements<SocketLoggerElement>
{
// Do nothing
}
/// <summary>
/// The WindowsEventLogLogger Collection
/// </summary>
[ConfigurationCollection(typeof(WindowsEventLogLoggerElement), AddItemName = "WindowsEventLogLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class WindowsEventLogLoggers : CollectionOfElements<WindowsEventLogLoggerElement>
{
// Do nothing
}
/// <summary>
/// The ConsoleLogger Collection
/// </summary>
[ConfigurationCollection(typeof(ConsoleLoggerElement), AddItemName = "consoleLogger", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ConsoleLoggers : CollectionOfElements<ConsoleLoggerElement>
{
// Do nothing
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.ComponentModel;
namespace NightBitsLogger.Configuration
{
/// <summary>
/// This is the baseClass that represents a Config Item (Logger)
/// </summary>
public class ConfigurationItem : ConfigurationSection
{
/// <summary>
/// Get the configuration
/// </summary>
/// <returns></returns>
public static ConfigurationItem GetConfiguration()
{
ConfigurationItem configuration = ConfigurationManager.GetSection("NightBitsLogger.Configuration") as ConfigurationItem;
if (configuration != null)
{
return configuration;
}
return new ConfigurationItem();
}
/// <summary>
/// Occurs after the element is deserialized
/// </summary>
///
protected override void PostDeserialize()
{
base.PostDeserialize();
Validate();
}
/// <summary>
/// Validate the element. Throw a exception if not valid.
/// </summary>
protected virtual void Validate()
{
if ((IncludeCategories.Trim() != "") && (ExcludeCategories.Trim() != ""))
{
throw new ConfigurationErrorsException("logging element can have either includeCategories or excludeCategories, but not both.");
}
}
/// <summary>
/// Return true if the Logger Element is configured for the current machine; otherwise return false.
/// </summary>
/// <returns></returns>
public bool IsConfiguredForThisMachine()
{
var machineNames = Machine.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return (machineNames.Length == 0) || new List<string>(machineNames).Exists(name => name.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase));
}
/// <summary>
/// Get the name of the Logger
/// </summary>
[ConfigurationProperty("name", DefaultValue = "", IsKey = true, IsRequired = true)]
[Description("The name of the logger")]
public string Name
{
get
{
return (string)this["name"];
}
}
/// <summary>
/// The machine names (separated by commas) for which the Logger will be created. An empty value creates it on all machines.
/// </summary>
[ConfigurationProperty("machine", DefaultValue = "", IsRequired = false)]
[Description("The machine names (separated by commas) for which this logger will be created. Leaving it empty will create it on all machines")]
public string Machine
{
get
{
return (string)this["machine"];
}
}
/// <summary>
/// Check if the Internal Exception Logging is enabled
/// </summary>
[ConfigurationProperty("enableInternalExceptionLogging", DefaultValue = false, IsRequired = false)]
[Description("true if the internal exceptionLogging is enabled; otherwise false")]
public bool IsInternalLoggingEnabled
{
get
{
return (bool)this["isInternalLoggingEnabled"];
}
}
/// <summary>
/// Check if the Logger is enabled
/// </summary>
[ConfigurationProperty("isEnabled", DefaultValue = true, IsRequired = false)]
[Description("true if the logger is enabled; otherwise false")]
public bool IsEnabled
{
get
{
return (bool)this["isEnabled"];
}
}
/// <summary>
/// The LogLevel of the Logger
/// </summary>
[ConfigurationProperty("logLevel", DefaultValue = LogLevel.Debug, IsRequired = false)]
[Description("The logLevel of the logger")]
public LogLevel LogLevel
{
get
{
return (LogLevel)this["logLevel"];
}
}
/// <summary>
/// Categories to include (leave blank for all)
/// </summary>
[ConfigurationProperty("includeCategories", DefaultValue = "", IsRequired = false)]
[Description("The categories, separated by commas, to include when logging. Leave blank to include everything.")]
public string IncludeCategories
{
get
{
return (string)this["includeCategories"];
}
}
/// <summary>
/// Categories to exclude
/// </summary>
[ConfigurationProperty("excludeCategories", DefaultValue = "", IsRequired = false)]
[Description("The categories, separated by commas, to exclude when logging.")]
public string ExcludeCategories
{
get
{
return (string)this["excludeCategories"];
}
}
/// <summary>
/// If true, wrap the Logger in an KeepLoggingLogger.
/// </summary>
[ConfigurationProperty("keepLogging", DefaultValue = false, IsRequired = false)]
[Description("if true, the logger will be wrapped in a KeepLoggingLogger")]
public bool keepLogging
{
get
{
return (bool)this["keepLogging"];
}
}
/// <summary>
/// If true, wrap the Logger in an AsynchronousLogger.
/// </summary>
[ConfigurationProperty("isAsynchronous", DefaultValue = false, IsRequired = false)]
[Description("if true, the logger will be wrapped in a AsynchronousLogger")]
public bool IsAsynchronous
{
get
{
return (bool)this["isAsynchronous"];
}
}
/// <summary>
/// The FormatString for the Logger
/// </summary>
[ConfigurationProperty("formatString", DefaultValue = "", IsRequired = false)]
[Description("The format string of the logger. If blank, it will use the format string of the enclosing section (the CollectionOfLoggers).")]
public virtual string FormatString
{
get
{
return (string)this["formatString"];
}
}
}
}

Stored Procedure loses connection

I have an ASP.NET MVC project in which the model is managed through .NET entities and it seems that some times it loses the connection, but this happens only on stored procedures.
I get the following error:
Execution of the command requires an open and available connection. The connection's current state is broken.
Why is this happening?
Code
public ObjectResult<Categories> GetCategoriesStructure() {
return ObjectContext.getCategoriesStructure();
}
var catss = GetCategoriesStructure().ToList();
this exception occurs when I am trying to assign the List to catss variable
Object Context Instantiation
public abstract class ObjectContextManager {
/// <summary>
/// Returns a reference to an ObjectContext instance.
/// </summary>
public abstract TObjectContext GetObjectContext<TObjectContext>()
where TObjectContext : ObjectContext, new();
}
public abstract class BaseDAO<TObjectContext, TEntity> : IBaseDAO<TObjectContext, TEntity>
where TObjectContext : System.Data.Objects.ObjectContext, new()
where TEntity : System.Data.Objects.DataClasses.EntityObject {
private ObjectContextManager _objectContextManager;
/// <summary>
/// Returns the current ObjectContextManager instance. Encapsulated the
/// _objectContextManager field to show it as an association on the class diagram.
/// </summary>
private ObjectContextManager ObjectContextManager {
get { return _objectContextManager; }
set { _objectContextManager = value; }
}
/// <summary>
/// Returns an ObjectContext object.
/// </summary>
protected internal TObjectContext ObjectContext {
get {
if (ObjectContextManager == null)
this.InstantiateObjectContextManager();
return ObjectContextManager.GetObjectContext<TObjectContext>();
}
}
/// <summary>
/// Default constructor.
/// </summary>
public BaseDAO() { }
/// <summary>
/// Instantiates a new ObjectContextManager based on application configuration settings.
/// </summary>
private void InstantiateObjectContextManager() {
/* Retrieve ObjectContextManager configuration settings: */
Hashtable ocManagerConfiguration = ConfigurationManager.GetSection("ObjectContextManagement.ObjectContext") as Hashtable;
if (ocManagerConfiguration != null && ocManagerConfiguration.ContainsKey("managerType")) {
string managerTypeName = ocManagerConfiguration["managerType"] as string;
if (string.IsNullOrEmpty(managerTypeName))
throw new ConfigurationErrorsException("The managerType attribute is empty.");
else
managerTypeName = managerTypeName.Trim().ToLower();
try {
/* Try to create a type based on it's name: */
Assembly frameworkAssembly = Assembly.GetAssembly(typeof(ObjectContextManager));
Type managerType = frameworkAssembly.GetType(managerTypeName, true, true);
/* Try to create a new instance of the specified ObjectContextManager type: */
this.ObjectContextManager = Activator.CreateInstance(managerType) as ObjectContextManager;
} catch (Exception e) {
throw new ConfigurationErrorsException("The managerType specified in the configuration is not valid.", e);
}
} else
throw new ConfigurationErrorsException("ObjectContext tag or its managerType attribute is missing in the configuration.");
}
/// <summary>
/// Persists all changes to the underlying datastore.
/// </summary>
public void SaveAllObjectChanges() {
this.ObjectContext.SaveChanges();
}
/// <summary>
/// Adds a new entity object to the context.
/// </summary>
/// <param name="newObject">A new object.</param>
public virtual void Add(TEntity newObject) {
this.ObjectContext.AddObject(newObject.GetType().Name, newObject);
}
/// <summary>
/// Deletes an entity object.
/// </summary>
/// <param name="obsoleteObject">An obsolete object.</param>
public virtual void Delete(TEntity obsoleteObject) {
this.ObjectContext.DeleteObject(obsoleteObject);
}
public void Detach(TEntity obsoleteObject) {
this.ObjectContext.Detach(obsoleteObject);
}
/// <summary>
/// Updates the changed entity object to the context.
/// </summary>
/// <param name="newObject">A new object.</param>
public virtual void Update(TEntity newObject) {
ObjectContext.ApplyPropertyChanges(newObject.GetType().Name, newObject);
ObjectContext.Refresh(RefreshMode.ClientWins, newObject);
}
public virtual TEntity LoadByKey(String propertyName, Object keyValue) {
IEnumerable<KeyValuePair<string, object>> entityKeyValues =
new KeyValuePair<string, object>[] {
new KeyValuePair<string, object>(propertyName, keyValue) };
// Create the key for a specific SalesOrderHeader object.
EntityKey key = new EntityKey(this.ObjectContext.GetType().Name + "." + typeof(TEntity).Name, entityKeyValues);
return (TEntity)this.ObjectContext.GetObjectByKey(key);
}
#region IBaseDAO<TObjectContext,TEntity> Members
public bool validation(TEntity newObject) {
return newObject.GetType().Name.ToString() == "Int32";
}
#endregion
}
Without knowing how you are instantiating your ObjectContext, I'll throw something in the answer bucket here.
This is how I do my Entity Framework commands and connections (for small simple projects at least):
using (MyEntities context = new MyEntities())
{
return context.getCategoriesStructure();
}
You can also optionally pass in a connection string when instantiating your context (if not, it will use the one in your app.config):
new MyEntities("...connection string...")
If this does not help your issue, please help us understand your code a little better by posting how you are creating your ObjectContext. You could at least attempt to do it this way to see if it works; that will tell you whether it is an issue with your connection string or not.

Categories

Resources