Darth Vader Junior Poster in Training

Hello,

I try to catch the HTML code from a webpage after I have logged in to a page.
HTML is returned but that is the orignal HTML only BEFORE I logged in. For example I try to find "Log out" and other content in the string "getDocumentHTML" returned which exists on the webpage. But that can't be found.

How do we returned the final HTML content for the webpage after logging in?

        private void button1_Click(object sender, EventArgs e)
        {
            String url = textBox1.Text;
            webKitBrowser1.Navigate("http://hotmail.com");
        }
        private void webKitBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //This doesn't returnd the FINAL HTML content after a login to a webpage
            String getDocumentHTML = webKitBrowser1.DocumentText;
        }

Darth Vader Junior Poster in Training

Hello,

I use the webkitbrowser which is simular to the webbrowser.
Now on a website, I want to programatically insert a string into a textBox.

This I have succeeded to do like this:

webKitBrowser1.Document.GetElementById("txtbox1").SetAttribute("value", "hello");

After this I will need to programatically click a button that will check that "hello" is correct. I have succeeded to click the button like this:

    webKitBrowser1.Document.InvokeScriptMethod("execFunction", new object[] {  });

Now comes the problem. When "execFunction" is activated which is a tag in HTML, I get the message that the "hello" string is not correct.
Now I know why that is the problem. The textBox1 control has an event that detects keydown like this: onkeydown="javaScript: afSI(event);"
So what is missing when just set the string "hello" is that there is a javascript event "afSI" that has registrated that the "hello" text was entered manually where the "onkeydown" fires.

Below are all the code including javascript code that detects "onkeydown": "Number($F) == 13"
So my question would be, instead of putting the string "hello" like above. Can we simulate "onkeydown" that sends along the string "hello" to the textBox with the KeyCode == 13 ?

            afSI($N)
            {
                var $F = document.all?event.keyCode:$N.which?$N.which:$N.keyCode?$N.keyCode:$J.charcode;
                var $T = document.frmMain.txtbox1;
                if(typeof $T!=='undefined')
                {
                    if($T.value.length > 0 && Number($F) == 13)
                    {
                        execFunction();
                    }
                }
            };

//This is the textBox
<input type="text" tabindex="1" class="ibtxt" name="txtbox1" id="txtbox1" maxlength="20" onfocus="javaScript: focusFunc(this);" style="display:inline;visibility:visible;" value="">
<input type="text" tabindex="2" class="ibtxt" name="txtbox1" id="txtbox1" maxlength="20" onkeydown="javaScript: afSI(event);" style="display:none;visibility:hidden;">

//This is the button
<a class="iomcc" href="#" tabindex="1" id="execButton" ...

Darth Vader Junior Poster in Training

Hello,

I have an application that is not mine, that has 6 textboxes with values on it.
I am trying to use the windows API to retreive the values from those textBoxes. I know that they exists in a control named "Panel1".
So I have come so far in the code like below to find the "Panel1". But from here, I can't manage to find the textboxes and get their values?
I have used "SysExp" software which do find those values for those textboxes so it is possible in somehow.

Code attempt:

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] StringBuilder lParam);

         private void button1_Click(object sender, EventArgs e)
         {

             foreach (Process p in Process.GetProcesses())
             {
                 if (p.MainWindowTitle.ToString().ToLower().Contains("applicationname"))
                 {

                     IntPtr applicationnamewindow = p.MainWindowHandle;
                     List<IntPtr> GetAllChildrenHandles = GetAllChildrenWindowHandles(applicationnamewindow, 100);
                     for (int i = 0; i < GetAllChildrenHandles.Count; i++)
                     {
                         try
                         {
                             IntPtr childHandle = (IntPtr)GetAllChildrenHandles[i];

                             const int WM_GETTEXT = 0x0D;
                             StringBuilder sb = new StringBuilder();
                             IntPtr retVal = SendMessage(childHandle, WM_GETTEXT, 10, sb);

                             if (sb.ToString().ToLower() == "panel1")
                             {

                                 //Inside this panel1 window. There exists 6 textBoxes. How to find them and get the value from them???
                             }
                         }
                         catch { }
                     }
                 }
             }
         }

