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

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 access first form's combobox value from a 2nd form?

$
0
0

While in the main form (form1), the user selects a value (v1) from a combobox.

My target is to open a second form (form2), use the value selected (v1) from the first form, do some operations based on that value, close form2, and return control to form1.

Somehow I couldn't refer to the value selected in Form1, while Form2 is opened.

How can I do it?

Monitor when two files are loaded on the same instance using FileSystemWatcher

$
0
0

The following method is called when a file is open:

private void Load(string fileName) { // Only watch seq files. this.watcher.Path = Path.GetDirectoryName(fileName); // Watch for changes in LastAccess and LastWrite times, and // the renaming of files or directories. this.watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; this.watcher.Filter = Path.GetFileName(fileName); // Begin watching. this.watcher.EnableRaisingEvents = true; // Add event handlers. this.watcher.Changed += this.OnChanged; // code for opening file asynchronously } private void OnChanged(object source, FileSystemEventArgs e) { App.Current.Dispatcher.Invoke(() => { MessageBoxResult result = CustomMessageBox.ShowYesNoCancel("The file has been modified by another instance.","More instances are opened!","Overwrite","Reload","Save as", MessageBoxImage.Exclamation); if (result == MessageBoxResult.Yes) { // Overwrite } if (result == MessageBoxResult.Cancel) { // Save as; }

 if (result == MessageBoxResult.No)
            {
                // reload file and lose changes

            }
        });
        var t = new System.Timers.Timer();
        ((FileSystemWatcher)source).Changed -= new FileSystemEventHandler(this.OnChanged);
        t.Interval = 1000;
        t.Elapsed += new ElapsedEventHandler(Elapsed);
        t.Start();
    }

    private static void Elapsed(object sender, ElapsedEventArgs e)
    {
        ((System.Timers.Timer)sender).Stop();
    }

private static void Elapsed(object sender, ElapsedEventArgs e) { ((System.Timers.Timer)sender).Stop(); }

1.I'm very disappointed that I get my MessageBox only when the file from one instances is saved but I like to have my message when I load the file on the second instance. Main problem is that the user opened the application twice and now is possible to modified in both instances. For saving I'm using this method:

public override void WriteStartObject(XmlDictionaryWriter writer, object graph);

Is this NotifyFilters.LastAccess working? For me just NotifyFilters.LastWrite seems to work...

  1. The other small problem is that after I save the changes to my file on one instances the messageBox appear twice(as if I do not have enough problems).


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

SQL Row Count in VS

$
0
0

How do I get the query to row count in order 1,2,3,4 it is counting 1111 i have try a few different ways

using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1  where ItemCode = @egg", con))

 using (var cmd = new SqlCommand("SELECT ROW_NUMBER() Over (order by ItemCode)as Number, ItemCode FROM Table1  where ItemCode = @egg", con))
 using (var cmd = new SqlCommand("SELECT Count(*) Over(PARTITION by ItemCode)as Number, ItemCode FROM Table1  where ItemCode = @egg", con))
 using (var cmd = new SqlCommand("SELECT Top 8 ROW_NUMBER() Over (Order by ItemCode) as Number, ItemCode FROM Table1  where ItemCode = @egg", con))

Number
1     EG216455
1     nEG216456
1     nEG216457
1     nEG216458

Number
1     EG216455
2     nEG216456
3     nEG216457
4     nEG216458

Here is the code and you can see the query

private void button1_Click(object sender, EventArgs e)
        {
            string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460"	
            int k = Convert.ToInt32(textBox2.Text);  
            string[] stringSeparators = new string[];
            string[] s = egg.Split(stringSeparators, StringSplitOptions.None);


            DataTable dtSerial = new DataTable();
            DataTable table = new DataTable();

            for (int i = 0; i < k; i++)
            {
                                   //ConfigurationManager.ConnectionStrings["pie"].ConnectionString;
                string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database.mdf;Integrated Security=True";

                using (SqlConnection con = new SqlConnection(connString))
                {
                    using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1  where ItemCode = @egg", con))
                        cmd.Parameters.AddWithValue("@egg", s[i]); 
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        dtSerial.Load(reader);
                        table = dtSerial.Clone();
                        foreach (DataRow dr in dtSerial.Rows)
                        {

                            table.Rows.Add(dr.ItemArray);
                        }
                    }
                    con.Close();
                }
            }


            dataGridView1.DataSource = dtSerial;
        }


