nServiceBus is not persisting to the MessageQueue - message-queue

I'm using nServivceBus to persist a message to the Message Queue. I've ran the runmefirst.bat. The messagequeue servivce is successfully installed. When I run the web application the private queues are successfully created.
When I send the message, it's not showing up in the Message Queue. No errors are thrown. I'm stumped.
Setup
Configure config = Configure.WithWeb();
config
.StructureMapBuilder(Container)
.MsmqSubscriptionStorage()
.MsmqTransport()
.IsTransactional(true)
.PurgeOnStartup(false)
.XmlSerializer()
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
Config
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
<section name="MsmqSubscriptionStorageConfig" type="NServiceBus.Config.MsmqSubscriptionStorageConfig, NServiceBus.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<MsmqSubscriptionStorageConfig Queue="subscribe" />
<MsmqTransportConfig InputQueue="subscribe" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5"/>
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="Momntz" Endpoint="subscribe"/>
</MessageEndpointMappings>
</UnicastBusConfig>
Code
private readonly IDocumentDatabase _database;
private readonly IBus _bus;
/// <summary>
/// Initializes a new instance of the <see cref="HomeIndexCommandHandler"/> class.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="bus"></param>
public CreateUserCommandHandler(IDatabases database, IBus bus)
{
_database = database.RavenDb;
_bus = bus;
}
/// <summary>
/// Executes the specified command.
/// </summary>
/// <param name="command">The command.</param>
public void Execute(CreateUserCommand command)
{
var user = Mapper.DynamicMap<CreateUserCommand, User>(command);
user.AccountStatus = UserAccountStatus.Active;
var foundUser = CheckForDuplicateUsername(user);
if(foundUser != null)
{
throw new DuplicateUsernameException(string.Format("Username '{0}' already exists.", user.Username));
}
_database.Add(user);
var denormalizeMessage = Mapper.DynamicMap<User, UserDenormalizeMessage>(user);
_bus.Send(denormalizeMessage);
}
update
The intent is for a website to send messages to a message queue and a service to process the messages. It's very simple. I'm not looking for a response or communication between the client and server. It's one way communication.

You appear to be using the same queue address for your input queue and for your message routing config:
<MsmqTransportConfig InputQueue="subscribe" ...
and
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="Momntz" Endpoint="subscribe"/> ...
This is not correct. The MsmqTransportConfig section defines your service's local input queue. The UnicastBusConfig section defines the destination addressing for sending messages.
Have you looked at the logfile which is generated by default by log4net? There will probably be some error information in there.
You also have defined a subscription queue:
<MsmqSubscriptionStorageConfig Queue="subscribe" />
This suggests that you want your service to act as a publisher. In this case you would not use Bus.Send() but Bus.Publish(), and furthermore if this were the case then you would not need to add any routing information into the UnicastBusConfig section because this would be handled by the publish/subscribe functionality in NServiceBus.

Related

Websphere Liberty 18.0.0.3 MySQL data source object not injected

