MSMQQueueManagement error when creating a class instance - interop

I have a routine to get the counts on a MSMQ queue. I have been using this code for years on 2003 and 2008 server with no trouble. I am now updating the code to run on 2012R2 server and to test this I am compiling with VS2013 premium on Windows 8.1 using the following code:
String sPath;
Int32 nCount = 0;
Object oPath, oNull, oServer;
String [] sParts;
Char [] sSeps = { ':', '\\' };
MSMQ.MSMQQueueManagementClass mgmt;
//
// The configuration path is a standard .net path. For DCOM we need the
// DIRECT= prefixed
//
sPath = "DIRECT=OS:" + m_QueueConfig.QueuePath;
//
// Split the string looking for the sever name
//
sParts = sPath.Split( sSeps, StringSplitOptions.RemoveEmptyEntries );
//
// Get the count from the server
//
mgmt = new MSMQ.MSMQQueueManagementClass();
try
{
oPath = sPath;
oNull = Type.Missing;
if( sParts.Length < 2 || sParts[1] == "." )
oServer = Environment.MachineName;
else
oServer = sParts[1];
mgmt.Init( ref oServer, ref oNull, ref oPath );
nCount = mgmt.MessageCount;
}
catch( Exception )
{
nCount = 0;
}
finally
{
Marshal.ReleaseComObject( mgmt );
}
return nCount;
This will error on the "mgmt. = new MSMQ.MSMQQueueManagementClass()" statement with the following error:
Retrieving the COM class factory for component with CLSID {33B6D07E-F27D-42FA-B2D7-BF82E11E9374} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
Looking in the HKEY_CLASSES_ROOT hive I can find 39CE96FE-F4C5-4484-A143-4C2D5D324229 which pointed to the MQOA.DLL in system32, but not the CLSID from the error, which is what a 80040154 is.
I have tried creating a new typelib using the system32/mqoa.dll but I still get the same error. So what I am doing wrong?
According to the registry I have MSMQ version 6.2.9200 installed and it works with my application I just can't get the management interface to load.

mgmt.Init( ref oServer, ref oNull, ref oPath );
The MSMQQueueManagement interface does not have an Init() method. Looks to me like you are mixing up different coclasses. The 39CE96FE guid is for MSMQManagement, the 33B6D07E guid is for MSMQQueueManagment. The latter one is not supposed to appear in the registry so the runtime error is entirely expected. Fix:
mgmt = new MSMQ.MSMQManagement();
// etc..

Related

ADO fails to access oracle in win10

