Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Exception System.ArgumentException in dynamic object.

$
0
0

Hello,

I have the following code:

class Program
    {
        static string strProgId = "MyAutomation.Document";
        static dynamic pserver = null;
        static void Main(string[] args)
        {
            try
            {
                Type tPserver = Type.GetTypeFromProgID(strProgId);
                if (tPserver != null)
                {
                    pserver = Activator.CreateInstance(tPserver);
                }
                pserver.About(null, 0);
                pserver.OpenDataFile(IntPtr.Zero, true, "Test.dat");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            if (pserver != null)
            {
                pserver.FileExit();
            }
        }
    }


It creates dynamic object for DCOM automation server and calls two methods on it. The first call (About) works fine. The second one (OpenDataFile) throws exception (System.ArgumentException) with message: "Could not convert argument 0 for call to OpenDataFile." Note that argument 0 in both calls is the same, but for some reason the first one works and the second does not. The exception is thrown before method is called. I tried all sorts of casting without success. Looks like some sort of bug in the dynamic class wrapper. I have attached exception details and the method definition from ODL file.

Exception details:

-		e	{"Could not convert argument 0 for call to OpenDataFile."}	System.Exception {System.ArgumentException}+		Data	{System.Collections.ListDictionaryInternal}	System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
		HResult	0x80070057	int
		HelpLink	null	string+		InnerException	null	System.Exception
		Message	"Could not convert argument 0 for call to OpenDataFile."	string
		ParamName	null	string
		Source	"System.Dynamic"	string
		StackTrace	"   at System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message)\r\n   at CallSite.Target(Closure , CallSite , ComObject , IntPtr , Boolean , String )\r\n   at System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)\r\n   at CallSite.Target(Closure , CallSite , Object , IntPtr , Boolean , String )\r\n   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)\r\n   at PurifyCOM.Program.Main(String[] args) in C:\\vlh\\Test\\MS.NET\\PurifyCOM\\Program.cs:line 23"	string+		TargetSite	{Void CheckThrowException(Int32, System.Dynamic.ExcepInfo ByRef, UInt32, System.String)}	System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}+		Static members		+		Non-Public members		

Method definition from ODL file:

[id(35)] boolean OpenDataFile(long hWnd, boolean bEmbed, BSTR* bsPfyFilePath );


Verify Account 42

$
0
0

Several new users have asked why they cannot post links and images and receive the following message when they try:
     • Body text cannot contain images or links until we are able to verify your account.

Simply put, we are preventing spam. Typical users will not need to take any additional action in order to have their account verified. However, if you would like to expedite this process please reply below.

Furthermore, you'll be verified automatically if you've contributed to the forum with recognitions (points, replies, and answers etc.) successfully since registered MSDN

, Technet Support

How to keep application runnning/alive using thread in c#.

$
0
0

This is my Program.cs file.

 static void Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
           
           if(Properties.Settings.Default.path == "" )
            {
                Application.Run(new Form2());
            }
            else
            {
                Application.Run(new Form1());
            }
        }

How can I make changes into this to keep this running / alive using thread.

NetworkStream.Read(). If connection is still open, can it return 0?

$
0
0

I've seen in the documentation that NetworkStream.Read(…) will return 0 if the socket is closed.  But what happens if the socket is still open and the server is just not sending any data?  What would the return value be then?  I guess this is somewhat a moot point given how Read blocks until something can be read but still... 



Rick

Need help with binary

$
0
0

Hello,

I am creating a program that saves info to an xml.

I want to create a binary file from the xml data.

But I only want to read the opening nodes, not the closed one's.

and only the inner text of the attributes 

Here is a sample to work with :

<?xml version="1.0" encoding="utf-16"?><File Version="1.0" AppVersion="1.0.0.0"><Parent><Eldest_Child><Grand_Child_One><Info Name="Grand_Child_One_Name">John Doe</Info></Grand_Child_One></Eldest_Child></Parent><File>

I want to use BinaryReader to read through the xml 

and then use BinaryWriter to save everything except 

the opening nodes  and the inner text 

leave the opening nodes  and the inner text, binary everything else .