Darth Vader

The better code attempt I have is the below. I have used the application WinSpy++ to identify the class name of the datagridview which is: "WindowsForms10.Window.8.app.0.141b42a_r13_ad1"
When running the code. The messageBox shows an empty string while the datagridview has alot of text in the cells.
I wonder if I am near a solution to get text from the datagridview?

static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] StringBuilder lParam);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
private void button15_Click(object sender, EventArgs e)
{
    foreach (Process clsProcess in Process.GetProcesses())
    {
        if (clsProcess.MainWindowTitle.ToString().ToLower().Contains("nameofapplication"))
        {
            Process[] processes = Process.GetProcessesByName(clsProcess.ProcessName);
            foreach (Process p in processes)
            {
                IntPtr pFoundWindow = p.MainWindowHandle;
                IntPtr childHandle;

                //Find window handle
                childHandle = FindWindowEx(
                    p.MainWindowHandle,    //Parent handle
                    IntPtr.Zero,    //Child window after which to seek
                    "WindowsForms10.Window.8.app.0.141b42a_r13_ad1", // Class name to seek (viewable in the Spy++ tool)
                    p.MainWindowTitle);

                const int WM_GETTEXT = 0x0D;
                StringBuilder sb = new StringBuilder();
                IntPtr retVal = SendMessage(childHandle, WM_GETTEXT, 100, sb);
                MessageBox.Show(sb.ToString());
            }
        }
    }
}

Darth Vader Junior Poster in Training

Hello,

I wonder how it would be possible to get text from a datagridview in another form application? The datagridview has 5 rows and 5 columns with text in each cell.

I know that this could be achieved with windows API but googling around I have not understand how to actually do this.

My beginning of code finds the application and in somehow we would return all childcontrols that exists to find the datagridview and extract text from the cells?

        [DllImport("user32.dll")]
        private void button15_Click(object sender, EventArgs e)
        {
            foreach (Process clsProcess in Process.GetProcesses())
            {
                //We found the application
                if (clsProcess.MainWindowTitle.ToString().ToLower().Contains("nameofapplication"))
                {
                    //Now how will we find the datagridview and extract text from the cells?
                    Process[] processes = Process.GetProcessesByName(clsProcess.ProcessName);
                    foreach (Process p in processes)
                    {

                    }
                }
            }
        }

Darth Vader

it does is frees up data that might be cached with say a router.........

That is a good thing. That is what I also experience that even sometimes you need to restart the router or shutdown the power and put it on for internet to work again and have the ability to use the /renew to renew the IP might be something that could solve that programatically.

Darth Vader

>> However, usually I do ipconfig /release first.

That was an interesting point. Should it be okay to run the below code or do you think you need to do any additional "wait/check" code to see that the IP has been released BEFORE renew the IP?

I beleive the renew means that it does refresh the IP address in someway but are not entirely shure either even when googling around to understand exactly what it it does. If it does anything on the router/adapter etc.

//Release
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "ipconfig";
info.Arguments = "/release "; //release
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(info);
p.WaitForExit();

//Renew
info = new ProcessStartInfo();
info.FileName = "ipconfig";
info.Arguments = "/renew"; //renew
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(info);
p.WaitForExit();

Darth Vader Junior Poster in Training

Hello,

I am trying to find all possible operative system/router/adapter reasons what can cause internet to stop connecting.
The goal is to create code that check for all those reasons and programatically resolves those issues.

I have found 2 codes that do reconnect the internet connection if not connected.
Example 1: enables the network adapter if disabled using "\" enable"