My company has long been using ADO to communicate with database, Oracle 10 or 11 typically. This has been working fine in win7 or Windows XP era. But recently some software running on Win10 or Win7 with IE updating from IE8 to IE11 couldn't connect to database with ADO. The code and error is as follow:
_ConnectionPtr m_pConnection;
try
{
hr = m_pConnection->Open(_bstr_t(m_strConnection), _bstr_t(lpstrUserID), _bstr_t(lpstrPassword), NULL);
return hr == S_OK;
}
catch(_com_error &e)
{
dump_com_error(e);
return FALSE;
}
It works fine in win7 but throws exception in win10, the exception object gives information as follow:
_com_error &e:
m_hresult = E_FAIL
[0] = 0x536a8590 _com_error::`scalar deleting destructor'(unsigned int)
m_perrinfo = 0x013aaaa0
IUNKOWN
__vfptr = 0x532d120c
[0] = 0x533001e0
[1] = 0x533003c0
[2] = 0x532fedc0
m_pszMsg = 0x00000000 <Bad Ptr>
And the description in the exception object is:
CADODataBase Error
Code = 80004005
Code meaning = undefined error
Source = OraOLEDB
Description = ORA-12154: TNS: unable to resolve given connection identifier
What could lead to this problem and how could I fix it? Thanks.

UWP VPN - VpnPlugin connect implementation throws exception in StartWithMainTransport

Kindly see the UWP code snippet below tried on Windows 10 desktop using Visual Studio 2017 community edition.
The code implements Custom IVpnPlugin module. When system's VPN configuration is selected to this app and connect is done, the application's task gets triggered and VPN plugin's "Connect()" method gets invoked.
However, following code steps face exception while executing StartWithMainTransport(…).
("The operation was cancelled by user") on Visual Studio.
On the system's VPN settings following error is seen - "remote access service ip configuration is unusable"
I think I am passing correctly v4 and v6 address to the channel->StartWithMainTransport(…) API which are bound to my m/c network I/f. What other validations may have caused this issue. I do not want to configure certificates etc for the VpnChannel as I plan to implement encapsulate and decapsulate myself in VpnPlugin.
// Sample Plugin's connect implementation
void TunnelPlugin::Connect(Windows::Networking::Vpn::VpnChannel^ channel)
{
this->dSock = ref new DatagramSocket();
channel->AssociateTransport(this->dSock, nullptr); // No difference even if this statement is moved after ConnectAsync().
Platform::String^ svcName = "22111";
auto result = create_task(dSock->BindServiceNameAsync(svcName));
result.get();
// Connect to the destination tunnel address on UDP socket.
HostName^ remoteTunnelIP = ref new HostName("192.168.1.137");
Platform::String^ remoteTunnelPort = "22112";
result = create_task(this->dSock->ConnectAsync(remoteTunnelIP, remoteTunnelPort));
result.get();
VpnChannelConfiguration^ chanCfg = channel->Configuration;
// IP destinations to be routed via VPN
VpnRouteAssignment^ routeScope = ref new VpnRouteAssignment();
routeScope->Ipv4InclusionRoutes->Append(ref new VpnRoute(ref new HostName("192.168.1.111"), 32));
Vector<HostName^>^ localV4Addrs = ref new Vector<HostName^>;
localV4Addrs->Append(ref new HostName("192.168.1.133")); // Local host name to be bound.
Vector<HostName^>^ localV6Addrs = ref new Vector<HostName^>;
localV6Addrs->Append(ref new HostName("fc00::44fd:d3ed:b02a:a05e"));
Vector<HostName^>^ dnsServers = ref new Vector<HostName^>;
dnsServers->Append(ref new HostName("1.1.1.1"));
VpnDomainNameInfo^ dnsInfo = ref new VpnDomainNameInfo(".", VpnDomainNameType::Suffix, dnsServers, ref new Vector<HostName^>);
VpnDomainNameAssignment^ dnsAssignment = ref new VpnDomainNameAssignment;
dnsAssignment->DomainNameList->Append(dnsInfo);
try
{
// Throws exception here.
channel->StartWithMainTransport(localV4Addrs->GetView(), localV6Addrs->GetView(), nullptr, routeScope, dnsAssignment, 1400, 1412, false, this->dSock);
}
catch (Exception^ exc)
{
auto type = exc->GetType();
Platform::String^ str = exc->ToString();
}
}

Various errors using VisionServiceClient in XamarinForms

I am trying to create a simple Xamarin forms app which allows the user to browse for or take a photo and have azure cognitive services tag the photo using a custom vision model.
I am unable to get the client to successfully authenticate or find a resource per the error message in the exception produced by the VisionServiceClient. Am I missing something? What would be the correct values to use for the arguments to VisionServiceClient?
All keys have been removed from the below images, they are populated.
Exception thrown in VS2017:
'Microsoft.ProjectOxford.Vision.ClientException' in System.Private.CoreLib.dll
Call to VisionServiceClient:
private const string endpoint = #"https://eastus2.api.cognitive.microsoft.com/vision/prediction/v1.0";
private const string key = "";
VisionServiceClient visionClient = new VisionServiceClient(key, endpoint);
VisualFeature[] features = { VisualFeature.Tags, VisualFeature.Categories, VisualFeature.Description };
try
{
AnalysisResult temp = await visionClient.AnalyzeImageAsync(imageStream,
features.ToList(), null);
return temp;
}
catch(Exception ex)
{
return null;
}
VS Exception Error:
Azure Portal for cognitive services:
Custom Vision Portal:
It looks like you're confusing the Computer Vision and the Custom Vision APIs. You are attempting to use the client SDK for the former using the API key of the latter.
For .NET languages, you'll want the Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction NuGet package.
Your code will end up looking something like this:
ICustomVisionPredictionClient client = new CustomVisionPredictionClient()
{
ApiKey = PredictionKey,
Endpoint = "https://southcentralus.api.cognitive.microsoft.com"
};
ImagePrediction prediction = await client.PredictImageAsync(ProjectId, stream, IterationId);
Thank you to cthrash for the extended help and talking with me in chat. Using his post along with a little troubleshooting I have figured out what works for me. The code is super clunky but it was just to test and make sure I'm able to do this. To answer the question:
Nuget packages and classes
Using cthrash's post I was able to get both the training and prediction nuget packages installed, which are the correct packages for this particular application. I needed the following classes:
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models
Endpoint Root
Following some of the steps Here I determined that the endpoint URL's only need to be the root, not the full URL provided in the Custom Vision Portal. For instance,
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/
Was changed to
https://southcentralus.api.cognitive.microsoft.com
I used both the key and endpoint from the Custom Vision Portal and making that change I was able to use both a training and prediction client to pull the projects and iterations.
Getting Project Id
In order to use CustomVisionPredictionClient.PredictImageAsync you need a Guid for the project id and an iteration id if a default iteration is not set in the portal.
I tested two ways to get the project id,
Using project id string from portal
Grab the project id string from the portal under the project settings.
For the first argument to PredictImageAsync pass
Guid.Parse(projectId)
Using the training client
Create a new CustomVisionTrainingClient
To get a list of <Project> use
TrainingClient.GetProjects().ToList()
In my case I only had a single project so I would just need the first element.
Guid projectId = projects[0].Id
Getting Iteration Id
To get the iteration id of a project you need the CustomVisionTrainingClient.
Create the client
To get a list of <Iteration> use
client.GetIterations(projectId).ToList()
In my case I had only a single iteration so I just need the first element.
Guid iterationId = iterations[0].Id
I am now able to use my model to classify images. In the code below, fileStream is the image stream passed to the model.
public async Task<string> Predict(Stream fileStream)
{
string projectId = "";
//string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.2/Training/";
string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/";
string trainingKey = "";
//string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/";
string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
string predictionKey = "";
CustomVisionTrainingClient trainingClient = new CustomVisionTrainingClient
{
ApiKey = trainingKey,
Endpoint = trainingEndpoint
};
List<Project> projects = new List<Project>();
try
{
projects = trainingClient.GetProjects().ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to get projects:\n\n" + ex.Message);
return "Unable to obtain projects.";
}
Guid ProjectId = Guid.Empty;
if(projects.Count > 0)
{
ProjectId = projects[0].Id;
}
if (ProjectId == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project ID");
return "Unable to obtain project id.";
}
List<Iteration> iterations = new List<Iteration>();
try
{
iterations = trainingClient.GetIterations(ProjectId).ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to obtain iterations.");
return "Unable to obtain iterations.";
}
foreach(Iteration itr in iterations)
{
Debug.WriteLine(itr.Name + "\t" + itr.Id + "\n");
}
Guid iteration = Guid.Empty;
if(iterations.Count > 0)
{
iteration = iterations[0].Id;
}
if(iteration == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project iteration.");
return "Unable to obtain project iteration";
}
CustomVisionPredictionClient predictionClient = new CustomVisionPredictionClient
{
ApiKey = predictionKey,
Endpoint = predictionEndpoint
};
var result = await predictionClient.PredictImageAsync(Guid.Parse(projectId), fileStream, iteration);
string resultStr = string.Empty;
foreach(PredictionModel pred in result.Predictions)
{
if(pred.Probability >= 0.85)
resultStr += pred.TagName + " ";
}
return resultStr;
}

Create Pervasive Database using Distributed Tuning Objects (DTO)

I am writing an application in C# (.NET 4.0) which has to integrate with another, much older application. Part of the requirement is to integrate with a much older program that uses Pervasive PSQL Version 9. I asked this question about accessing the database without having to install an ODBC DSN. Part of the answer (thanks very much) is that I need to create a database using DTO.
I've used COM interop to access the dto2.dll COM library, and have read the samples, but I am having problems creating the database. Here is a summary of the code I'm using.
var session = new DtoSession();
var result = session.Connect("localhost", "", "");
Assert.AreEqual(dtoResult.Dto_Success, result);
testDB = new DtoDatabase {
Session = session,
Name = "Test1",
Ddfpath = #"C:\TEMP\DATA\DDF",
DataPath = #"C:\TEMP\DATA",
};
result = session.Databases.Add(testDB);
Assert.AreEqual(dtoResult.Dto_Success, result);
No matter what values I use for the Name and paths, that final Assert always fails. The error code is Dto_errDuplicateName. If I do not include the Session property I get a different error code (7039).
Has anyone done this successfully? What am I doing wrong?
I believe you are missing the Flags property of the DtoDatabase object. I had the following code in my archive as an example of adding a database with DTO. This code was probably written when DTO was first released but it works and the only difference I can see is the Flags property.
DtoSession session = new DtoSession();
dtoResult result;
result = session.Connect("localhost", "","");
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error connecting. Error code: " + result.ToString());
return;
}
DtoDatabase testDB = new DtoDatabase();
testDB.Name = "Test1";
testDB.DataPath = #"C:\DATA";
testDB.DdfPath = #"C:\DATA";
testDB.Flags = dtoDbFlags.dtoDbFlagNotApplicable;
result = session.Databases.Add(testDB);
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error Adding. Error code: " + result.ToString());
return;
}
Console.WriteLine("DB Added.");

Show ErrorList Windows in Visual Studio 2010 Addin

I have Win7 64 bits, Visual Studio 2010, and I have developed an Addin for Vs2010.
I try show messages in Error List Windows VS.
I use ErrorListProvider in OnBuildProjConfigDone build event for Addin
this._buildEvents.OnBuildProjConfigDone += new _dispBuildEvents_OnBuildProjConfigDoneEventHandler(_buildEvents_OnBuildProjConfigDone);
I get this error InvalidOperationException
The service 'Microsoft.VisualStudio.Shell.Interop.IVsTaskList' must be
installed for this feature to work. Ensure that this service is
available.
Connect
public partial class Connect : IDTExtensibility2, IDTCommandTarget, System.Windows.Forms.IWin32Window, IOleCommandTarget
OnBuildProjConfigDone
void _buildEvents_OnBuildProjConfigDone(string project, string projectConfig, string platform, string solutionConfig, bool success)
{
// Omitted
if (!resul)
{
project.DTE.ExecuteCommand("Build.Cancel");
var errorListHelper = new ErrorListHelper();
ErrorListProvider errorProvider = errorListHelper.GetErrorListProvider();
var newError = new ErrorTask();
newError.ErrorCategory = TaskErrorCategory.Message;
newError.Category = TaskCategory.BuildCompile;
newError.Text = "Cualquier mensaje de error aqui";
errorProvider.Tasks.Add(newError);
}
}
ErrorListHelper
public class ErrorListHelper : System.IServiceProvider
{
public ErrorListProvider GetErrorListProvider()
{
ErrorListProvider provider = new ErrorListProvider(this);
provider.ProviderName = "Provider";
provider.ProviderGuid = System.Guid.NewGuid();
return provider;
}
public object GetService(Type serviceType)
{
return Package.GetGlobalService(serviceType);
}
}
Suggestion by #JohnL: I put a breakpoint in my GetService method and Package.GetGlobalService is returning null.
Any suggestions?
Ryan Molden (MSFT) says:
Package.GetGlobalService is relying on at least one MPF package (from
the specific version of MPF you are referencing) having been loaded.
Since you yourself are an AddIn not a Package you can't guarantee that
in any way.
You should pass something like new
ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider))) as the argument to ErrorListProvide
Package.GetGlobalService is returning null.
I use this code in my Addin. I test it and I get not error, and I can show errors and warnings in ErrorList Windows VS. I'll testing more for safely.
public partial class Connect
{
ErrorListProvider _errorListProvider = null;
void CreateErrorListProvider()
{
if (_errorListProvider == null)
{
System.IServiceProvider serviceProvider = new ServiceProvider(_applicationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
_errorListProvider = new ErrorListProvider(serviceProvider);
_errorListProvider.ProviderName = "custom Errors";
_errorListProvider.ProviderGuid = new Guid("xxxxxxxxxxxxxx");
}
}

Resources