Function wait until thread(websocket) to finish before returning result

$
0
0
Hello, I am trying to run a Websocket client example:
the lib used is: https://github.com/sta/websocket-sharp

I have made below function to communicate with an Websocket server, the problem is that it returns the result before it is set by the OnMessage function from websocket(ws):
public static Tuple<int, string> wingm(string userName, string extrastr, string)
        {
            var ws = new WebSocket("wss://just.mywssgame.uk:7002/");
            using (ws)
            {
                //ws.Connect();

                String returnResultJSON = "";
                ws.OnMessage += (sender, e) =>
                {
                    dynamic messageJSONresponse = JsonConvert.DeserializeObject(e.Data);
                    if (Convert.ToString(messageJSONresponse.type) == "playerone")
                        {
			    returnResultJSON = Convert.ToString(messageJSONresponse);
                            Console.WriteLine(returnResultJSON);
                        }

                    }
                };
                //we begin here
                ws.Connect();
                ws.Send(userName);
                Console.ReadKey(true);
            }
       return Tuple.Create("0", returnResultJSON);
 }

I then call above function in an console application:
Tuple<int, string> tempResult = wingm("somnam", "");
Console.WriteLine(tempResult.Item1.ToString());
Console.WriteLine(tempResult.Item2.ToString());
The problem is that, the function returns the returnResultJSON before it is set by ws.OnMessage, is there a way to wait for the websocket until it is closed? what would the approach be in this situation?

Thank you in advance, I have been stuck in this for hours.

Google People API sample code to get list of contact groups

$
0
0
I'm new here so I hope I'm in the right forum.
I'm using the new Google People API to load the list of a user's Google contacts into my app. I've used the code to get the list of contacts from the People API guide: www.developers.google.com/people/v1/read-people and that works fine, but I can't find any similar code to load the list of contact groups (eg family, workmates etc). I got this working before with the Contacts API and there is lots of sample code for that, but I can't find any for the People API in Csharp. 
Thanks.

[XML] Huge file manage (> 2GB)

$
0
0

Hi,

I have an XML file to import into a new database with EntityFramework.

File looks like this :

<?xml version="1.0" encoding="utf-8"?><ArrayOfExternAnimal xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><ExternAnimal Breed="Griffon Fauve de Bretagne" Name="Oska" Male="false" Coat="" ChipOrTattoo="BDT567" Lof="149/40" FatherId="0" MotherId="0" SccDatabaseId="900005"><BirthDate>1978-07-14T00:00:00</BirthDate><DeathDate>0001-01-01T00:00:00</DeathDate><Quotation>Confirmé</Quotation><Dna /><SccHealth /></ExternAnimal><ExternAnimal Breed="Griffon Fauve de Bretagne" Name="Panisse" Male="true" Coat="F.Fo." ChipOrTattoo="BAR660" Lof="150/78" FatherId="899881" FatherName="Ludo" MotherId="899791" MotherName="Mascotte" SccDatabaseId="900012"><BirthDate>1979-11-30T00:00:00</BirthDate><DeathDate>0001-01-01T00:00:00</DeathDate><Quotation>Confirmé</Quotation><Dna /><SccHealth /></ExternAnimal><ExternAnimal Breed="Griffon Fauve de Bretagne" Name="Petula" Male="false" Coat="F.Cl." ChipOrTattoo="BAR662" Lof="152/79" FatherId="899881" FatherName="Ludo" MotherId="899791" MotherName="Mascotte" SccDatabaseId="900013"><BirthDate>1979-11-30T00:00:00</BirthDate><DeathDate>0001-01-01T00:00:00</DeathDate><Quotation>Confirmé</Quotation><Dna /><SccHealth /></ExternAnimal></ArrayOfExternAnimal>

