Not found exception When start the ManagementEventWatcher - c#-4.0

Not Found Exception some times while starting the MaagementEventWatcher
My code sample is given below :
try
{
string scopePath = #"\\.\root\default";
ManagementScope managementScope = new ManagementScope(scopePath);
WqlEventQuery query =
new WqlEventQuery(
"SELECT * FROM RegistryKeyChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'"
+ #"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");
registryWatcher = new ManagementEventWatcher(managementScope, query);
registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);
registryWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (registryWatcher != null)
{
registryWatcher.Stop();
}
}
Exception:
Not found
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementEventWatcher.Start()
at MTTS.LabX.RockLog.AppService.USBMonitor.AddRegistryWatcherHandler()]
Note : I checked in the registry,folder and files are found.

ManagementException "Not found" is thrown when there is not match in the WQL query. Maybe you have specified the wrong KeyPath or the KeyPath is no longer available.

Actually the problem was, In the laptops(pcs having the serial ports so COM1 port) when starting first time SERIALCOMM folder not created in the Registry because,
basically we plugged the device in the USB port or serial port the SERIALCOMM folder will create, in this case we are using WMI to get the connected comm ports from the registry.
in some laptops no USB ports and Serial Ports are connected So, the SERIALCOMM folder not created, In that time we are accessing this registry path we get the error.
so the Solution is,
try
{
string scopePath = #"\\.\root\default";
ManagementScope managementScope = new ManagementScope(scopePath);
string subkey = "HARDWARE\\DEVICEMAP\\SERIALCOMM";
using (RegistryKey prodx = Registry.LocalMachine)
{
prodx.CreateSubKey(subkey);
}
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryKeyChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE'" +
#"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");
registryWatcher = new ManagementEventWatcher(managementScope, query);
registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);
registryWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (registryWatcher != null)
{
registryWatcher.Stop();
}
}

Related

Hazelcast failed to create an ObjectName when using file|http(s) protocol