Example :

  Parent
     Eldest_Child
        Grand_Child_One
                             Grand_Child_One_Name
   

Any help with methods would be great

Regards


Converting DataTable to List of objects

$
0
0
I am trying to convert my DataTable to a list of objects but I am getting an error saying "specified cast is not valid"  when I am now trying to create a list from the data I got from the database
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            myConnectionString = "Data Source=" + ".\\SQLServerInstance" + @";Initial Catalog = " + "DatabaseName" + @";Integrated Security=SSPI;";
        }
        string myConnectionString;
        private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection myGetTaxTypeConnection = new SqlConnection(myConnectionString);
            SqlDataAdapter myGetTaxTypeDataAdapter = new SqlDataAdapter("SELECT * FROM Settings_TaxType", myGetTaxTypeConnection);
            SqlCommandBuilder myGetTaxTypeCommandBuilder = new SqlCommandBuilder(myGetTaxTypeDataAdapter);
            DataTable myGetTaxTypeDataTable = new DataTable();
            myGetTaxTypeDataTable.Reset();
            myGetTaxTypeDataAdapter.Fill(myGetTaxTypeDataTable);

            List<myTaxType> myTaxTypesList = (from myDataRow in myGetTaxTypeDataTable.AsEnumerable()
            select new myTaxType()
            {
                    TaxTypeID = myDataRow.Field<int>("TaxTypeID"),
                    TaxType = myDataRow.Field<string>("TaxType"),
                    TaxRate = myDataRow.Field<decimal>("TaxRate"),
                    TaxStartDate = myDataRow.Field<DateTime>("TaxStartDate"),
                    TaxEndDate = myDataRow.Field<DateTime>("TaxEndDate"),
                    Discontinued = myDataRow.Field<bool>("Discontinued")
            }).ToList();
        }
        class myTaxType
        {
            public int TaxTypeID { get; set; }
            public string TaxType { get; set; }
            public decimal TaxRate { get; set; }
            public DateTime TaxStartDate { get; set; }
            public DateTime TaxEndDate { get; set; }
            public bool Discontinued { get; set; }
        }        
    }
}
When this method did not work I tried a different approach like this and it is also giving the same error
List<TaxType> listName = myGetTaxTypeDataTable.AsEnumerable().Select(m => new TaxType()
{
    TaxTypeID = m.Field<int>("TaxTypeID"),
    myTaxType = m.Field<string>("TaxType"),
    TaxRate = m.Field<decimal>("TaxRate"),
    TaxStartDate = m.Field<DateTime>("TaxStartDate"),
    TaxEndDate = m.Field<DateTime>("TaxEndDate")
}).ToList();
Please help me . I dont want to loop

If you think it you can achieve it

I am not understanding the code

$
0
0

I have came across this code line where I am not understanding whats the problem.

Its showing the error: CS0103  C# The name 'Properties' does not exist in the current context

code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.GPU;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Newtonsoft.Json;
using System.IO;
using System.Timers;

namespace Emgu_4._0
{

    /// <summary>
    /// Used to callibrate the outermoust positions of the screen to be used when calculating servo positions
    /// </summary>
    public partial class Calibration : Form
    {
        private buttonState buttonState = new buttonState();
        private System.Timers.Timer buttonHoldtimer;
        private Capture capture;
        private Settings settings;
        private Point virtualPoint = new Point(90, 90);

        public Calibration()
        {
            InitializeComponent();
            initializePerepherals();
            initializeSettings();
            initializeTimer();
            resetPos();
            
            Application.Idle += displayImage;
            MessageBox.Show("Use the arrows to adjust the laser to the outermost part of the screen");

        }

        private void initializeTimer()
        {
            buttonHoldtimer = new System.Timers.Timer();
            buttonHoldtimer.Interval = 1;
            buttonHoldtimer.Enabled = false;
            buttonHoldtimer.Elapsed += timerEllapsed;
            buttonHoldtimer.AutoReset = true;

        }

