How to set CCSID for MQQueueManager from code? - c#

I have some strange problem. I think I followed documentation correctly but my code doesn't work. I have this very simple hard coded test (NUnit):
[TestFixture]
public class MQQueueTests {
public const string MessageContent = "<test>This is test message</test>";
public static void Main(string[] args) {
var tests = new MQQueueTests();
tests.PutAndGetMessage();
}
[Test]
public void PutAndGetMessage() {
var properties = new Hashtable
{
{MQC.HOST_NAME_PROPERTY, "TestServer"},
{MQC.CHANNEL_PROPERTY, "Test.Channel"},
{MQC.PORT_PROPERTY, 1415},
// Is this correct? It looks like it is not
// enough because adding this line didn't solve
// the problem.
{MQC.CCSID_PROPERTY, 437}
};
using (var manager = new MQQueueManager("Test.Queue.Manager", properties)) {
using (MQQueue queue = manager.AccessQueue("Test.Queue",
MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_AS_Q_DEF)) {
MQMessage message = new MQMessage();
message.WriteUTF(MessageContent);
queue.Put(message);
MQMessage readMessage = new MQMessage();
queue.Get(readMessage);
Assert.AreEqual(MessageContent, readMessage.ReadUTF());
queue.Close();
}
manager.Disconnect();
}
}
}
I'm running the test application either from console or through Resharper 6 test runner. If I run the application in test runner I always get following exception:
IBM.WMQ.MQException : MQRC_CHANNEL_CONFIG_ERROR (reason code is 2539)
The exception is thrown by MQQueueManager.Connect (called by its constructor).
If I check MQ logs I see:
AMQ9541: CCSID supplied for data conversion not supported.
EXPLANATION: The program ended because, either the source CCSID '437'
or the target CCSID '852' is not valid, or is not currently supported.
ACTION: Correct the CCSID that is not valid, or ensure that the
requested CCSID can be supported.
If I run the application from the console I got the same error but if I change the code page for console by calling
chcp 437
My test application works. How can I configure code page from code?

Well I found a workaround - it can probably solve my problem but I'm not very satisfied with it. I can set up MQCCSID environment variable either globally or by calling:
Environment.SetEnvironmentVariable("MQCCSID", "437");
That will configure code page. Still I would like to use properties of a new MQQueueManager instance to setup code page.

Both of these are answers correct. For Windows Forms Project setting the environment variable MQCCSID the same as the ccsid of the Queue Manager that you are trying to connect will be enough.
- the 2nd solution
HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet->Control->Nls->CodePage>OEMCP value.
i had a web application(web forms) that only worked with the 2nd solution

change your system locale to English(United States), on windows 7 Regional Settings -> Administrative->Change System locale. also after do that you can check it in regedit value.
regedit->HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet->Control->Nls->CodePage check OEMCP value.

Related

Setting Outlook automatic reply signature using C# is only partly working

I am trying to set the default Outlook signature for both new messages and replies using C#.
Everything is working as expected for new messages (meaning that when I create a new message in Outlook, I can see the default signature), but nothing shows up when I reply to messages (or forward them).
This seems weird for two reasons:
In Outlook, I can see in the signature manager that that the default signature for replies is set properly. If I select another signature and select "Auto_Signature" again, everything starts working as expected, so it's not a problem with the signature itself.
The new messages signature is set the same way as the replies signature and that one works.
Here is the code that I am using to set the default signatures:
using Microsoft.Office.Interop.Word;
private void ApplyDefaultSignatureExecuted(object? obj)
{
var signaturesFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft\\Signatures");
var fileName = Path.Combine(signaturesFolder, "Auto_Signature.htm");
using (var writer = new StreamWriter(fileName))
{
writer.WriteLine("<html><body>");
writer.WriteLine("<div><p><i></span></b></p></div>");
writer.WriteLine(HttpUtility.HtmlEncode("Signature that was generated via C#"));
writer.WriteLine("</i></p><p><b><span style='font-size:24.0pt'>");
writer.WriteLine(HttpUtility.HtmlEncode("Name goes here"));
writer.WriteLine("</span></b></p></div>");
writer.WriteLine("</body></html>");
}
Application oWord = new Application();
EmailOptions oOptions = oWord.Application.EmailOptions;
oOptions.EmailSignature.NewMessageSignature = "Auto_Signature";
// This is the line that should be setting the auto-reply signature
oOptions.EmailSignature.ReplyMessageSignature = "Auto_Signature";
//Release Word, not sure if this has any effect as I get the same results with or without those lines
System.Runtime.InteropServices.Marshal.ReleaseComObject(oOptions);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
}
And here are some screenshots to go along with my explanation:
Reply - Signature does not appear automatically
Signature manager - Default signatures are set properly by C#, and changing to another one and back makes everything work as it should
New message - Signature appears automatically
According to everything I have read, this should be working since setting the signature for new message and replies is the same code, but it's not. I am using Office 365 and I don't mind switching libraries if that solves my issues.
I got it working by simply changing the line
oOptions.EmailSignature.ReplyMessageSignature = "Auto_Signature";
To
oOptions.EmailSignature.ReplyMessageSignature = oOptions.EmailSignature.NewMessageSignature;
Everything is now working exactly the same for replies and forwards as it does for new messages.