My web app is not getting the datasource which was configured in server.xml. I have added the sqlconnector jar (mysql-connector-java-8.0.12) under the folder C:\wlp\usr\shared\resources\mysql
server.xml
<!-- Enable features -->
<featureManager>
<feature>cdi-1.2</feature>
<feature>jaxrs-2.0</feature>
<feature>jdbc-4.0</feature>
<feature>jndi-1.0</feature>
<feature>jpa-2.0</feature>
<feature>localConnector-1.0</feature>
<feature>servlet-3.1</feature>
</featureManager>
<!-- Declare the jar files for MySQL access through JDBC. -->
<library id="MySQLLib">
<fileset dir="${shared.resource.dir}/mysql" includes="mysql-connector-java-8.0.12.jar"/>
</library>
<!-- Declare the runtime database -->
<dataSource jndiName="AdminWeb/jdbc/AdminDS" transactional="false">
<jdbcDriver libraryRef="MySQLLib"/>
<properties databaseName="admin" password="****" portNumber="3306" serverName="localhost" user="root"/>
</dataSource>
DAO
#Resource(name = "AdminWeb/jdbc/AdminDS",lookup="AdminWeb/jdbc/AdminDS")
DataSource dataSource;
public UserEntity getAllUsers() {
UserEntity user = new UserEntity();
Connection connection = null;
try {
System.out.println("****************1");
connection = dataSource.getConnection();
System.out.println("2");
While invoking the webapp, the getconnection method throws
[ERROR ] SRVE0777E: Exception thrown by application class 'com.fist.tools.admin.dao.UserDAO.getAllUsers:25'
java.lang.NullPointerException
Could anyone please help me on this?
The dataSource/server configuration itself looks fine. #Resource can only be injected into web components/ejb components. Does the class you are injecting into fit that description?

adding drink to favorite page on click in windows store

I am making an app of drinks for windows store.
According to requirement user can select drink as favorite.
So his favorite drinks should be shown in favorite page.
So how can I add these drinks to favorite page on button click as shown in image 1
Is it possible without using database..?
Any share of idea would be appreciated.
I am using xml file to save data on button click
I have managed to get the data from xml file in a grid on my favourite page
but it is statically done by me as I had wrote xml file by myself.
I want it to be wrote like that:
<drink>
<drinkImage>ck.png</drinkImage>
<drinkTitle>COKE</drinkTitle>
<drinkDescription>(1793-1844)</drinkDescription>
</drink>
my current file is this:
<?xml version="1.0" encoding="utf-8" ?>
<drinks>
<drink>
<drinkImage>pepsi.png</drinkImage>
<drinkTitle>PEPSI</drinkTitle>
<drinkDescription>(1793-1844)</drinkDescription>
</drink>
**<here I Want above xml on add to my favourite button click>**
</drinks>
The solution you're looking for really depends on what it is that you're wanting to get out of the adding to favourites page.
If you just want to add it to the favourites page for the duration of the app, have a ViewModel which contains the collection of favourites that you can access from any page by storing it in an IOC container (possibly using MVVMLight).
If you're wanting to then save it, you can write the favourites out to a JSON file which you can store in the local storage for the application. You'll also want to load it back into your app next time it loads.
You can do your JSON save logic as below
/// <summary>
/// Save an object of a given type as JSON to a file in the storage folder with the specified name.
/// </summary>
/// <typeparam name="T">The type of object</typeparam>
/// <param name="folder">Folder to store the file in</param>
/// <param name="data">The object to save to the file</param>
/// <param name="encoding">The encoding to save as</param>
/// <param name="fileName">The name given to the saved file</param>
/// <returns>Returns the created file.</returns>
public async Task<StorageFile> SaveAsJsonToStorageFolder<T>(StorageFolder folder, T data, Encoding encoding, string fileName)
{
if (folder == null)
throw new ArgumentNullException("folder");
if (data == null)
throw new ArgumentNullException("data");
if (fileName == null)
throw new ArgumentNullException("fileName");
string json = JsonConvert.SerializeObject(data, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
byte[] bytes = encoding.GetBytes(json);
return await this.SaveBytesToStorageFolder(folder, bytes, fileName);
}
/// <summary>
/// Saves a byte array to a file in the storage folder with the specified name.
/// </summary>
/// <param name="folder">Folder to store the file in</param>
/// <param name="bytes">Bytes to save to file</param>
/// <param name="fileName">Name to assign to the file</param>
/// <returns>Returns the created file.</returns>
public async Task<StorageFile> SaveBytesToStorageFolder(StorageFolder folder, byte[] bytes, string fileName)
{
if (folder == null)
throw new ArgumentNullException("folder");
if (bytes == null)
throw new ArgumentNullException("bytes");
if (string.IsNullOrWhiteSpace(fileName))
throw new ArgumentNullException("fileName");
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, bytes);
return file;
}

Insert XmlFile (or other) from camel route to mongoDB

I've been trying to insert a XML file into mongoDB with camel and I can't manage to make it work.
I've followed this tutorial for the first steps:
http://www.pretechsol.com/2014/09/apache-camel-mongodb-component-example.html
In my route, I convert it in JSON then use 'convertBodyTo(string.class) for mongo to recognize the file.
The code works well with regular route (sending the file to another folder for example). But when I run it for mongoDB, all I get in the console is my Process message again and again with my databased never being filled.As I don't receive any error message, I don't know how to find where the problem come from.
The mongoDB name, ip, users, password have been already checked multiple times.
I would be very grateful if someone could help me on this one. Here is the files I am using. (I will spare you the process file).
camel-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="myDb" class="com.mongodb.Mongo">
<constructor-arg index="0">
<bean class="com.mongodb.MongoURI">
<constructor-arg index="0"
value="mongodb://username:password#192.168.3.29:27017/db" />
</bean>
</constructor-arg>
</bean>
<bean id="mongodb" class="org.apache.camel.component.mongodb.MongoDbComponent"></bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="camelRoute" />
</camelContext>
<bean id="camelRoute" class="infotel.camel.project01.CamelRoute" />
Here is my RoutingFile:
#Component
public class CamelRoute extends SpringRouteBuilder {
final Processor myProcessor = new MyProcessor();
final Processor myProcessorMongo = new MyProcessorMongo();
final XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
#Override
public void configure() {
xmlJsonFormat.setForceTopLevelObject(true);
from("file:xml_files?noop=true").marshal(xmlJsonFormat).convertBodyTo(String.class).process(myProcessorMongo)
.to("mongodb:myDb?database=test_bignav&collection=doc&operation=insert");
}
}
And finally here is my main:
public class MyMain {
public static void main(String[] args) throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml");
}
}
Thanks a lot.
Edit:
Here is MyProcessorMongo edited to get the error:
public class MyProcessorMongo implements Processor{
public void process(Exchange exchange) throws Exception {
System.out.println("\n file transfered to mongo: "+ exchange.getIn().getHeader("CamelFileName"));
exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).printStackTrace();
}
}
Enable tracing with trace="true":
<camelContext trace="true" xmlns="http://camel.apache.org/schema/spring">
Dirty but quick, to get the error you can add this to you configure() method before your from :
.onException(Exception.class).handled(true).process(new Processor() {
#Override
public void process(Exchange exchange) {
exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).printStackTrace();
}
})
The handled(true) prevents your message from being processed again and again.
thanks for your help I have been able to get the error message.
The problem actually came from mongoDB itself and not camel or code. With the change on users the connection works and I'm able to insert document inside a collection.
Remove the ".process(myProcessorMongo)" from route configuration . Input xml-> json conversion->string conversion -> Mongodb. Above route will work. And you are passing the exchange object to myProcessorMongo but Out message is null so nothing will be inserted into MongoDB . Put exchange.getOut().getBody(); in the myProcessorMongo and print it.If its coming as null u have to get the input message from exchange Obj and set it back it in to Out message property in the exchange Object.