        /// <summary>
        /// Winforms has no event for buttonhold, this is a makeshift one
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerEllapsed(object sender, ElapsedEventArgs e)
        {
            switch (buttonState)
            {
                case buttonState.Right:
                    virtualPoint.X--;
                    break;

                case buttonState.Up:
                    virtualPoint.Y++;
                    break;

                case buttonState.Left:
                    virtualPoint.X++;
                    break;

                case buttonState.Down:
                    virtualPoint.Y--;
                    break;
            }

            sendSerial();

            buttonHoldtimer.Interval = 100;
        }

        private void displayImage(object sender, EventArgs arg)
        {
            imageBox1.Image = capture.QueryFrame();


        }

        private void initializeSettings()
        {

            try
            {
                settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(Properties.Resources.settingsFileName));
            }
            catch (FileNotFoundException e)
            {
                MessageBox.Show("No memory file detected, generating one");
                settings = new Settings();
                saveSettings();

            }
            catch (JsonReaderException e)
            {
                MessageBox.Show("Corrupt Memory File");
                File.Delete(Properties.Resources.settingsFileName);
                this.Close();
            }
        }

        private void saveSettings()
        {
            File.WriteAllText(Properties.Resources.settingsFileName, JsonConvert.SerializeObject(settings));

        }
        private void resetPos()
        {
            serialPort1.Write("X90:Y90");
        }

        private void initializePerepherals()
        {
            try
            {
                capture = new Capture();
            }
            catch (Exception e)
            {
                MessageBox.Show("Cannot initialize camera");
                this.Close();
            }

            try
            {
                serialPort1.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show("Cannot initialize on COM port");
                this.Close();
            }
        }

        private void sendSerial()
        {
            if (virtualPoint.X < 180 && virtualPoint.X > 0 && virtualPoint.Y < 180 && virtualPoint.Y > 0)
            {
                serialPort1.Write("X" + (virtualPoint.X).ToString() + ":Y" + (virtualPoint.Y).ToString()); //Data stream format
            }

        }




        private void Calibration_FormClosing(object sender, FormClosingEventArgs e)
        {
            capture.Dispose();
            resetPos();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Calibrate " + radDropDownList1.Text + "?", "", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                if (radDropDownList1.SelectedIndex != -1)
                {
                    if (radDropDownList1.SelectedIndex == 0)
                    {
                        settings.xLeftCalibration = virtualPoint.X;
                    }
                    else if (radDropDownList1.SelectedIndex == 1)
                    {
                        settings.xRightCalibration = virtualPoint.X;
                    }
                    else if (radDropDownList1.SelectedIndex == 2)
                    {
                        settings.yTopCalibration = virtualPoint.Y;
                    }
                    else if (radDropDownList1.SelectedIndex == 3)
                    {
                        settings.yBotCalibration = virtualPoint.Y;
                    }

                    saveToFile();
                }
            }

        }

        private void saveToFile()
        {
            File.WriteAllText(Properties.Resources.settingsFileName, JsonConvert.SerializeObject(settings));

        }

        private void mouseDown(object sender, MouseEventArgs e)
        {
            Button button = (Button)sender;

            if (button.Equals(upButton))
            {
                buttonState = buttonState.Up;
            }
            else if (button.Equals(rightButton))
            {
                buttonState = buttonState.Right;
            }
            else if (button.Equals(downButton))
            {
                buttonState = buttonState.Down;
            }
            else if (button.Equals(leftButton))
            {
                buttonState = buttonState.Left;
            }


            buttonHoldtimer.Enabled = true;
        }

        private void mouseUp(object sender, MouseEventArgs e)
        {
            buttonHoldtimer.Enabled = false;
        }
    }

    public enum buttonState
    {
        Up, Down, Right, Left    
    }

    public enum soundType
    {
        Detection, Missing, Startup, Shutdown, Saddness
    }
}

How to implement wrapper view of label control list or textBox control list?

$
0
0

Dear All,

How to implement wrapper view of label control list or textBox control list?

Thanks and best regards,