Xamarin says "Allow Multiple Bind To Same Port only allowed on Windows". What do I do?

I'm trying to use SocketLite.PCL with my iOS/Android solution in Xamarin,
but I get the message Allow Multiple Bind To Same Port only allowed on Windows when running it.
What does it mean and how do I fix it?
EDIT:
Example code I'm using can be found here: https://github.com/1iveowl/SocketLite.PCL
I put the following code inside rotected async override void OnStart(){} of the app:
var udpReceived = new UdpSocketReceiver();
await udpReceived.StartListeningAsync(4992, allowMultipleBindToSamePort: true);
var udpMessageSubscriber = udpReceived.ObservableMessages.Subscribe(
msg =>
{
System.Console.WriteLine($"Remote adrres: {msg.RemoteAddress}");
System.Console.WriteLine($"Remote port: {msg.RemotePort}");
var str = System.Text.Encoding.UTF8.GetString(msg.ByteData);
System.Console.WriteLine($"Messsage: {str}");
},
ex =>
{
// Exceptions received here
}
);
EDIT 2:
Ok, so setting allowMultipleBindToSamePort to false stopped that error.
Now I get the error Address already in use.
However I am still curious as to what allowMultipleBindToSamePort is used for.
As you can see in the new documentation:
IMPORTANT: Please notice that the parameter allowMultipleBindToSamePort will only work on Windows. On other platforms it should be set to false
About However I am still curious as to what allowMultipleBindToSamePort is used for.
There is a good and complete explanation on this post, you can read more in the following stackoverflow post

Updating from Selenium.Webdriver 2.44 to 2.46 causes NullReferenceException