Example 2: I don't know what this code is doing. What is that code doing and how is it possible to check for if we need to "/renew" the connection?

Using "/renew" and "/release" connects and disconnects to internet in Example 2

//Example 1: Checking the network adapter
private void button2_Click(object sender, EventArgs e)
{
    bool isconnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
    if (isconnected == false)
    {
        EnableNetWorkAdapter("Local Area Connection");
    }
}
static void EnableNetWorkAdapter(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}

//Example 2: What is actually renewed here and how to check if we need to "/renew" the connection?
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "ipconfig";
info.Arguments = "/renew"; // or renew/release if you want to connect/disconnect
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(info);
p.WaitForExit();

Darth Vader

Thanks,

It seems that either of maximized/minimized works as below code.

ProcessWindowStyle.Maximized
ProcessWindowStyle.Minimized

The other thing is that I don't want the window to be maximized.

I would need to have the windows docked at the TOP and both SIDES and then specify a height of the window, let us say 200 px.

How could this be done?

Darth Vader Junior Poster in Training

Hi,

It is possible to open a webbrowser window with the below code.

I wonder how it would be possible to have the web browser docked at TOP of the desktop and
have the window stretched to LEFT and RIGHT of the desktop and also how to choose a HEIGHT
of the opened web browser window?

System.Diagnostics.Process.Start("opera.exe", "http://google.com");

Darth Vader

>> That sleeps even if the file is available. Maybe better like

I must ask, I don't think above is true as I am using "break" when it succeds and by this breaking out of the loop Before Thread.Sleep(1); ?

Darth Vader

The problem is that I am using the file lock technique now but this is very slow as you need to use Thread.Sleep(1). When using 1 millisecond sleep, that in practic isn't 1 millisecond as the kernel can wait up to half a second.

The ideá is good but the Sleep(1) and by using the catch{} are making it very slow if there is not any other way to improve the speed with this code?

            String lockfile = "C:/lockfile.txt"; FileStream lockfilestream = null;
            while (true)
            {
                try
                {
                    //Try to Lock the symbol file
                    lockfilestream = new FileStream(lockfile, FileMode.Open, FileAccess.Read, FileShare.None);
                    break;
                }
                catch { }
                Thread.Sleep(1);
            }
            ///
            ///
            //Critial code area
            ///
            ///
            if (lockfilestream != null) { lockfilestream.Close(); }

Darth Vader

Yes, I am trying to read about "named mutexes". That seems to be a solution to interprocess between for example 2 application where the "named mutex" can be accessible "computer wide" and then with other words by 2 different applications.

However I have never used it so I am not 100% sure of the fact above?
I found an example on this url:
"http://www.c-sharpcorner.com/UploadFile/1d42da/threading-with-mutex/"

The example shows to Wait and Release a named mutex like below. I wonder if this is the correct way to do it and that the mutex is accessible from 2 different applications?

        //Application 1
        void thread1()
        {
            Random rnd = new Random(); Mutex mutex = new Mutex(false, "RunsMutex");
            while (true)
            {
                mutex.WaitOne();
                //Allow only 1 application at a time in this code area!

                //release the mutex
                mutex.ReleaseMutex();
                Thread.Sleep(rnd.Next(1, 10));
            }
        }

        //Application 2
        void thread2()
        {
            Random rnd = new Random(); Mutex mutex = new Mutex(false, "RunsMutex");
            while (true)
            {
                mutex.WaitOne();
                //Allow only 1 application at a time in this code area!

                //release the mutex
                mutex.ReleaseMutex();
                Thread.Sleep(rnd.Next(1, 10));
            }
        }

Darth Vader Junior Poster in Training

Hello,

I wonder how we can use lock objects between 2 different applications.
In the example below we can use lock objects to let only one thread to execute the code inside the lock object at a time.
This works fine within one application.

Now I wonder how we can use a lock object between 2 different applications. Is there some kind of Global system lock that
can be used?