E-John

    public partial class Form1 : Form
    {
        public const int MaxItemCount = 8;

        private List<string> _labelNameList = new List<string>(new string[MaxItemCount]);
        private List<string> _textBoxNameList = new List<string>(new string[MaxItemCount]);

        // wrapper view for label control
        public string LabelName
        {
            get { return labelName.Text; }
            set { labelName.Text = value; }
        }

        // wrapper view for text box control
        public string TextBoxName
        {
            get { return textBoxName.Text; }
            set { textBoxName.Text = value; }
        }

        // wrapper view for label control list???
        public List<string> LabelNameList
        {
            get { return _labelNameList; }
            set { _labelNameList = value; }
        }

        // wrapper view for text box control list???
        public List<string> TextBoxNameList
        {
            get { return _textBoxNameList; }
            set { _textBoxNameList = value; }
        }

        public Form1()
        {
            InitializeComponent();
            groupBox1.Visible = false;

            labelName1.Text = _labelNameList[0];
            labelName2.Text = _labelNameList[1];
            labelName3.Text = _labelNameList[2];
            labelName4.Text = _labelNameList[3];
            labelName5.Text = _labelNameList[4];
            labelName6.Text = _labelNameList[5];
            labelName7.Text = _labelNameList[6];
            labelName8.Text = _labelNameList[7];

            textBoxName1.Text = _textBoxNameList[0];
            textBoxName2.Text = _textBoxNameList[1];
            textBoxName3.Text = _textBoxNameList[2];
            textBoxName4.Text = _textBoxNameList[3];
            textBoxName5.Text = _textBoxNameList[4];
            textBoxName6.Text = _textBoxNameList[5];
            textBoxName7.Text = _textBoxNameList[6];
            textBoxName8.Text = _textBoxNameList[7];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TextBoxName) == false)
            {
                groupBox1.Text = TextBoxName;
                var baseName = TextBoxName;

                for (int i = 0; i < 8; i++)
                {
                    _labelNameList[i] = baseName + "-" + (i + 1).ToString();
                    _textBoxNameList[i] = baseName + "-" + (i + 1).ToString();
                }

                groupBox1.Visible = true;
            }
        }
    }


Exception thrown: 'System.IO.FileNotFoundException' in Microsoft.Speech.dll

$
0
0

I was trying to run program from figure 3 which is given in below link,

https://msdn.microsoft.com/en-us/magazine/dn857362.aspx?f=255&MSPPError=-2147217396

I have started a new Console application in .net framework renamed it as ConsoleSpeechProgram and executed but it is showing me this error:Exception thrown: 'System.IO.FileNotFoundException' in Microsoft.Speech.dll

Note that I have added Microsoft.Speech.dll in reference as well