But the DeSerialize is not a good way for a such big file. So, what is the best way to do this ?

Thanks,

Vincent


Function wait until thread(websocket) to finish before returning result

$
0
0
Hello, I am trying to run a Websocket client example:
the lib used is: https://github.com/sta/websocket-sharp

I have made below function to communicate with an Websocket server, the problem is that it returns the result before it is set by the OnMessage function from websocket(ws):
public static Tuple<int, string> wingm(string userName, string extrastr, string)
        {
            var ws = new WebSocket("wss://just.mywssgame.uk:7002/");
            using (ws)
            {
                //ws.Connect();

                String returnResultJSON = "";
                ws.OnMessage += (sender, e) =>
                {
                    dynamic messageJSONresponse = JsonConvert.DeserializeObject(e.Data);
                    if (Convert.ToString(messageJSONresponse.type) == "playerone")
                        {
			    returnResultJSON = Convert.ToString(messageJSONresponse);
                            Console.WriteLine(returnResultJSON);
                        }

                    }
                };
                //we begin here
                ws.Connect();
                ws.Send(userName);
                Console.ReadKey(true);
            }
       return Tuple.Create("0", returnResultJSON);
 }

I then call above function in an console application:
Tuple<int, string> tempResult = wingm("somnam", "");
Console.WriteLine(tempResult.Item1.ToString());
Console.WriteLine(tempResult.Item2.ToString());
The problem is that, the function returns the returnResultJSON before it is set by ws.OnMessage, is there a way to wait for the websocket until it is closed? what would the approach be in this situation?

Thank you in advance, I have been stuck in this for hours.

Webrequest to Download File From Azure Blob in chunks and send Response in Chunks c#

$
0
0

Hi All,

I have a requirement as below in c#:

I have a service running which would request a MVC controller and my controller would interact with my Azure blob download the file in Chunks and send the chunks across to the service that it has requested it...

I need this to be implemented using memory usage rather than writing the file on disk at the controller

Can anyone help me out reg how this could be achieved.

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

C# Logical Code Not Working

$
0
0

Hi,

I really need help, because of my code. Let me explain... I want to make a kind of Mario Game and I did all the stuff like add arrows to make the character move , add the mario character , add a ground and I am working on a block that mario will jump. that stupidly dont work, it is bizzare because the ground is working but not the block I let you see just under. I know there is some codes that is useless, but ill remove them after.

namespace Pong_Test12
{
    public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = pictureBox1.Location.X;
            int y = pictureBox1.Location.Y;
            if (e.KeyCode == Keys.Right)
            {
                x += 10;
                Refresh();
            }
            else if (e.KeyCode == Keys.Left)
            {
                x -= 10;
                Refresh();
            }
            else if (e.KeyCode == Keys.Up)
            {
                y -= 20;
                Refresh();
            }
            else if (e.KeyCode == Keys.Down)
            {
                y += 10;
                Refresh();
            }
            pictureBox1.Location = new Point(x, y);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //e.Graphics.FillRectangle(Brushes.ForestGreen, x, y, 75, 100);
            //e.Graphics.DrawImage(new Bitmap("WIN_20190119_16_59_10_Pro.jpg"), x, y, 100, 100);
            //graphics = e.Graphics;
            //SolidBrush bleu = new SolidBrush(Color.Red);
            //graphics.FillRectangle(bleu, x, y, 75, 100);
            
        }
        private void Blockwall()
        {
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            
        }
        private void gravity()
        {
            if (pictureBox1.Location.Y == 165 || pictureBox1.Location.Y == 14)
            {
                tmrgravity.Stop();
            }
            else if (pictureBox1.Location.Y != 165 && pictureBox1.Location.Y != 14) 
            {
                tmrgravity.Start();
            }
        }

        private void tmrgravity_Tick(object sender, EventArgs e)
        {
            int x = pictureBox1.Location.X;
            int y = pictureBox1.Location.Y;
            y += 10;
            pictureBox1.Location = new Point(x, y);
        }

        private void tmrvalidater1_Tick(object sender, EventArgs e)
        {
            gravity();
        }
    }
}