I have put this code as illustration of what I try to find a solution for:

        object lockobject = new object();

        //Application 1
        void thread1()
        {
            Random rnd = new Random();
            while (true)
            {
                lock (lockobject)
                {
                    //Allow only 1 application at a time in this code area!
                }
                Thread.Sleep(rnd.Next(20, 2000));
            }
        }

        //Application 2
        void thread2()
        {
            Random rnd = new Random();
            while (true)
            {
                lock (lockobject)
                {
                    //Allow only 1 application at a time in this code area!
                }
                Thread.Sleep(rnd.Next(20, 2000));
            }
        }

Darth Vader

Thanks for answer,

Yes, I will put the complete code to fully understand how I work with the currenttime.

Below is the so called EWrapperImpl class. This class has many events. I have just taken currenttime as an example.
The thing is that the class events like currenttime on intervals is returning the currenttime without calling any method.

public class EWrapperImpl : EWrapper
{
    public void currentTime(long time) 
    {
             Form1 form1 = new Form1();
      form1.functionNeedingGlobalValue(time);
    }
}

I do use an API that connects to a server with the below code in the "button1_Click"

namespace TestCsharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        String globalvalue = "";
        private void button1_Click(object sender, EventArgs e)
        {
            EWrapperImpl client = new EWrapperImpl();

            globalvalue = "hello";
            client.ClientSocket.eConnect("127.0.0.1", 7496, 0); //Connect to server
        }
        public void functionNeedingGlobalValue(long time)
        {
            MessageBox.Show(time.ToString() + "," + globalvalue);
        }
    }
}

If we take the above example, when I click on the button1_Click, this connects to the server. Then the currentime
returns the time value on the server. The thing is that I need to call "functionNeedingGlobalValue" which will also use
the "globalvalue".
In the above when "functionNeedingGlobalValue" is called the "globalvalue" is == "" even that it was set to "hello"
in the button1_Click.
I wonder why this happens?

However if I delcare like this instead:

static String globalvalue = "";

Then "hello" will be shown.
I think this leaves me with 2 questions. Is it a good practise to put static ...

Darth Vader Junior Poster in Training

Hello,

I will try to ask this question very straight forward to not complicate the example.
As seen the an event called currentTime is located INSIDE a public class EWrapperImpl.
The functions comes from a DLL reference file that I code against. By default it seems
that the currentTime(long time) has to be declared in the EWrapperImpl class.

I wonder if there are any standard procedure to be able to let this currentTime event
to Also run in the "public partial class Form1 : Form" somehow?

public class EWrapperImpl : EWrapper
{
    public void currentTime(long time) { }
}

What wonder is how it would be possible to have this event in the "public partial class Form1 : Form"
which is the application itself.

Can we declare the currentTime event in the below code somehow?

namespace TestCsharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeCompo nent();
        }

        //How is it possible to declare below function here?: 

        //"public void currentTime(long time) { }"
    }
}

Darth Vader Junior Poster in Training

Hi,

I get an error when trying to compile a class that I have created: "EWrapperImpl.cs"
Error: TestCsharp.EWrapperImpl' does not implement interface member 'IBApi.EWrapper.currentTime(long)

It is documented in an example that: "you need to provide at least an empty shell of the method declared in EWrapper"
but I don't know how to do this. I wonder if it is a basic delaration that can be done in EWrapper ?

    namespace TestCsharp
    {
        public class EWrapperImpl : EWrapper
        {

            EClientSocket clientSocket;

            private int nextOrderId;

            public EWrapperImpl()
            {
                clientSocket = new EClientSocket(this);
            }

            public EClientSocket ClientSocket
            {
                get { return clientSocket; }
                set { clientSocket = value; }
            }

        }
    }

Darth Vader

is just one instance on one core and threads appear to be in that CPU instance.
not thread but launch the app again which revs up another CLR

