I have list of over 20 queues that needs to be added as private queue in MSMQ.
Is there a way to do it using
Command Line
C# programming
If there is a way to do using some sort of script or .net programming then I could add it with out manually inputting it and causing typos.
Please let me know.
thanks
using System.Messaging;
//...
void CreateQueue(string qname) {
if (!MessageQueue.Exists(qname)) MessageQueue.Create(qname);
}
You can only create private queues on your local computer. For more information see: Creating Queues
For command line, you can create a .vbs file with following content:
Option Explicit
Dim objInfo
Dim objQue
Dim objMsg
Dim strFormatName ' Destination
strFormatName = "direct=os:.\private$\test"
Set objInfo = CreateObject("MSMQ.MSMQQueueInfo")
Set objMsg = CreateObject("MSMQ.MSMQMessage")
objMsg.Label = "my message"
objMsg.Body = "This is a sample message."
objInfo.FormatName = strFormatName
set objQue = objInfo.Open( 2, 0 )
' Send Message
objMsg.Send objQue
' Close Destination
objQue.Close
Set objMsg = Nothing
Set objInfo = Nothing
msgbox "Done..."
A bit late on this, however I only started working on them now.
To add to Richard's answer, you can create public queues.
you need the hostname though and admin access to that machine.
public static MessageQueue CreatePrivate(string name) {
string path = string.Format(#".\private$\{0}", name);
if (!MessageQueue.Exists(path)) {
MessageQueue.Create(path);
return new MessageQueue(path);
}
return new MessageQueue(path);
}
public static MessageQueue CreatePublic(string hostname,string queuename) {
string path = string.Format(#"{0}\{1}", hostname,queuename);
if (!MessageQueue.Exists(path)) {
MessageQueue.Create(path);
return new MessageQueue(path);
}
return new MessageQueue(path);
}
}
Related
For a while i've been trying to make a standalone program in c#, which uses the BrowseTags function from iHistorian_SDK. (iFix 5.8 and Historian 7.0)
First I made this function in VBA where it works great, but due to VBA being single threaded, I want to moive it out of VBA.
My VBA code that works today:
Public connectedServer As Object
Public myServerManager As Object
Private Sub TestBrowseFunction()
Call BrowseTagsFromHistorianCollector("SVNF-IFIX-HIS01", "SVNF-IFIX-SCA01_iFIX")
End Sub
Public Function BrowseTagsFromHistorianCollector(ByVal HistServer As String, ByVal HistCollector As String, Optional AdditionsOnly As Boolean = False, Optional SourceFilter As String = "*", Optional DescriptionFilter As String = "*")
On Error Resume Next
Dim MyTags As Variant
Dim Tag As Variant
Set connectedServer = Nothing
Set MyServerManager = CreateObject("iHistorian_SDK.ServerManager")
DoEvents
'Make sure Historian is installed correctly'
If MyServerManager Is Nothing Then
Err.Raise 0, , "Error Creating iHistorian Server Manager - please check to see if Historain Client is correctly installed on your system", vbOKOnly, "test"
Exit Function
End If
'Create iHistorian server object'
Set connectedServer = CreateObject("iHistorian_SDK.Server")
'Check to see if the connection is established, else connect.'
If CheckConnection = False Then connectedServer.Connect (HistServer)
If CheckConnection = True Then
'Browse the collector for tags.'
Set MyTags = connectedServer.collectors.Item(HistCollector).BrowseTags(AdditionsOnly, SourceFilter, DescriptionFilter)
'Loop all the tags from the collector'
For Each Tag In MyTags.Item
'INSERT CODE TO DO FOR EACH TAG HERE!'
Debug.Print Tag.tagName
Next
End If
End Function
' make sure that we are connected to a server'
Public Function CheckConnection() As Boolean
On Error GoTo errc
If connectedServer Is Nothing Then
CheckConnection = False
Exit Function
End If
If Not connectedServer.Connected Then
CheckConnection = False
Exit Function
End If
If connectedServer.ServerTime < CDate("1/1/1970") Then
CheckConnection = False
Exit Function
End If
CheckConnection = True
Exit Function
errc:
CheckConnection = False
End Function
This works great.
But in my attempt to convert the same function over to C# i keep getting errors.
First i connect to my historian server, which is pretty painless.
tsStatus.Text = "Connecting to " + HistServer;
try
{
connectedServer = new iHistorian_SDK.Server();
connectedServer.Connect(HistServer);
tsStatus.Text = "Connected to " + HistServer;
}
catch (Exception ex)
{
Debug.Print("Server connection threw exception: " + ex);
tsStatus.Text = "Failed connecting to " + HistServer;
}
My status label before i try to connect:
My status label after i try to connect:
After the connection is established, I would like to be able to do something like what i've done in VBA.
Set MyTags = connectedServer.collectors.Item(HistCollector).BrowseTags(AdditionsOnly, SourceFilter, DescriptionFilter)
My c# attempt goes as follows
iHistorian_SDK.TagRecordset MyTags;
MyTags = new iHistorian_SDK.TagRecordset();
MyTags = connectedServer.Collectors.Item("SVNF-IFIX-SCA01_iFIX").BrowseTags(false, "*", "*");
Does anyone know how I can come around this, or if it's even possible in C# to browse tags with the same methode of the collector object.
I've seen this video a few times so I would assume it's possible, they just skip the code where they actually browse tags.
Thanks in advance
/T
The parenthesis in VBA is an indexer. Try to replace .Collectors.Item.("...") with .Collectors.Item.["..."]
If you check the source code for the video link you provided (I.e. The client SDK sample), they aren't using the collectors to query the tags.
cmdBrowseTags_Click is using the ITags "Query" method to 'Browse Tags'.
Here is the GE provided help doco example included in "iHistClientAccessAPI.chm":
TagQueryParams query = new TagQueryParams();
List<Tag> list = new List<Tag>(), temp = null;
query.Criteria.TagnameMask = "*";
// simple query
connection.ITags.Query(ref query, out list);
// paged query
list.Clear();
query.PageSize = 100; // return at most 100 results per request
while (connection.ITags.Query(ref query, out temp))
list.AddRange(temp);
list.AddRange(temp);
I prefer something like this (includes the server connection for completeness):
ServerConnection serverConnection = new ServerConnection(
new ConnectionProperties
{
ServerHostName = "MyHistorianHostName",
Username = "MyUserName",
Password = "MyPassword",
ServerCertificateValidationMode = CertificateValidationMode.None
});
serverConnection.Connect();
if (serverConnection.IsConnected())
{
List<Tag> tagList = new List<Tag>();
TagQueryParams tagQueryParams = new TagQueryParams
{
Criteria = new TagCriteria { TagnameMask = "*" }, // Wilcard, get all tags.
Categories = Tag.Categories.All, // Change this to Basic fo mimimal info.
PageSize = 100 // The batch size of the while loop below..
};
bool isQuery = true;
while (isQuery)
{
isQuery = serverConnection.ITags.Query(ref tagQueryParams, out var tags);
tagList.AddRange(tags);
}
// At this point, tagList contains a list of all tags that matched your wildcard filter.
// To filter to a specific collector, you could then do something like:
var collectorTagList = tagList.Where(t => t.CollectorName == "MyCollector");
}
Goodluck :)
I think I've come across a bug in the CreateFolder command in the Reportingservices2010 SOAP API
The test scenario is I'm trying to create a folder (named Sales Dashboard) in the same Parent folder (lets say Sales) as a report also named Sales Dashboard.
The command completed with the "AlreadyExists" Exception when the folder does not already exist. It looks like the method isn't checking the catalog item type.
Here's my code:
public static void createFolders(string targetURL, string folderName, string parentPath, string description, string visible)
{
//Build Authentication
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = targetURL;
//Declare properties
Property descriptionProp = new Property();
Property visibleProp = new Property();
Property[] props = new Property[2];
descriptionProp.Name = "Description";
descriptionProp.Value = description;
visibleProp.Name = "Visible";
visibleProp.Value = visible;
props[0] = descriptionProp;
props[1] = visibleProp;
try
{
rs.CreateFolder(folderName, parentPath, props);
}
catch(Exception ex)
{
if(ex.Message.Contains("AlreadyExists"))
{
//do nothing?
}
else
{
throw;
}
}
}
I wanted to see if I could contribute a fix but there's no GitHub repo for the C# SSRS stuff. Any thought's on a workaround?
The API is returning the correct error since this is a restriction of Reporting Services in general: items within the same folder must have unique names (regardless of item type).
I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.
I am fairly new to c# and am getting an error "Object reference not set to an instance of an object." I am creating an XML packet and sending it to an external device for control. If I put the following code on the form in a click event it works beautifully.
On the btn Click event it looks like this:
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
this.PopulateTestDataXml();
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
However, If I move my entire function out of the form and try to call it when clicking a button I get the error.
written in a method off the form in a .cs file it reads:
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
The error occurs when building stringRequestXml.
Part of my problem is the PopulateTestData() is a method on the form itself. Its purpose is to take data from txtboxes and cmbboxes and assign them to their respective arguments..
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
Here is the SetTestInformation() method where I am getting the error:
public static string SetTestInformation(TestInformation testInfo, string stringTestId, string stringUser, string stringSampleType, string stringSampleId, int intMethodNumber, string stringTubeSn, string stringComments)
{
try
{
string stringRequestXMLPacket = string.Empty;
string stringType = #"Request";
string stringCommand = #"Set";
string stringArgument = #"TestInformation";
CommunicationPacket requestXMLPacket = new CommunicationPacket(stringRootTag, stringXMLVersion, stringType, stringCommand);
requestXMLPacket.AddCommandArgument(stringArgument);
requestXMLPacket.AddArgumentItem(stringArgument, "sTestId", testInfo.TestID.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sUser", testInfo.TestUser.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleType", testInfo.TestSampleType.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleId", testInfo.TestSampleId.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "nMethodNumber", testInfo.TestMethodNumber.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sTubeSn", testInfo.TestTubeSn.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sComments", testInfo.TestComments.ToString());
stringRequestXMLPacket = requestXMLPacket.CreateXMLPacket();
return stringRequestXMLPacket;
}
catch (Exception ex)
{
throw ex;
}
}
Iknow I am having trouble with the variable scope here. I still have to use the method PopulateTestDataXml on the form before I call the setTestData() method. But when I call the Method I have to declare testInfo = null or the parameters for SetTestInformation are not valid ("Does not exist in the current context"). What would I need to pass and how for this to work as a called method on the form btn click? I need to do this as I have alot of deserializing functions written as well to catch error messages in the response xml (these all work fine) and its just too much info on the click event. (And I need to learn).
Thanks
Neither of your examples should work (regardless of where you put them). This is simply incorrect:
TestInformation testInfo = null;
// ...
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo,
testInfo.TestID, ...);
// ^^ BANG!
Your testInfo object is null. When you try and access anything on a null object.. a NullReferenceException is thrown. You need to initialize it first. You're trying to do that in your PopulateTestDataXml method.. which returns the object your after. So change your code to this:
TestInformation testInfo = PopulateTestDataXml(); // assign it
Here is your problem..
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
Are you assigning values for these objects I see they are just declared but never assigned.
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
i don't see you use null objects, so i'm wonder if you set them later, also u said the error happen on
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
after moving it out of your form, which mean possibly it's text box references is broken...
so what you can do, is store a pointer, like in your program.cs where you call your form to show up,
you can create an static object of form, and then put it in your class, then set it in program.cs file like :
Form1 f=new Form();
MyClass.staticFormPointer = f;
and also replace (new Form()), with (f) on the calling method,
your my class is like this:
class MyClass{
public static Form1 staticFormPointer = null;
//your code
.
.
.
// and in your methods you call it like this txtBox1.Text -> staticFormPointer.txtBox1.Text
}
I'm trying to use word to automatically correct some text that is not in English the problem is that when i use the SpellCheck function the "Spell and Grammar" dialog box pop-up and waits for users input and i want the text to be corrected automatically. So my question is how do i solve this ?
using System.Collections.Generic;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using TobyCL.ro.toby.StringOperations;
namespace namespace.ro.toby
{
class WordProofing:IProof
{
private readonly Word.Application _wordApp;
private readonly Word.Document _wordDoc;
private static object _oEndOfDoc = "\\endofdoc";
public WordProofing()
{
_wordApp = new Word.Application {Visible = false};
_wordDoc = _wordApp.Documents.Add();
}
public void Close()
{
object obj = Word.WdSaveOptions.wdDoNotSaveChanges;
_wordDoc.Close(ref obj);
_wordApp.Quit(ref obj);
}
#region Implementation of IProof
public string Proof(string proofText)
{
Range wRng = _wordDoc.Bookmarks.get_Item(ref _oEndOfDoc).Range;
wRng.Text = proofText;
_wordDoc.CheckSpelling(IgnoreUppercase: true,AlwaysSuggest:false);
string str = wRng.Text;
wRng.Text = "";
return str;
}
#endregion
}
}
I wrote this code a few days ago and it worked. The problem is that i uninstall proofing tools to run some tests and now i keep getting that dialog so i'm thinking that may i have to set some Word settings or i've changed something in my code without knowing. Any help would be greatly appreciated.
I am using Microsoft Office Word 2010
For whoever might be interested this is the way i managed to solve it, but it really takes a lot of time so any improvements or new ideas are welcomed.
using Microsoft.Office.Interop.Word;
class WordProofing
{
private Application _wordApp;
private readonly Document _wordDoc;
private static object _oEndOfDoc = "\\endofdoc";
public WordProofing()
{
_wordApp = new Application { Visible = false };
_wordDoc = _wordApp.Documents.Add();
}
public void Close()
{
_wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges);
_wordApp.Quit();
}
public string Proof(string proofText)
{
Range wRng = _wordDoc.Bookmarks.get_Item(ref _oEndOfDoc).Range;
wRng.Text = proofText;
ProofreadingErrors spellingErros = wRng.SpellingErrors;
foreach (Range spellingError in spellingErros)
{
SpellingSuggestions spellingSuggestions =
_wordApp.GetSpellingSuggestions(spellingError.Text,IgnoreUppercase:true);
foreach (SpellingSuggestion spellingSuggestion in spellingSuggestions)
{
spellingError.Text = spellingSuggestion.Name;
break;
}
}
string str = wRng.Text;
wRng.Text = "";
return str;
}
}
Which MS Word version are you using?
By default the spell checker will show you the dialog box. To disable the dialog box there are two ways that I know.
1) Using Code, automatically choose the first option from Auto Correct.
It is something like this
AutoCorrect.Entries.Add Name:="AdSAD", Value:="Assad"
2) Or use the menu option. Please refer to this link.
Topic: Automatically correct spelling with words from the main dictionary
Link: http://office.microsoft.com/en-us/word-help/automatically-correct-spelling-with-words-from-the-main-dictionary-HA010174790.aspx
Do let me know if this is not what you want?