So it is in the section of  private void gravity()

PS - I am 12 years old pls dont give me a code of 100k

c# windows form project disabling mouse clicks and enabling

$
0
0

I am playing some videos on windows form project, displaying a full screen videos, and i do not want the user to click on the

mouse while video is paying since it would interrupt the video and menu would pop up, so i place the code to disable the mouse

clicks while form loads with media player and then ones the video is finished i want to enable back.

The disabling works, however enabling fails, my mouse still disable after the video is finished.

Here is code:

                                                                                                                                         

 private void Media_Player_Form_Load(object sender, EventArgs e)
        {   
            this.Width = 233;
            this.Height = 215;
            axWindowsMediaPlayer1.Width = 233;
            axWindowsMediaPlayer1.Height = 215;
            Point pt = new Point((Screen.GetWorkingArea(this).Width - this.Width) / 2, (Screen.GetWorkingArea(this).Height - this.Height) / 2);
            this.Location = pt;

           MouseClickMessageFilter B = new MouseClickMessageFilter();
            B.DisableMouseClicks();

        }

        private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {    
            if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
            {

                this.Width = 233;
                this.Height = 215;
                axWindowsMediaPlayer1.Width = 233;
                axWindowsMediaPlayer1.Height = 215;

                MouseClickMessageFilter B = new MouseClickMessageFilter();
                B.EnableMouseClicks();

this.Close();


            } 

        }



    }
}


        public class MouseClickMessageFilter : IMessageFilter
        {
            private MouseClickMessageFilter Filter;

            private const int LButtonDown = 0x201;
            private const int LButtonUp = 0x202;
            private const int LButtonDoubleClick = 0x203;
            private const int RButtonUp = 0x205;

            public bool PreFilterMessage(ref System.Windows.Forms.Message m)
            {
                switch (m.Msg)
                {
                    case LButtonDown:
                    case LButtonUp:
                    case LButtonDoubleClick:
                   // case RButtonDown;
                    case RButtonUp:
                  //  case RButtonDoubleClick:

                    return true;
                }
                return false;
            }
            public void DisableMouseClicks()
            {
                if (this.Filter == null)
                {
                    this.Filter = new MouseClickMessageFilter();
                    Application.AddMessageFilter(this.Filter);
                }
            }

            public void EnableMouseClicks()
            {
                if ((this.Filter != null))
                {
                    Application.RemoveMessageFilter(this.Filter);
                    this.Filter = null;
                }
            }



        } 

Write back, thanks in advance



Playing multiple cameras of same model not working - AFORGE Player

$
0
0

I can play with two cameras simultaneously using aforge player(one was PC webcam and another was a USB camera). Now when I'm trying with two cameras which is connected from a PCB, is not working (both camera are of same model). Camera which is connected to first player is only playing. Second player shows "connecting.." message only. Seems the issue was with same model of camera. . This might be a limitations of drivers/system. Can I resolve this? or can I reach in a summary what is the exact issue? When I'm running the same app in Windows 8 it is working. My lap is windows 10.

private void StartCameras() { try { // create first video source videoSource1 = new VideoCaptureDevice(videoDevices[camera1Combo.SelectedIndex].MonikerString); videoSourcePlayer1.VideoSource = videoSource1; videoSource1.NewFrame += new AForge.Video.NewFrameEventHandler(Video1_NewFrame); videoSourcePlayer1.Start(); // create second video source if (camera2Combo.Enabled == true) { videoSource2 = new VideoCaptureDevice(videoDevices[camera2Combo.SelectedIndex].MonikerString);

videoSourcePlayer2.VideoSource = videoSource2; videoSource2.NewFrame += new AForge.Video.NewFrameEventHandler(Video2_NewFrame); videoSourcePlayer2.Start(); } } catch(Exception ex) { string exx = ex.Message; } }