Thanks for your answer. Yes it is an extension of my last question. Sometimes its good to divide up the problem in two to not get to confusing.
I beleive the above that you mentioned are positive where threads are assigned to that CPU in which the instance was launched.
I have implemented the logic to launch instances/apps of the thread to be working in parallell and it actually so far is going well.
My test was with 10 apps in parallell and they executed the work in 1.30 minutes. Launching just one app, the work takes 13 minutes.
So it is about 10 times faster actually.

Darth Vader Junior Poster in Training

Hi,

I wonder if the below code I have take up "2 threads" on the processor.
In the Form1_Load event I call "startProcess". That process starts a backgroundworker
in a separate class. The process also monitor callbacks from the backgroundworker.
This is what makes me wonder if this takes up "2 threads" on the processor.

The big concern with my question is that I will launch the application 20 times which would
mean that 40 threads are running where perheps 20 of those are not nessecary.
To add is that is a big task to move the backgroundworker to the Form1.cs as the Instance.cs
contain 20,000 lines and alot of code to report back to "progress =>".

So I wonder if it takes up 2 threads. If so can there be a solution to make it only run the backgroundworker
as it is setup now and still monitor "progress =>" ?

        //Form1.cs
        private void Form1_Load(object sender, EventArgs e)
        {
            startProcess();
        }

        //Start thread
        void startProcess()
        {

            //Start the bgWorker with below code
            Project.Instance ts = new Project.Instance();

            ts.doSomething(
                //Here we will update the progress after different scenarios depending on the string that is received(message):
                        progress =>
                        {
                            //Get the returning string here:
                            String returnString = progress;
                            MessageBox.Show(returnString);
                        },
                        result =>
                        {
                            //bgWorker is finished
                        }
                    );
        }

        //Instance.cs
        public void doSomething(Action<String> progressCallBack, Action<String> completionCallBack)
        {
            BackgroundWorker bgWorker = new BackgroundWorker();
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.WorkerReportsProgress = true;
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.ProgressChanged += (sender, args) => { progressCallBack(args.UserState.ToString()); };
            bgWorker.RunWorkerCompleted += ...

Darth Vader

That is interesting, at this moment I do have Windows Enterprise 64 bit. I choosed that version of windows as it can handle two CPU.
I have 2 CPU with 16 cores in each. Total of 32 cores.

I have 4 CPU sockets on the motherboard so I will add 2 CPU/16 cores so I will have a total of 64 cores in the end.
Why I built this computer is just because this thread that I need to execute in parallell to make it faster.

TO THE QEUSTION:
The computer I have is a server - and Windows do have server versions of windows like for example "Windows Server 2012 R2"
I will need to upgrade to that version later as that version can handle 4 CPU as Windows Enterprise only can "see" 2 CPU.
I wonder if Windows Server 2012 R2 are better to execute work on different processors?

Darth Vader

*>> Hard disk reads are really slow, so programmers designed buffering so that they could read whole gobs of data all in one go

it shouldn't bother firing up additional processors to handle it's work load, it is going to dump them all on one processor*

Thanks for the great answers. It really helped out to understand this better.
With the arguments above, I have red in the data from the file into memory (a "string"). That should take up approx 15 MB.
Then I use StringReader to read line by line. So I beleive this will go much faster than "telling the hard disk to seek to that location"

Then it seems to be that the application may dump all Threads to one processor which makes the threads go slower.
So in combination with the StringReader, I will create a separate application to only execute this thread. As my test was that if I launch my app now 10 times, this will work 10 times faster, so it seems that the OS assigns the Apps to different processors much better.
I hope to be able to launch about 20-25 apps with this thread to make it more than 20 times faster as they will work in parallell.

Darth Vader

>> In one old app I didn't use new Thread but simply launched my app again with some parameters so it knew what to do. That way the OS would pick which CPU to run it on

This is what I am thinking of to do also. I have discovered like you that when launching the app again, this do double the speed. I tried just now to launch the app 8 times and it was exactly 8 times faster on the second almost.

I do have 32 cores, 32GB RAM in my system. So in that sense I have resources.
But as you mentioned: "OS would pick which CPU to run it on"
How does that work. Is one application "assigned" to a CPU, then 1 of the 32 cores?
When we create "new Thread", doesn't this then "assign" the thread to a separate CPU in the same way?
It seems that something different is happening here. I am very curious to what that is so it is possible to sort it out why?

Darth Vader

I have done a simple example test that really shows the difference and problem.
Using the code below and changing:
The number "10" in numberOfTasks = numberOfTasks / 10; (How many thread to be runned at the same time)
And comment out so many threads to be started: thread = new Thread(doSomething); thread.Start();

As seen below will be the benchmark which is a big question mark:

            Thread thread = new Thread(doSomething); thread.Start(); //1 core: 19.51 seconds
            thread = new Thread(doSomething); thread.Start(); //2 core: 11.44 seconds (Should be: 9.75 seconds)
            thread = new Thread(doSomething); thread.Start(); //3 core: 9.0 seconds (Should be: 6.5 seconds)
            thread = new Thread(doSomething); thread.Start(); //4 core: 7.2 seconds (Should be: 4.9 seconds)
            thread = new Thread(doSomething); thread.Start(); //5 core: 6.4 seconds (should be: 3.9 seconds)
            thread = new Thread(doSomething); thread.Start(); //6 core
            thread = new Thread(doSomething); thread.Start(); //7 core
            thread = new Thread(doSomething); thread.Start(); //8 core
            thread = new Thread(doSomething); thread.Start(); //9 core
            thread = new Thread(doSomething); thread.Start(); //10 core: 4.8 seconds (should be: 1.9 seconds)

Now comes the mystery. If I open up 10 instances of the complete application itself instead and run "1 task" in all applications at the Very same time which is equivalent where we use 10 cores/threads and divide numberOfTasks / 10. This will then only take: 2 seconds INSTEAD OF 4.8 seconds as it should do where 19.51 / 10 = 2 seconds approx.

This means that my computer are able to handle 10 tasks at the same time ...

Darth Vader

I have a RevoDrive in my computer which reads/writes 1250 MB/s vs a HDD that only reads/writes about 100 MB/s. So my harddrive is almost 3 times faster than a SSD which means extremely fast, so this can't be the main problem in this case. Also 95% of the timeconsuming work is in the code itself. With other words Substrings,calculations,IndexOf etc so it depends on the cycles of the CPU.

(Added text:
I just tried to read all txt files into memory before the process will run. So I use a for loop instead with the text files in memory.
I get the same slow result as the below benchmark. So the harddrive is not the problem.)

As I have 32 cores and as seen the below benchmarks, problem already occurs if I try to run the backgroundworker with 4 cores which really confuses me. It sounds strange that I have gone over the limit of threads that exist in my computer with only 4 cores?

  • If I use 1 process (1 core), the task takes 12 minutes.
  • If I use 2 process (2 cores), the task takes 7 minutes (This is what my goal is with multithreading)
  • If I use 4 process (4 cores), the task takes also 7 minutes (How is this possible? It should take 3.5 minutes?)
  • If I use 25 process (25 cores), the task takes 18 minutes. (But what happens with 25 cores. It takes even longer time?)

Darth Vader Junior Poster in Training

Hello,

I have a very strange problem. I have created a code that I beleive is multicore/parallell threading to make a task to run faster using more cores in the computer.

My computer is a server:
32 cores (2 CPU with 16 cores each)
32 GB

Refering to my code:

  • If I use 1 process (1 core), the task takes 12 minutes.
  • If I use 2 process (2 cores), the task takes 7 minutes (This is what my goal is with multithreading)
  • If I use 4 process (4 cores), the task takes also 7 minutes (How is this possible? It should take 3.5 minutes?)
  • If I use 25 process (25 cores), the task takes 18 minutes. (But what happens with 25 cores. It takes even longer time?)

As seen if I use 25 processes, it even takes longer which is my very big question mark here. I have no idéa why this is happening.

The thing is that I have 50 files that I will read, so every file if using 1 core takes: 12/50 minutes = 14 seconds
Now I do start 25 backgroundworkers and send along 2 files to each backgroundworker in hope that this will go much faster, in theory approx: 14 seconds x 2 = 28 seconds to complete all 25 backgroundworkers.

All backgroundworkers do work and in the end they produce the same result as 1 backgroundworker doing all 50 files. But it takes 18 minutes.

I simply can't understand why ...

Darth Vader

Thanks DaveAmour,

You are right. I took that away and it works.
I didn't know the static did share it.

Thanks

Darth Vader Junior Poster in Training

Hello,

I have an instance called "Instance".

From the button event I try to create 2 Instances of "Instance".
I want those 2 Instances to be completely separate from eachother in terms of the variables that exists inside "Instance".

So for example you can see the List variable: "instanceValues"

However, when I click the button to do a test to see if "instanceValues" is 0 when written to file,
the value is 0 for the first file "D:/test0.txt" but for the second file "D:/test1.txt" the value is 3 which I don't want it to be.

This must mean that the "instanceValues" List variable is not its own in each "Instance" but seems to be shared.

How to make the "Instance" isolated from eachother?

//Form1.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace HelloWorld
{
        private void button1_Click(object sender, EventArgs e)
        {
            HelloWorld.Instance ts = new HelloWorld.Instance();
            ts.doSomething(0);

            HelloWorld.Instance ts2 = new HelloWorld.Instance();
            ts2.doSomething(1);
        }
}
----------------------------------------------------------------------------------------------------------------

//Instance.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace HelloWorld
{
    public class Instance
    {

        static public List<String> instanceValues = new List<String>();
        public void doSomething(int number)
        {
            //Create file
            StreamWriter writer = null; FileStream fs = null;
            fs = new FileStream("D:/test" + number.ToString() + ".txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); writer = new StreamWriter(fs);
            writer.WriteLine(instanceValues.Count);
            writer.Close(); fs.Close();

            //Just add something
            instanceValues.Add("a");
            instanceValues.Add("b");
            instanceValues.Add("c");
        }

        class oneclass
        {
            //This function needs to access instanceValues as well
            public void dosomethingelse()
            {
                instanceValues.Add("c");
            }
        }
    }
}

Darth Vader

Thanks DaveAmour,

You solved the problem perfectly! :)
I was doing the wrong thing with the .length there. So I removed it and it was correct.

Thank you!

Darth Vader Junior Poster in Training

Hello,

I am trying to restrict to maximum type 60 words in a textbox.
I have tried to put a code that check if we have more than 60 words.

The code restricts to 60 words but when I loop the textboxes words and put back the string (up to 60 words) the string says:

"undefined undefined undefined undefined... etc"

Why does this happen? what is undefined?

 <asp:TextBox ID="TextBox26" runat="server" Height="209px" TextMode="MultiLine" onkeyup="return countwordsarticle();"
                Width="650px" Font-Names="Arial" Font-Size="10pt" ForeColor="#333333"></asp:TextBox>

    function countwordsarticle() {

        var str1 = document.getElementById("TextBox26").value.replace("  ", " ").trim();
        var words1 = str1.split(' ').length;

        //If more than 60 words only show 60
        if (words1 > 60) {

            var newstr;
            for( var i = 0; i < 60; i++ )
            {
                newstr = newstr + words1[i] + " ";
            }

            //Put to textbox
            document.getElementById("TextBox26").value = newstr.toString();
        }

        return false;
    }

Darth Vader

Yes I will share if I find a way to do it. Thanks for your help!