using System;
using Microsoft.Speech.Recognition;
using Microsoft.Speech.Synthesis;
using System.Globalization;
namespace ConsoleSpeech
{  class ConsoleSpeechProgram  {    static SpeechSynthesizer ss = new SpeechSynthesizer();    static SpeechRecognitionEngine sre;    static bool done = false;    static bool speechOn = true;    static void Main(string[] args)    {      try      {        ss.SetOutputToDefaultAudioDevice();        Console.WriteLine("\n(Speaking: I am awake)");        ss.Speak("I am awake");        CultureInfo ci = new CultureInfo("en-us");        sre = new SpeechRecognitionEngine(ci);        sre.SetInputToDefaultAudioDevice();        sre.SpeechRecognized += sre_SpeechRecognized;        Choices ch_StartStopCommands = new Choices();        ch_StartStopCommands.Add("speech on");        ch_StartStopCommands.Add("speech off");        ch_StartStopCommands.Add("klatu barada nikto");        GrammarBuilder gb_StartStop = new GrammarBuilder();        gb_StartStop.Append(ch_StartStopCommands);        Grammar g_StartStop = new Grammar(gb_StartStop);        Choices ch_Numbers = new Choices();        ch_Numbers.Add("1");        ch_Numbers.Add("2");        ch_Numbers.Add("3");        ch_Numbers.Add("4");        GrammarBuilder gb_WhatIsXplusY = new GrammarBuilder();        gb_WhatIsXplusY.Append("What is");        gb_WhatIsXplusY.Append(ch_Numbers);        gb_WhatIsXplusY.Append("plus");        gb_WhatIsXplusY.Append(ch_Numbers);        Grammar g_WhatIsXplusY = new Grammar(gb_WhatIsXplusY);        sre.LoadGrammarAsync(g_StartStop);        sre.LoadGrammarAsync(g_WhatIsXplusY);        sre.RecognizeAsync(RecognizeMode.Multiple);        while (done == false) { ; }        Console.WriteLine("\nHit <enter> to close shell\n");        Console.ReadLine();      }      catch (Exception ex)      {        Console.WriteLine(ex.Message);        Console.ReadLine();      }    } // Main    static void sre_SpeechRecognized(object sender,      SpeechRecognizedEventArgs e)    {      string txt = e.Result.Text;      float confidence = e.Result.Confidence;      Console.WriteLine("\nRecognized: " + txt);      if (confidence < 0.60) return;      if (txt.IndexOf("speech on") >= 0)      {        Console.WriteLine("Speech is now ON");        speechOn = true;      }      if (txt.IndexOf("speech off") >= 0)      {        Console.WriteLine("Speech is now OFF");        speechOn = false;      }      if (speechOn == false) return;      if (txt.IndexOf("klatu") >= 0 && txt.IndexOf("barada") >= 0)      {        ((SpeechRecognitionEngine)sender).RecognizeAsyncCancel();        done = true;        Console.WriteLine("(Speaking: Farewell)");        ss.Speak("Farewell");      }      if (txt.IndexOf("What") >= 0 && txt.IndexOf("plus") >= 0)      {        string[] words = txt.Split(' ');        int num1 = int.Parse(words[2]);        int num2 = int.Parse(words[4]);        int sum = num1 + num2;        Console.WriteLine("(Speaking: " + words[2] + " plus " +          words[4] + " equals " + sum + ")");        ss.SpeakAsync(words[2] + " plus " + words[4] +          " equals " + sum);      }    } // sre_SpeechRecognized  } // Program
} // ns

How to change the base application path of AppDomain

$
0
0

Hi I want to give access to a particular folder so that all IO operations are performed only in that folder.

public class Plugin : MarshalByRefObject
{
    public string TestRead(string path)
    {
        try
        {
            File.WriteAllText(path, "This is example text.");
            return "Done";
        }
        catch (SecurityException)
        {
            return "Access Denied";
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        string sandboxPath = "D:\\test\\public\\";

        string basePath = AppDomain.CurrentDomain.BaseDirectory;

        var setup = new AppDomainSetup();

        setup.ApplicationBase = basePath;

        var perm = new PermissionSet(PermissionState.None);

        perm.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

        perm.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sandboxPath));
        perm.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, basePath));

        var pluginDomain = AppDomain.CreateDomain("PluginDomain", null, setup, perm);

        var plugin =
            pluginDomain.CreateInstanceAndUnwrap(
                typeof(Plugin).Assembly.FullName,
                typeof(Plugin).FullName) as Plugin;

        Console.WriteLine(plugin.TestRead("D:\\test\\public\\test.txt"));
        Console.WriteLine(plugin.TestRead(@"D:\\test\\secret\\test.txt"));
        Console.ReadKey();
    }
}

It works fine and file is written only to sandBoxPath .i.e "D:\\test\\public\\" and the access is denied when file is written to other than sandBoxPath i.e. "D:\\test\\secret\\".

Now I want to specify only a file name without the whole path and program should pick the sandBoxPath .e.g. when I call 

Console.WriteLine(plugin.TestRead("test.txt"));

Program should be able to read/write text.txt file from/to sandBoxPath ("D:\\test\\public\\") .

I have tried to set the ApplicationBase but it's not working

pluginDomain.SetupInformation.ApplicationBase = sandboxPath;

Any idea how can I do that? 

Thanks.

 

MW

C# code for object movement in cross domain.

$
0
0

I have two domain under same forest & I want to move user from one domain to another domain using c# code. With the below code I am getting error while moving users in different domain(under same domain it is working).

       DirectoryEntry eLocation = new DirectoryEntry(url, user, pass, AuthenticationTypes.ServerBind);
       DirectoryEntry nLocation = new DirectoryEntry(url1, user1, pass1, AuthenticationTypes.ServerBind);
       eLocation.MoveTo(nLocation);
       nLocation.Close();
       eLocation.Close();