Sending message to the network.

$
0
0
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress serverAddr = IPAddress.Parse("192.168.2.255");
IPEndPoint endPoint = new IPEndPoint(serverAddr, 11000);
string text = "Hello";
byte[] send_buffer = Encoding.ASCII.GetBytes(text );
sock.SendTo(send_buffer , endPoint);
What I am trying to do here is to notify all the computers inside the network that something will happen. For example, one of the computers sends a message like "How are you" and then all the other computers inside the network will be able to receive it. The code above only sends the data to a specific computer but i want all the computers to be able to receive the data aswell.

Regards

How to save finger data into a Database and Match finger with c# in ZK4500 Fingerprint Scanner?

$
0
0

I am using ZKFingerSDK 5.3. It has a demo for c# where they used a memory cache for testing purpose but I need to save finger data to database and match finger data for customer identification. Please give me a example how to save finger data into any database ((MS SQL/MySQL/sqlite) and how to match.

C# Demo Project -- https://github.com/emrancu/zk4500

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 );

Generating a Datagridview to another Winform on another laptop/PC using Wireless Connection

$
0
0

Hi Guys, i have a POS and Kitchen Queuing where the Kitchen Queuing display is in another laptop. I have 3 listview's which collects the data from the database[dbo.Kitchen] - columns (tblnmber, Product, Quantity), specifically the table number of the customer who ordered an item. and when you click the table number, the products and quantity will show on another listview which is also can be 'Accept' -using the btnAccept and Done -using the btnDone. when it's done the orders will clear and also the table number from the queue , it's good and also running smoothly.

But the problem is that our panelists, wants to make it like the queuing of Mcdo, which generates a datagridview (i guess) , and the orders are inside on it, and a timer on the top of that. I want my queue to make it like that because our panelists wanted to do so, but i don't have any idea generating that datagridview with the orders inside on it and a timer on the top. And ofcourse, clearing those order after the staff on the kitchen tap the button 'Done' inside the datagridview.

Any response or suggestions will be greatly appreciated ! Thank You!

ToolStripButton loosing focus after Enter/Spacebar key press

$
0
0

Hi All,

I have a ToolStrip control in one of the winforms and I have some ToolStripButtons in that. I have set the TabStop property of the ToolStrip control to true so that I can navigate to it using keyboard. Once I get focus to the ToolStrip control, I can use the arrow keys to navigate through the ToolStripButtons. I use ENTER/SPACEBAR to click an item to perform some actions. But it is being observed that the focus on the ToolStripButtons getting disappeared once the click (ENTER/SPACEBAR key press) is over. Is there any way so that I can retain the focus on the same ToolStripButton which was pressed? 

Thanks

Ajith

Find and replace all between xml TAGS

$
0
0

I have code to find and replace based on text area to multiple files (loop). I woudl like to change find to find everything between <variables></variables>. Theres a lot xml files and they have random text after <variables>. App work fine to search exactly what i paste in to the field and change it in all files.

Now I have winform System.Windows.Forms.TextBox to find text. How I can change it all to find only all between tags?

I know I can use regex match(?<=<variables>).+?(?=</variables>) but I don't know how.