after running on this exception using hazelcast 3.6 :
java.lang.IllegalArgumentException: Failed to create an ObjectName
at
com.hazelcast.jmx.HazelcastMBean.setObjectName(HazelcastMBean.java:116)
at
com.hazelcast.jmx.ConnectionManagerMBean.(ConnectionManagerMBean.java:39)
at
com.hazelcast.jmx.InstanceMBean.createMBeans(InstanceMBean.java:74)
at com.hazelcast.jmx.InstanceMBean.(InstanceMBean.java:67) at
com.hazelcast.jmx.ManagementService.(ManagementService.java:67)
at
com.hazelcast.instance.HazelcastInstanceImpl.(HazelcastInstanceImpl.java:136)
at
com.hazelcast.instance.HazelcastInstanceFactory.constructHazelcastInstance(HazelcastInstanceFactory.java:160)
at
com.hazelcast.instance.HazelcastInstanceFactory.getOrCreateHazelcastInstance(HazelcastInstanceFactory.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.getOrCreateInstance(HazelcastServerCachingProvider.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:64)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:42)
at
com.hazelcast.cache.impl.AbstractHazelcastCachingProvider.getCacheManager(AbstractHazelcastCachingProvider.java:94)
at
com.hazelcast.cache.HazelcastCachingProvider.getCacheManager(HazelcastCachingProvider.java:131)
I took look at this part of the code, which is causing the error, on File: HazelcastServerCachingProvider.java (starting at line: 78 ):
String location = properties.getProperty(HazelcastCachingProvider.HAZELCAST_CONFIG_LOCATION);
// If config location is specified, get instance through it.
if (location != null) {
URI uri = new URI(location);
String scheme = uri.getScheme();
if (scheme == null) {
// It is a place holder
uri = new URI(System.getProperty(uri.getRawSchemeSpecificPart()));
}
ClassLoader theClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader;
final URL configURL;
if ("classpath".equals(scheme)) {
configURL = theClassLoader.getResource(uri.getRawSchemeSpecificPart());
} else if ("file".equals(scheme) || "http".equals(scheme) || "https".equals(scheme)) {
configURL = uri.toURL();
} else {
throw new URISyntaxException(location, "Unsupported protocol in configuration location URL");
}
try {
Config config = new XmlConfigBuilder(configURL).build();
config.setClassLoader(theClassLoader);
**HERE BAD INSTANCENAME IS GENERATED**
config.setInstanceName(configURL.toString());
return HazelcastInstanceFactory.getOrCreateHazelcastInstance(config);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
When using file or http(s) protocol in the passed hazelcast_config_location, we are going to fail creating the mbean, since the hazelCastInstanceName should not contain the character ‘:’, which is unfortunately part of the configURI name.
Is this a Bug or do I overlooked something??
Thanks for your response
javax ObjectName class does not support the character : and throws a MalformedObjectNameException. Hazelcast processes this exception and throws IllegalArgumentException with the message comes from it.
https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/HazelcastMBean.java#L121
https://docs.oracle.com/javase/7/docs/api/javax/management/ObjectName.html
Edit: quote function should've handled it in your case however, there is a bug in hz apparently. See: https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/ConnectionManagerMBean.java#L38

How to connect MS SQL Database using jdbc in Android Studio?

I am trying to connect MS SQL database using JDBC in Android Studio 1.1.0. I am refering to this site for connecting. Here is my code for connecting:
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionClass {
String ip = "IP_Address(for eg.192.168.5.60)";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "Andro";
String un = "username";
String password = "pwd";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
/* ConnURL = "jdbc:jtds:sqlserver://" + ip + "/"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";*/
ConnURL= "jdbc:jtds:sqlserver://IP_Address(for eg.192.168.5.60)/databaseName=Andro;user=username;password=pwd;";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
Calling connectionClass.CONN() function like this:
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
heading.setText("u"+con.toString());
String query = "select * from Usertbl where UserId='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
heading.setText("After statement");
ResultSet rs = stmt.executeQuery(query);
// heading.setText(rs.getString(1));
z = "under else block";
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
I just want to connect database with android studio. The error shows like this
Please suggest any solution or any hint to perform connectivity.
The error is because you are trying to set the text value of a textview field from the Asynchronous task.
Over here : heading.setText("u"+con.toString());
Just remove this and the error might be solved.
Also note that Asynchronous task cannot set the value of the activity component like EditText,Textview or even a button field.
i had also been trying to connect ms sql database from android studio, succeeded last night using the given link
https://www.youtube.com/watch?v=HRF8NpoFteg
note that jtds-1.2.7 must be downloaded, latest versions might not work for real mobile (i was facing this problem for one week the database connected on emulator but not on real mobile).
further after including jtds-1.2.7 gradle build might give an error of instant run kindly uncheck instant run from file -> settings -> instant run -> uncheck enable instant run.
hope it hepls!!!

Plugin code to update another entity when case is created mscrm 2011

Im new with plugin. my problem is, When the case is created, i need to update the case id into ledger. What connect this two is the leadid. in my case i rename lead as outbound call.
this is my code. I dont know whether it is correct or not. Hope you guys can help me with this because it gives me error. I manage to register it. no problem to build and register but when the case is created, it gives me error.
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.Web.Services;
/*
* Purpose: 1) To update case number into lejar
*
* Triggered upon CREATE message by record in Case form.
*/
namespace UpdateLejar
{
public class UpdateLejar : IPlugin
{
/*public void printLogFile(String exMessage, String eventMessage, String pluginFile)
{
DateTime date = DateTime.Today;
String fileName = date.ToString("yyyyMdd");
String timestamp = DateTime.Now.ToString();
string path = #"C:\CRM Integration\PLUGIN\UpdateLejar\Log\" + fileName;
//open if file exist, check file..
if (File.Exists(path))
{
//if exist, append
using (StreamWriter sw = File.AppendText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
else
{
//if no exist, create new file
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
}*/
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//for update and create event
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity targetEntity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents a connection.
if (targetEntity.LogicalName != "incident")
{
return;
}
else
{
try
{
//triggered upon create message
if (context.MessageName == "Create")
{
Guid recordid = new Guid(context.OutputParameters["incidentid"].ToString());
EntityReference app_inc_id = new EntityReference();
app_inc_id = targetEntity.GetAttributeValue<EntityReference>("new_outboundcalllid");
Entity member = service.Retrieve("new_lejer", ((EntityReference)targetEntity["new_outboundcallid"]).Id, new ColumnSet(true));
//DateTime createdon = targetEntity.GetAttributeValue<DateTime>("createdon");
if (app_inc_id != null)
{
if (targetEntity.Attributes.Contains("new_outboundcallid") == member.Attributes.Contains("new_outboundcalllistid_lejer"))
{
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
service.Update(member);
}
}
}
tracingService.Trace("Lejar updated.");
}
catch (FaultException<OrganizationServiceFault> ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
throw new InvalidPluginExecutionException("An error occurred in UpdateLejar plug-in.", ex);
}
catch (Exception ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
tracingService.Trace("UpdateLejar: {0}", ex.ToString());
throw;
}
}
}
}
}
}
Please check,
is that entity containing the attributes or not.
check it and try:
if (targetEntity.Contains("new_outboundcallid"))
((EntityReference)targetEntity["new_outboundcallid"]).Id
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
What is new_ringkasanlejarid's type? You're setting a string to it. If new_ringkasanlejarid is an entity reference, this might be causing problems.
You might want to share the error details or trace log, all we can do is assume what the problem is at the moment.

Non-unique ldap attribute name with Unboundit LDAP SDK

I am attempting to retrieve objects having several attributes with the name from netscape LDAP directory with LDAP SDK from Unboundit. The problem is that only one of the attributes are returned - I am guessing LDAP SDK relays heavily on unique attribute names, is there a way to configure it to also return non-distinct attributes as well?
#Test
public void testRetrievingUsingListener() throws LDAPException {
long currentTimeMillis = System.currentTimeMillis();
LDAPConnection connection = new LDAPConnection("xxx.xxx.xxx", 389,
"uid=xxx-websrv,ou=xxxx,dc=xxx,dc=no",
"xxxx");
SearchRequest searchRequest = new SearchRequest(
"ou=xxx,ou=xx,dc=xx,dc=xx",
SearchScope.SUB, "(uid=xxx)", SearchRequest.ALL_USER_ATTRIBUTES );
LDAPEntrySource entrySource = new LDAPEntrySource(connection,
searchRequest, true);
try {
while (true) {
try {
System.out.println("*******************************************");
Entry entry = entrySource.nextEntry();
if (entry == null) {
// There are no more entries to be read.
break;
} else {
Collection<Attribute> attributes = entry.getAttributes();
for (Attribute attr : attributes)
{
System.out.println (attr.getName() + " " + attr.getValue());
}
}
} catch (SearchResultReferenceEntrySourceException e) {
// The directory server returned a search result reference.
SearchResultReference searchReference = e
.getSearchReference();
} catch (EntrySourceException e) {
// Some kind of problem was encountered (e.g., the
// connection is no
// longer valid). See if we can continue reading entries.
if (!e.mayContinueReading()) {
break;
}
}
}
} finally {
entrySource.close();
}
System.out.println("Finished in " + (System.currentTimeMillis() - currentTimeMillis));
}
Non-unique LDAP attributes are considered multivalued and are reperesented as String array.
Use Attribute.getValues() instead of attribute.getValue.

Is it possible to use IMAP Query Terms in Javamail with GMail?

I am trying to programmatically retrieve the Call Log messages that are backup up from my android phone by a little application called SMSBackup (highly recommended).
What I want to do is to be able to retrieve the call logs for a particular day. I have tried the following program, using JavaMail:
public List<CallLogEntry> getCallLog(String username, String password, Date date, TimeZone tz) {
Store store = null;
try {
store = MailUtils.getGmailImapStore(username, password);
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new Exception("No default folder");
Folder inboxfolder = folder.getFolder("Call log");
if (inboxfolder == null)
throw new Exception("No INBOX");
inboxfolder.open(Folder.READ_ONLY);
Date fromMidnight = new Date(TimeUtils.fromMidnight(date.getTime(), tz));
Date toMidnight = new Date(TimeUtils.toMidnight(date.getTime(), 0, tz));
SentDateTerm fromTerm = new SentDateTerm(SentDateTerm.GT, fromMidnight);
SentDateTerm toTerm = new SentDateTerm(SentDateTerm.LT, toMidnight);
AndTerm searchTerms = new AndTerm(fromTerm, toTerm);
Message[] msgs = inboxfolder.search(searchTerms);
FetchProfile fp = new FetchProfile();
fp.add("Subject");
fp.add("Content");
fp.add("From");
fp.add("SentDate");
inboxfolder.fetch(msgs, fp);
List<CallLogEntry> callLog = new ArrayList<CallLogEntry>();
for (Message message : msgs) {
CallLogEntry entry = new CallLogEntry();
entry.subject = message.getSubject();
entry.body = (String) message.getContent();
callLog.add(entry);
}
inboxfolder.close(false);
store.close();
return callLog;
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
} catch (MessagingException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (store != null)
store.close();
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
return null;
}
My two utility methods (fromMidnight / toMidnight):
public static final long fromMidnight(long time, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 1);
return c.getTimeInMillis();
}
public static final long toMidnight(long time, int nDays, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time + nDays*MILLIS_IN_DAY);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTimeInMillis();
}
However, for some reason:
while eventually executing, it takes about 3 minutes to complete
I'm getting back the entire Call log, i.e. the entire content of the "Call Log" folder in my mailbox
What am I missing?
The main thing that you're missing is that the underlying IMAP SEARCH syntax supports only dates, not date-times. So your query will result in JavaMail issuing the command:
A001 SEARCH SENTBEFORE 16-JAN-2011 SENTSINCE 16-JAN-2011 ALL
(Put a breakpoint in IMAPProtocol.issueSearch() to see this.)
GMail appears to freak out on this query, which logically cannot match any messages. Try switching your logic to a single term using SentDateTerm.EQ (which maps to SENTON) and it should work:
SentDateTerm term = new SentDateTerm(SentDateTerm.EQ, date.getTime());
Message[] msgs = inboxfolder.search(term);

Resources