error for the cross domain movement is ::

{"The user name or password is incorrect.\r\n"}

Building and deploy Chat bot

$
0
0

Dear all,

I have a requirement on building a POC around Chat bot service.

Does anyone have experience with that or point me out on how to :
- Build the chat bot in C#
-Interacte with it 
- Publish it on a test web site

I have seen some basic sample in Azure which use Bot emulator but not complete sample on our to interact with bot.

if any one have more real sample to get started would be great.

Thanks for your help on this

regards

i have a problem while update query in c# access data , please help me it says data type mismatch

$
0
0

 "public static int updatestrecord(String St_name, String St_fname, String Address, int Contact_no, int Student_id)
        {
            String query= "update St_record set St_name='" + St_name+ "',St_fname='"+St_fname+"',Address='"+Address+"',Contact_no='"+Contact_no+"' where Student_id='"+Student_id+"'";
            OleDbCommand com= new OleDbCommand(query,conn);
            int rows = com.ExecuteNonQuery();
            return rows;
        }"this is a database class code for update button ".

and thats a button code of update "

private void update_Click(object sender, EventArgs e)
        {
            int Student_id = Int32.Parse(textBox1.Text);
            String St_name = textBox2.Text;
            String St_fname = textBox3.Text;
            String Address = textBox4.Text;
            int Contact_no = Int32.Parse(textBox5.Text);
            
            int row = Databaseconn.updatestrecord(St_name,St_fname,Address,Contact_no,Student_id);
            if (row > 0)
            {
                MessageBox.Show("record updated");
            }
            else MessageBox.Show("error");

        }

Help

$
0
0

SeverityCodeDescriptionProjectFileLineSuppression State
ErrorUnable to copy file "obj\Debug\WindowsApp1.exe" to "bin\Debug\WindowsApp1.exe". Access to the path 'obj\Debug\WindowsApp1.exe' is denied.WindowsApp1

Why can i not run my build? 

Regards

About the standards followed by RNGCryptoServiceProvider

$
0
0
What is the standard that RNGCryptoServiceProvider follows?What is the standard that RNGCryptoServiceProvider follows.
Is it NIST SP 800-90A, or something else?

How to write to multiple serial ports at the same time

$
0
0

Hi,