public partial class FindReplaceForm : Form
    {
        private string outputDirectory;
        private string findWhatString;
        private string replaceWithText;
        private bool isMatchWholeWord;
        private bool isMatchCase;
        private bool isWildcard;

        public FindReplaceForm()
        {
            InitializeComponent();
        }
        private int DoFindReplace(BackgroundWorker worker)
        {
            int filesAffectedCount = 0;
            int counter = 0;

            string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.xml");

            int totalFiles = filesInDirectory.GetLength(0);

            foreach (string file in filesInDirectory)
            {
                if (FindAndReplace(file))
                {
                    filesAffectedCount++;
                }

                counter++;
                worker.ReportProgress((int)((counter / totalFiles) * 100.00));
            }
            return filesAffectedCount;
        }

        private bool FindAndReplace(string file)
        {
            string content = string.Empty;
            using (StreamReader sr = new StreamReader(file))
            {
                content = sr.ReadToEnd();
            }
            string searchText = GetSearchText(findWhatString);
            if (Regex.IsMatch(content, searchText, GetRegExOptions()))
            {
                string newText = Regex.Replace(content, searchText, replaceWithText, GetRegExOptions());
                using (StreamWriter sw = new StreamWriter(file))
                {
                    sw.Write(newText);
                }
                return true;
            }
            return false;
        }

        private RegexOptions GetRegExOptions()
        {
            RegexOptions options = new RegexOptions();
            if (isMatchCase == false)
                options |= RegexOptions.IgnoreCase;
            return options;
        }
        private string GetSearchText(string textToFind)
        {
            string searchText = Regex.Escape(textToFind);

            if (isMatchWholeWord)
            {
                searchText = string.Format("{0}{1}{0}", @"\b", textToFind);
            }
            if (isWildcard)
            {
                searchText = searchText.Replace(@"\*", ".*").Replace(@"\?", ".");
            }
            return searchText;
        }
        private void InitializeProcess()
        {
            outputDirectory = txtDirectory.Text;
            findWhatString = txtFindWhat.Text;
            replaceWithText = txtReplaceWith2.Text;
            isWildcard = chkUseWildcards.Checked;
            isMatchCase = chkMatchCase.Checked;
            isMatchWholeWord = chkMatchWholeWord.Checked;
            statusLabel.Text = "Pracuje...";
            progressBar.Value = 0;
            progressBar.Visible = true;
            btnReplace.Enabled = false;
            btnCancel.Enabled = true;
            backgroundWorker.RunWorkerAsync();
        }
        private void DeinitializeProcess()
        {
            statusLabel.Text = "Gotowy";
            progressBar.Visible = false;
            btnReplace.Enabled = true;
            btnCancel.Enabled = false;
        }
        private void BrowseDirectory()
        {
            FolderBrowserDialog browser = new FolderBrowserDialog();
            if (browser.ShowDialog(this) == DialogResult.OK)
            {
                txtDirectory.Text = browser.SelectedPath;
            }
        }
        private bool InputIsValid()
        {
            bool isError = false;
            errorProvider.Clear();
            if (string.IsNullOrEmpty(txtFindWhat.Text))
            {
                errorProvider.SetError(txtFindWhat, "This is a required field.");
                isError = true;
            }
            if (string.IsNullOrEmpty(txtReplaceWith2.Text))
            {
                errorProvider.SetError(txtReplaceWith2, "This is a required field.");
                isError = true;
            }

            if (string.IsNullOrEmpty(txtDirectory.Text))
            {
                errorProvider.SetError(txtDirectory, "This is a required field.");
                isError = true;
            }
            else
            {
                if (Directory.Exists(txtDirectory.Text) == false)
                {
                    errorProvider.SetError(txtDirectory, "The selected directory does not exist.");
                    isError = true;
                }
            }

            if (isError)
                return false;
            else
                return true;
        }
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            e.Result = (int)DoFindReplace(worker);
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DeinitializeProcess();

            if (e.Error != null)
                MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else if (e.Cancelled)
                MessageBox.Show(this, "Operacja przerwana przez użytkownika", "Anulowano.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                MessageBox.Show(this, string.Format("{0} plików zostało nadpisanych.", e.Result.ToString()), "Zamiana zakończona!", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            if (InputIsValid())
                InitializeProcess();
        }

        private void lnkBrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BrowseDirectory();
        }

    }
}


Viewing all 31927 articles
Browse latest View live


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