Error reading Custom Configuration Section: No parameterless constructor defined for this object

Having a horrible time reading a custom configuration section from web.config:
I am using Configuration Section Designer (http://csd.codeplex.com/).
UPDATE:
here is the error I am getting:
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for SendToTestConfig/sendToTestIndexConfig: No parameterless constructor defined for this object. (C:\TFS\Mainline\Business.Utility.SendToTest\Business.Utility.SendToTest\web.config line 20) ---> System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
Here is my auto-generated configuration section:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Business.Utility.SendToTest.Configuration
{
/// <summary>
/// The SendToTestIndexConfig Configuration Section.
/// </summary>
public partial class SendToTestIndexConfig : global::System.Configuration.ConfigurationSection
{
#region Singleton Instance
/// <summary>
/// The XML name of the SendToTestIndexConfig Configuration Section.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
internal const string SendToTestIndexConfigSectionName = "sendToTestIndexConfig";
/// <summary>
/// Gets the SendToTestIndexConfig instance.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
public static global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig Instance
{
get
{
return ((global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig)(global::System.Configuration.ConfigurationManager.GetSection(global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.SendToTestIndexConfigSectionName)));
}
}
#endregion
#region Xmlns Property
/// <summary>
/// The XML name of the <see cref="Xmlns"/> property.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
internal const string XmlnsPropertyName = "xmlns";
/// <summary>
/// Gets the XML namespace of this Configuration Section.
/// </summary>
/// <remarks>
/// This property makes sure that if the configuration file contains the XML namespace,
/// the parser doesn't throw an exception because it encounters the unknown "xmlns" attribute.
/// </remarks>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
[global::System.Configuration.ConfigurationPropertyAttribute(global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.XmlnsPropertyName, IsRequired=false, IsKey=false, IsDefaultCollection=false)]
public string Xmlns
{
get
{
return ((string)(base[global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.XmlnsPropertyName]));
}
}
#endregion
#region IsReadOnly override
/// <summary>
/// Gets a value indicating whether the element is read-only.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
public override bool IsReadOnly()
{
return false;
}
#endregion
#region appGroups Property
/// <summary>
/// The XML name of the <see cref="appGroups"/> property.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
internal const string appGroupsPropertyName = "appGroups";
/// <summary>
/// Gets or sets the appGroups.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ConfigurationSectionDesigner.CsdFileGenerator", "2.0.0.0")]
[global::System.ComponentModel.DescriptionAttribute("The appGroups.")]
[global::System.Configuration.ConfigurationPropertyAttribute(global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.appGroupsPropertyName, IsRequired=true, IsKey=false, IsDefaultCollection=false)]
public global::Business.Utility.SendToTest.Configuration.AppGroupSettingsCollection appGroups
{
get
{
return ((global::Business.Utility.SendToTest.Configuration.AppGroupSettingsCollection)(base[global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.appGroupsPropertyName]));
}
set
{
base[global::Business.Utility.SendToTest.Configuration.SendToTestIndexConfig.appGroupsPropertyName] = value;
}
}
#endregion
}
}
namespace Business.Utility.SendToTest.Configuration
{
...
And here is my config file:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="SendToTestConfig" type="System.Configuration.ConfigurationSectionGroup, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<section name="sendToTestIndexConfig" type="Business.Utility.SendToTest.Configuration.SendToTestIndexConfig, Business.Utility.SendToTest.Configuration"/>
</sectionGroup>
etc.
</configSections>
<SendToTestConfig xmlns="Business.Utility.SendToTest.Configuration">
<sendToTestIndexConfig>
<appGroups>
<!-- TODO Change indexFileNamePrefix to desired value-->
<appGroupSettings name="ItemBased" indexFileNamePrefix="S" indexFolderLocation="C:\TFS\Mainline\Business.Utility.SendToTest\Business.Utility.SendToTest" imageFolderLocation="C:\TFS\Mainline\Business.Utility.SendToTest\Business.Utility.SendToTest">
<topicEntries>
<topicEntry topicIDSuffix="DATE" addDuplicateVSAMEntry="true">
<itemSubFields>
<subField index="0" typeName="Date"/>
</itemSubFields>
</topicEntry>
<topicEntry topicIDSuffix="Item" addDuplicateVSAMEntry="true">
<itemSubFields>
<subField index="0" typeName="ItemNumber"/>
</itemSubFields>
</topicEntry>
<topicEntry topicIDSuffix="DESCR">
<itemSubFields>
<subField index="0" typeName="LongDescription"/>
</itemSubFields>
</topicEntry>
</topicEntries>
</appGroupSettings>
</appGroups>
</sendToTestIndexConfig>
</SendToTestConfig>
...
</configuration>
I have tried all of the following, but I keep getting null for the first few config (which I think makes sense), and getting the abovementioned exception for the rest.
//These return null:
SendToTestIndexConfig config = SendToTestIndexConfig.Instance;
//SendToTestIndexConfig config = (SendToTestIndexConfig) ConfigurationManager.GetSection("sendToTestIndexConfig");
//SendToTestIndexConfig configb = (SendToTestIndexConfig)WebConfigurationManager.GetSection("sendToTestIndexConfig");
//SendToTestIndexConfig configc = (SendToTestIndexConfig)WebConfigurationManager.OpenWebConfiguration(null).GetSection("sendToTestIndexConfig");
//SendToTestIndexConfig configd = (SendToTestIndexConfig)WebConfigurationManager.GetWebApplicationSection("sendToTestIndexConfig");
//SendToTestIndexConfig configf = (SendToTestIndexConfig)WebConfigurationManager.GetSection("sendToTestIndexConfig");
////These throw a "parameterless constructor error" on object "SendToTestConfig/sendToTestIndexConfig"
//SendToTestIndexConfig configg = (SendToTestIndexConfig)WebConfigurationManager.GetSection("SendToTestConfig/sendToTestIndexConfig");
//SendToTestIndexConfig configh = (SendToTestIndexConfig)WebConfigurationManager.OpenWebConfiguration(null).GetSection("SendToTestConfig/sendToTestIndexConfig");
//SendToTestIndexConfig configi = (SendToTestIndexConfig)WebConfigurationManager.GetWebApplicationSection("SendToTestConfig/sendToTestIndexConfig");
//SendToTestIndexConfig configj = (SendToTestIndexConfig)WebConfigurationManager.GetSection("SendToTestConfig/sendToTestIndexConfig");
I'm guessing it has something to do with my naming. ConfigurationManager.AppSettings works fine, so I know I have the right web.config.
Actually, the solution to the problem is succinctly stated in an example for the GenericEnumConverter on MSDN. I did the same thing you probably did and explicitly set the [TypeConverter(typeof(GenericEnumConverter))] attrbibute on one of my configuration section properties and got the same error. According to the documentation for GenericEnumConverter linked to above, you do not need to set this attribute in order to use the GenericEnumConverter type converter--it is called implicitly by the framework. Remove that attribute from your configuration property specifications, and this error should disappear and everything should just work.
Here is an example of a configuration section property that uses an Enum:
public enum UsernameFormat
{
DownLevelDomainName,
UsernameOnly,
UserPrincipalName
}
public class WindowsADElement : ConfigurationElement
{
// This property will implicitly use the GenericEnumConverter type converter.
[ConfigurationProperty("usernameFormat", IsRequired=true, DefaultValue=UsernameFormat.UserPrincipalName)]
public UsernameFormat UsernameFormat
{
get { return (UsernameFormat)this["usernameFormat"]; }
set { this["usernameFormat"] = value; }
}
Then, to use it in code:
MyConfigurationSection config = ConfigurationManager.GetSection("myConfigurationSection") as MyConfigurationSection;
UsernameFormat format = config.UsernameLookup.WindowsAD.UsernameFormat;
Hope that helps.
I am not sure if this is the best solution, but I was able to get around the problem. The error was because I was using the GenericEnumTypeConverter class to convert the config strings to the AppGroup and SubFieldTypes enums. I created my own custom TypeConverters, and it solved the problem. Apparently, GenericEnumTypeConverter has no parameterless constructors, requiring the enum type for the constructor. Would love to know if there is a way to use GenericEnumTypeConverter, but this worked for me.
This clued me in on the answer: Configuration Error With Custom Behaviour

Can I suppress the Restart request message when pushing a WAP provisioning update to a Windows Mobile device?

Our automatic maintenance procedure sends out provisioning updates like this to our devices overnight:
<wap-provisioningdoc>
<characteristic type="SoftwareDisable">
<characteristic type="DisabledSystemFiles">
<parm name="Labyrinth.exe" />
</characteristic>
</characteristic>
</wap-provisioningdoc>
This works fine, apart from it pops up a box asking the user if they want to restart now or later, specifically:
Restart
Recent changes to your device require a
restart. During this process you cannot make
or receive phone calls, including emergency
calls. Restart your device now?
Now Later
This is of course difficult to do because there is no user, just racks and racks of devices sitting there by themselves.
So, is there any way of not popping this message up and just restarting the device automatically? Possibly some registry setting or something?
You can soft reset your device via code.
Just need to p/invoke
public enum SystemPowerStates : uint
{
/// <summary>
/// On state.
/// </summary>
On = 0x00010000,
/// <summary>
/// No power, full off.
/// </summary>
Off = 0x00020000,
/// <summary>
/// Critical off.
/// </summary>
Critical = 0x00040000,
/// <summary>
/// Boot state.
/// </summary>
Boot = 0x00080000,
/// <summary>
/// Idle state.
/// </summary>
Idle = 0x00100000,
/// <summary>
/// Suspend state.
/// </summary>
Suspend = 0x00200000,
/// <summary>
/// Reset state.
/// </summary>
Reset = 0x00800000
}
[DllImport("coredll.dll")]
internal static extern int SetSystemPowerState(string psState, int StateFlags, int Options);
/// <summary>
/// Defines the System power requirement flags
/// </summary>
public enum PowerReqFlags : uint
{
POWER_NAME = 0x00000001,
POWER_FORCE = 0x00001000,
}
And call the function SetSystemPowerState, I use it enclosed in another method.
private static void DeviceReset()
{
SetSystemPowerState(
null,
(int)SystemPowerStates.Reset,
(int)PowerReqFlags.POWER_FORCE);
}