I am creating an application that sends out data to multiple serial ports(Arduino nano's). Speed plays a pretty big role in this project, so it isn't an option to write to all the serial ports one after the other.

I am using "Write (Byte[], Int32, Int32)" to send the data to the serial ports and it is quick enough when it only has to send the data to a single serial port, but when it has to write the data to multiple serial ports it takes way longer, because it writes the data to the serial ports one after the other.

So is there a way that I could write to multiple serial ports at the same time?

Can I get some help to write an xml to binary

$
0
0

hello,

I am trying to create a binary dictionary file for a program.

The settings file is in xml, and I want the program to load the binary file.

here is the code of the xml:

<?xml version="1.0" encoding="utf-16"?><Lang Version="1.0" AppVersion="1.0.0.0"><Dialogs><Main><Menus><I Name="Main_Menu_Load">Load</I><I Name="Main_Menu_Save">Save</I><I Name="Main_Menu_Exit">Exit</I><I Name="Main_Menu_SaveAll">Save All</I><I Name="Main_Menu_Close">Close</I><I Name="Main_Menu_CloseAll">Close All</I><I Name="Main_Menu_Languages">Languages</I><I Name="Main_Menu_Help">Help</I><I Name="Main_Menu_Help_About">About</I><I Name="Main_Menu_Help_CheckForNewVersion">Check For New Version</I><I Name="Main_Text_LoadLanguage">Load Language {0}</I><I Name="Main_Menu_LoadMultiple">Load Multiple</I><I Name="Main_Menu_EmptyTextsColor">Empty Texts Color</I><I Name="Main_Menu_MatchingTextsColor">Matching Texts Color</I><I Name="Main_Menu_ExpandAll">Expand All</I><I Name="Main_Menu_CollapseAll">Collapse All</I><I Name="Main_Menu_ChangeColors">Change Colors</I></Menus><Headers><I Name="Main_HDR_Name">Name</I><I Name="Main_HDR_WarningName">Name</I><I Name="Main_HDR_WarningLanguages">Languages</I><I Name="Main_HDR_ErrorName">Name</I><I Name="Main_HDR_ErrorLanguage">Language</I></Headers><Texts><Logs><I Name="Main_Text_MissingFormatArgument">Missing format arguments : {0}</I></Logs><I Name="Main_Text_Warnings">{0} Warnings</I><I Name="Main_Text_Errors">{0} Errors</I></Texts></Main></Dialogs><Questions><I Name="Question_SaveChangesToFollowingLangs">Save changes to the following language(s) ?</I></Questions><Infos><I Name="Info_XmlSavedTo">'{0}' xml saved to {1}</I><I Name="Info_DicxSavedTo">'{0}' dicx saved to {1}</I><I Name="Info_LanguageAlreadyLoadedAt">'{0}' already loaded at {1}</I></Infos><Errors><I Name="Error_LanguageItemsAreMissing">{0} language item(s) are missing in {1}</I></Errors><XSystem.Update><Dialogs><I Name="Info_UpdateAvailable">Version : {0} is available</I><I Name="Info_CheckingForNewVersion">Checking for new version</I></Dialogs></XSystem.Update></Lang>

What I need is binarywrite code to save this to a binary file

Here is a link to my project:

LanguageEditor and DicxFiler download

any help would be great

Thank you



How to solve "error CS1061" ??

$
0
0
Hi Everyone,
I have an error message when I try to run my program, this is error CS1061 like show below. But actually my program is success full to run before.. But I don't know why suddenly when I try to compile there's any error :  
------ Build started: Project: Latihan1, Configuration: Debug x86 ------
c:\users\lina\documents\visual studio 2010\Projects\Latihan1\Latihan1\Form1.Designer.cs(40,55): error CS1061: 'Latihan1.Form1' does not contain a definition for 'Form1_Load' and no extension method 'Form1_Load' accepting a first argument of type 'Latihan1.Form1' could be found (are you missing a using directive or an assembly reference?)
Compile complete -- 1 errors, 0 warnings
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Specifying a range for a list input relative to previous list inputs

$
0
0

I'm trying to validate user input to a range which compares an input to previous inputs in a list, I can seem to find the syntax. I've written something indicative of what i'm trying to do, but the if statement that declares the range is obviously all wrong. My code reads as follows:

List<Opening> OpeningsList = new List<Opening>();

int MinRange = openingFromSOP + openingWidth + (int)StudCount() / 2 * (int)TimberThickness;
            if (openingFromSOP > MinRange.CompareTo(List<Opening> OpeningsList))
            {
                OpeningsList.Add(new Opening() { OpeningFromSOP = openingFromSOP - StudCount() / 2 * TimberThickness, DistanceOverOpening = openingFromSOP + openingWidth + StudCount() / 2 * TimberThickness, OpeningWidth = openingWidth + StudCount() * TimberThickness, OpeningHeadHeight = openingHeadHeight, OpeningCillHeight = openingCillHeight, LintelTicker = flag2 });
            }
            else
            {
                ContentDialog CillTooHigh = new ContentDialog
                {
                    Title = "Invalid input",
                    Content = "The opening is within the bounds of another opening.",
                    CloseButtonText = "Ok"
                };
            }

Any help would be appreciated, cheers, Matthew

VS2017 fails to add a reference to C# project.

$
0
0

Hello,

I am trying to add a reference to a C# project. The reference is imported from a TLB file. I do "Add reference/Browse" and specify the required TLB file. After I hit "OK", VS2017 shows me the following message: "A reference to <file name> could not be added. Make sure that the file is accessible, and that it is a valid assembly or COM component." When I open the same file with OleView, I can see a valid IDL generated from this type library. What am I missing here?

The TLB in question can be found at the link below:

https://1drv.ms/u/s!AkX9Ou21NcEig9FcEVdnTnjXKbVcOg

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>