We have just started working with Appium in my company, using it to automate testing on websites and webapps.
Testing Framework = Nunit 2.6.4
Language used = C#
Mobile Device = Samsung Galaxy S4
Android version = 5.0.1
I've used Selenium and Nunit to test on Desktop before on a simple website, using [Test], [TestCase] and [TestCaseSource] attributes in my tests.
Following the advice in the article of the answer to:
How to integrate Appium with C#?
(Quicker article link here:
http://blogs.technet.com/b/antino/archive/2014/09/22/how-to-set-up-a-basic-working-appium-test-environment.aspx)
An associate set up a solution that would do a simple navigation to StackOverflow, click a link and assert:
namespace AppiumTests
{
using System;
using NUnit.Framework;
using AppiumTests.Helpers;
using AppiumTest.Framework;
using OpenQA.Selenium; /* Appium is based on Selenium, we need to include it */
using OpenQA.Selenium.Appium; /* This is Appium */
using OpenQA.Selenium.Appium.Interfaces; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Appium.MultiTouch; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Interactions; /* Not needed for commands shown here. It might be needed in single tests for automation */
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Appium.Android;
[TestFixture]
public class AndroidAppiumTestSuite
{
private AppiumDriver driver;
private static Uri testServerAddress = new Uri(TestServers.WindowsServer);
private static TimeSpan INIT_TIMEOUT_SEC = TimeSpan.FromSeconds(180); /* Change this to a more reasonable value */
private static TimeSpan IMPLICIT_TIMEOUT_SEC = TimeSpan.FromSeconds(10); /* Change this to a more reasonable value */
[SetUp]
public void BeforeAll()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
TestCapabilities testCapabilities = new TestCapabilities();
//testCapabilities.App = "";
testCapabilities.AutoWebView = true;
testCapabilities.AutomationName = "<just a name>";
testCapabilities.BrowserName = "Chrome"; // Leave empty otherwise you test on browsers
testCapabilities.DeviceName = "Needed if testing on IOS on a specific device. This will be the UDID";
testCapabilities.FwkVersion = "1.0"; // Not really needed
testCapabilities.Platform = TestCapabilities.DevicePlatform.Android; // Or IOS
testCapabilities.PlatformVersion = "5.0.1"; // Not really needed
testCapabilities.AssignAppiumCapabilities(ref capabilities);
driver = new AndroidDriver(testServerAddress, capabilities, INIT_TIMEOUT_SEC);
driver.Manage().Timeouts().ImplicitlyWait(IMPLICIT_TIMEOUT_SEC);
}
[TearDown]
public void AfterAll()
{
TestContext.CurrentContext.Result.ToString();
driver.Quit(); // Always quit, if you don't, next test session will fail
}
/// <summary>
/// Just a simple test to heck out Appium environment.
/// </summary>
[Test]
public void CheckTestEnvironment()
{
driver.Navigate().GoToUrl("http://stackoverflow.com");
driver.FindElementByCssSelector("body > div.topbar > div.network-items > div.login-links-container > a").Click();
Assert.AreEqual("Log in using any of the following services", (driver.FindElementByCssSelector("h2.title")).Text);
}
Many thanks to Andrea Tino for this starting point.
Now this worked fine, and my colleague who set this up and showed it to me has gone on holiday leaving me the task of adding in our existing tests and tweaking bits here and there.
I added in my testclass which requires the Webdriver.Support pacakge to be installed, which depends on Webdriver >= 2.46.0
Now, when I run my code, I get a null reference exception on this line:
driver = new AndroidDriver(testServerAddress, capabilities, INIT_TIMEOUT_SEC);
This is the error I'm getting:
AppiumTests.AndroidAppiumTestSuite.CheckTestEnvironment:
SetUp : System.NullReferenceException : Object reference not set to an instance of an object.
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
So my thought was that something in 2.46.0 meant I need to supply another capability, but I've been banging my head against this for two days now with no progress.
I have a screenshot of the appium server communication, but I'm not able to link images yet XD so here is it pasted in:
info: [debug] Device launched! Ready for commands
info: [debug] Setting command timeout to the default of 60 secs
info: [debug] Appium session started with sessionId 4575272bba7d11c85414d48cf53ac8e3
info: <-- POST /wd/hub/session 303 10828.204 ms - 70
info: --> GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3 {}
info: Proxying [GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3] to [GET http://127.0.0.1:9515/wd/hub/session/4575272bba7d11c85414d48cf53ac8e3] with body: {}
info: Got response with status 200: {"sessionId":"4575272bba7d11c85414d48cf53ac8e3","status":0,"value":{"acceptSslCerts":true,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"browserName":"chrome","chrome":{},"cssSelect...
info: <-- GET /wd/hub/session/4575272bba7d11c85414d48cf53ac8e3 200 6.770 ms - 506
info: --> POST /wd/hub/session {"desiredCapabilities":{"javascriptEnabled":true,"device":"Android","platformName":"Android","deviceName":"d5cb5478","browserName":"Chrome","platformVersion":"5.0.1","browserVersion":"43.0.2357.93"}}
error: Failed to start an Appium session, err was: Error: Requested a new session but one was in progress
So from here I can see that its trying to start a new session when I've already started one, but I can't figure out the cause!
So here's how to get around the Appium-specific half of the problem -- I don't have an answer for your NullReferenceException.
That Appium error is caused when the port you're trying to start Appium WebDriver on is already in use.
To manually fix this
You can do $telnet ip port to figure out what Process ID you need to kill.
You can find the address/port by checking the value for what new Uri(TestServers.WindowsServer); returns.
Exit any emulators
Once you have the PID then you can do $kill -9 pid and start your Appium server like normal.
A proper solution
If you are having this problem regularly, it may be because your script is ending without quitting the Appium WebDriver.
Usually you put the teardown code for the WebDriver (driver.quit()) in the #After section of your tests, or in your base TestCase class.
I see that you have a teardown section there -- so maybe you got into this bad state during a previous session? Either way, the manual fix should get you back to working order.

C# program connecting to example DBus daemon always gets 'Access is denied: DBus.BusObject'

For our current project we are using DBus (1.6.n).
It is largely accessed from C++ in shared memory mode, and this works really well.
I am now trying to access the same DBus from a C# program.
In order to try things out first, I downloaded the latest version of dbus-sharp I could find, and started the daemon included in the download to see if I could connect to it from my test C# app.
Whenever I make a connection, the daemon console shows that I am communicating with it, but as soon as I try to access any methods on the connection I get the error;
'Access is denied: DBus.BusObject'
Here is the code I have tried;
DBus.Bus dBus = null;
try
{
//input address comes from the UI and ends up as "tcp:host=localhost,port=12345";
//dBus = new Bus(InputAddress.Text + inputAddressExtension.Text);
//string s = dBus.GetId();
//dBus.Close();
//DBus.Bus bus = DBus.Bus.System;
//DBus.Bus bus = Bus.Open(InputAddress.Text + inputAddressExtension.Text);
//DBus.Bus bus = DBus.Bus.Session;
//DBus.Bus bus = DBus.Bus.Starter;
var conn = Connection.Open(InputAddress.Text + inputAddressExtension.Text);
var bus = conn.GetObject<Introspectable>(#"org.freedesktop.DBus.Introspectable", new ObjectPath("/org/freedesktop/DBus/Introspectable"));
bus.Introspect();
}
finally
{
if(dBus != null)
dBus.Close();
}
The commented code produces the same error eventually too.
I have stepped through with the debugger and it always gets to the following code in the TypeImplementer.cs;
public Type GetImplementation (Type declType)
{
Type retT;
lock (getImplLock)
if (map.TryGetValue (declType, out retT))
return retT;
string proxyName = declType.FullName + "Proxy";
Type parentType;
if (declType.IsInterface)
parentType = typeof (BusObject);
else
parentType = declType;
TypeBuilder typeB = modB.DefineType (proxyName, TypeAttributes.Class | TypeAttributes.Public, parentType);
if (declType.IsInterface)
Implement (typeB, declType);
foreach (Type iface in declType.GetInterfaces ())
Implement (typeB, iface);
retT = typeB.CreateType (); <======== Fails here ==========
lock (getImplLock)
map[declType] = retT;
return retT;
}
I have not found any useful examples or documentation about accessing DBus from C#, and there seem to be few recent entries about this anywhere, so maybe no-one else is trying this.
I am running the daemon in the same folder as the test program.
As I am running on windows, the daemon is listening on the tcp setting;
string addr = "tcp:host=localhost,port=12345";
Since this is the example included with the download, I thought it would be really simple to get it going, but alas no luck yet.
Has anyone else been here and know the next piece of the puzzle?
Any ideas would be appreciated.
Having received no comment or response, I will answer the question with the information I have found since asking it.
There appears to be no useful C# interface to DBus. (By useful, I mean one that works!)
The only information or examples I could find are not up to date and no effort appears to be being expended on providing a working interface.
I have decided to interface with DBus by using a C++ implementation written as a Windows service, and my C# program will send messages to DBus via the service. This seems to work ok, so satisfies the business need.
I am disappointed not to be able to get the C# to DBus working, but there are lots of service bus implementations that work on Windows, so in future I will look at implementing those instead of DBus.
If anyone does come up with a workable, documented solution to accessing DBus from C# on Windows, I would still be interested to see it.
I had the same error when I created new test project and add dbus cs source files to it main project assembly. It was when IBusProxy type dynamically created in dynamically created assembly.
asmB = AppDomain.CurrentDomain.DefineDynamicAssembly (new AssemblyName ("NDesk.DBus.Proxies"), canSave ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run);
modB = asmB.DefineDynamicModule ("NDesk.DBus.Proxies");
......
retT = typeB.CreateType ();
I think it was cause current running assembly isnt friendly for created assembly. And just when I add to project compiled NDesk.DBus.dll this error disappeared.

ActiveDirectory error 0x8000500c when traversing properties

I got the following snippet (SomeName/SomeDomain contains real values in my code)
var entry = new DirectoryEntry("LDAP://CN=SomeName,OU=All Groups,dc=SomeDomain,dc=com");
foreach (object property in entry.Properties)
{
Console.WriteLine(property);
}
It prints OK for the first 21 properties, but then fail with:
COMException {"Unknown error (0x8000500c)"}
at System.DirectoryServices.PropertyValueCollection.PopulateList()
at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
at System.DirectoryServices.PropertyCollection.PropertyEnumerator.get_Entry()
at System.DirectoryServices.PropertyCollection.PropertyEnumerator.get_Current()
at ActiveDirectory.Tests.IntegrationTests.ObjectFactoryTests.TestMethod1() in MyTests.cs:line 22
Why? How can I prevent it?
Update
It's a custom attribute that fails.
I've tried to use entry.RefreshCache() and entry.RefreshCache(new[]{"theAttributeName"}) before enumerating the properties (which didn't help).
Update2
entry.InvokeGet("theAttributeName") works (and without RefreshCache).
Can someone explain why?
Update3
It works if I supply the FQDN to the item: LDAP://srv00014.ssab.com/CN=SomeName,xxxx
Bounty
I'm looking for an answer which addresses the following:
Why entry.Properties["customAttributeName"] fails with the mentioned exception
Why entry.InvokeGet("customAttributeName") works
The cause of the exception
How to get both working
If one wants to access a custom attribute from a machine that is not
part of the domain where the custom attribute resides (the credentials
of the logged in user don't matter) one needs to pass the fully
qualified name of the object is trying to access otherwise the schema
cache on the client machine is not properly refreshed, nevermind all
the schema.refresh() calls you make
Found here. This sounds like your problem, given the updates made to the question.
Using the Err.exe tool here
http://www.microsoft.com/download/en/details.aspx?id=985
It spits out:
for hex 0x8000500c / decimal -2147463156 :
E_ADS_CANT_CONVERT_DATATYPE adserr.h
The directory datatype cannot be converted to/from a native
DS datatype
1 matches found for "0x8000500c"
Googled "The directory datatype cannot be converted to/from a native" and found this KB:
http://support.microsoft.com/kb/907462
I have the same failure. I´m read and saw a lot of questions about the error 0x8000500c by listing attribute from a DirectoryEntry.
I could see, with the Process Monitor (Sysinternals), that my process has read a schema file. This schema file is saved under
C:\Users\xxxx\AppData\Local\Microsoft\Windows\SchCache\xyz.sch.
Remove this file and the program works fine :)
I just encountered the issue and mine was with a web application.
I had this bit of code which pulls the user out of windows authentication in IIS and pulls their info from AD.
using (var context = new PrincipalContext(ContextType.Domain))
{
var name = UserPrincipal.Current.DisplayName;
var principal = UserPrincipal.FindByIdentity(context, this.user.Identity.Name);
if (principal != null)
{
this.fullName = principal.GivenName + " " + principal.Surname;
}
else
{
this.fullName = string.Empty;
}
}
This worked fine in my tests, but when I published the website it would come up with this error on FindByIdentity call.
I fixed the issue by using correct user for the app-pool of the website. As soon as I fixed that, this started working.
I had the same problem with a custom attribute of a weird data type. I had a utility program that would extract the value, but some more structured code in a service that would not.
The utility was working directly with a SearchResult object, while the service was using a DirectoryEntry.
It distilled out to this.
SearchResult result;
result.Properties[customProp]; // might work for you
result.Properties[customProp][0]; // works for me. see below
using (DirectoryEntry entry = result.GetDirectoryEntry())
{
entry.Properties[customProp]; // fails
entry.InvokeGet(customProp); // fails as well for the weird data
}
My gut feel is that the SearchResult is a little less of an enforcer and returns back whatever it has.
When this is converted to a DirectoryEntry, this code munges the weird data type so that even InvokeGet fails.
My actual extraction code with the extra [0] looks like:
byte[] bytes = (byte[])((result.Properties[customProp][0]));
String customValue = System.Text.Encoding.UTF8.GetString(bytes);
I picked up the second line from another posting on the site.

Categories