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

Opening an item from a listbox

$
0
0

Hello, I am working on a simple application that I have ran into a snag. Currently I have a listbox being populated from a network directory. 

            DirectoryInfo dinfo = new DirectoryInfo(@"N:\Support Teams\Information Technology\Documents\Guides\KB\");
            FileInfo[] Files = dinfo.GetFiles("*.*");

            foreach (var file in dinfo.GetFiles("*", SearchOption.AllDirectories))
            {
                listBox1.Items.Add(file.Name);
            }

Which works fine. The directory has a tree of folders that contain documents; so the search function was added to accommodate for this.

The issue I am having is trying to open the files from the list.

private void button1_Click(object sender, EventArgs e)
        {
            string file = listBox1.SelectedItem.ToString();

            string fullFileName = Path.Combine(@"N:\Support Teams\Information Technology\Documents\Guides\KB\", file);
            //Process.Start(fullFileName);
            MessageBox.Show("" + fullFileName);
        }

I was using a messagebox to help figure out the issue I was having, and as you can tell; it's not recognizing the folder the file is in. How  can I get Process.Start to read the full path of the file trying to be open, so it will actually open the file? 

Thanks! 



How To Send Message To Windows Application Users on Another PC

$
0
0

Hello,

        Please consider this scenario. I have one windows c# application which is being used by 5 different users on different machines. I want to lock/close the application but before locking that application as Admin I want send notification message to all users that "please save your current work . Application will be closing in 5 minutes."

    So how this can be achieved using windows C# application so that I will be able to send message to all users before restricting that application access???? I have stored username with their respected machine names as well but dont know how to send message to that machine by its name. Please help to solve this problem.

Thank You.

finally{ } - does not execute allways !

$
0
0

Hi!

Question: In MSDN is written 
Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement."???  

Also "Although the catch clause can be used without arguments to catch any type of exception, ..."

To put it mildly is not quite right.

Why a lot of people are sure that finally{} block will work allways?

I found out that finally block (also catch{}) doesn't work allways - even in try-catch-finally.

I generate a concrete exception (StackOverFlow) that can't be caught in  catch(StackOverflowException ex).

After getting into try{ } - application is closing (error) without execusion of any catch{ } (even StackOverflowException ) and finally{ }.

I think that such kind of situation should be marked in MSDN.

Breakpoint moves to top of function

$
0
0

For some unknown reason, I got a new annoying behavior with the debugger of VS C# 2015.

When I put a breakpoint on a particular line, at debugging time, the breakpoint moves to the top of the function it is in, and the whole function code is highlighted in red (as a single breakpoint).

When the breakpoint is reached in the execution at the top of the function,  the function code becomes highlighted in orange (not the usual yellow).

Anyone can tell me how to fix this? 

How to check if same client is reconnected in client socket

$
0
0

Hi, I make a client-server application using wpf. In server application, all connected client is added to listbox and all client has a countdown timer and online-offline icon in that list. Server app is to monitor the online-offline and time left of the client app, when the clinet has timed out then in server will show a messagebox/notification that this client has timed out. I can detect online-offline client, but, how to detect if same client is reconnected (disconnected before the client is timed out). For example, when a problem in network connection, and the client is temporary disconnected then the icon of this client in the client listbox is changed to offline and when the network is back online then the client reconnect automatically to server and synchronize the countdown timer in client and server and client's icon is changed to online?

Thank you,

LINQ on DataTable to select rows which only match a list is not responding forever.

$
0
0
          
if (A_dt.AsEnumerable().Where(r => A_list.Contains(r.Field<string>("Pres_Id"))).Any())
{
                                                    A_dt = A_dt.AsEnumerable().Where(r => A_list.Contains(r.Field<string> "Pres_Id"))).CopyToDataTable();
}

I've been using this kind of code frequently.

And at the first line, Any() returns true and Debugger goes to 3rd line.

However, the 3rd line code doesn't finish at all and the Debugger never goes to 4th line..with no exception and no debugger message..

It's really strange because same code with Any() works fine and pass as normal.

Is this a kind of bug?

What are the important points in this situation? How Can I overcome this problem?

For your information, the number of items in A_list (List<string>) and the number of rows in A_dt are each around 50,000

Thank you for your excellent opinions !


Calling a C# DLL from MFC application - Properties missing

$
0
0

I can provide more details if needed.

Firstly, I have this method in my COM DLL:

        public void GetStudents(out Publisher[] aryStudents)
        {
            List<Publisher> listStudents = new List<Publisher>();

            foreach (KeyValuePair<string, Publisher> pkvPair in _PublisherData.PublisherDictionary)
            {
                if (pkvPair.Value.Assignments.CanUseFor(AssignmentType.Student))
                {
                    listStudents.Add(pkvPair.Value);
                }
            }

            aryStudents = listStudents.ToArray();
        }

It exposes a SAFEARRAY* of Publisher objects.

Now, in MFC, when I use the object browser:

Object Browser

I can see the Publisher object is there. But, when I try to access the SAFEARRAY in MFC:

void CTestDlg::OnBnClickedButtonTest()
{
	MSAToolsLibrary::IMSAToolsLibraryInterfacePtr p;
	HRESULT	hr;
	hr = p.CreateInstance(__uuidof(MSAToolsLibrary::MSAToolsLibraryClass));
	if (SUCCEEDED(hr))
	{
		__int64 i;
		p->SetPathXML(m_strPublisherDatabaseXML.AllocSysString(), &i);
		p->ReadPublisherData(&i);

		SAFEARRAY *pub;

		p->GetStudents(&pub);

		MSAToolsLibrary::Publisher *pVals = NULL;
		HRESULT hr = SafeArrayAccessData(pub, (void**)&pVals); // direct access to SA memory

		if (SUCCEEDED(hr))
		{
			long lowerBound, upperBound;  // get array bounds
			SafeArrayGetLBound(pub, 1, &lowerBound);
			SafeArrayGetUBound(pub, 1, &upperBound);

			long cnt_elements = upperBound - lowerBound + 1;
			for (int i = 0; i < cnt_elements; ++i)  // iterate through returned values
			{
				// How do I access the publisher methods ?
			}
			SafeArrayUnaccessData(pub);
		}
		SafeArrayDestroy(pub);
	}
}


I can't see any of the Publisher properties (Name etc.). What am I doing wrong?

Yes, if I look here:

Object Browser

It tells me the array is of type MSAToolsLibrary::PublisherEntry::Publisher but I can't see MSAToolsLibrary::PublisherEntry in my droplist in MFC.

Problem to length of decrypted value

$
0
0
Hi,
How to avoid THIS PROBLEM 
Invalid length for a Base-64 char array or string.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.FormatException: Invalid length for a Base-64 char array or string.

Source Error:


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:



[FormatException: Invalid length for a Base-64 char array or string.]
   System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) +14116343
   System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) +162
   System.Convert.FromBase64String(String s) +56
   ChgPass._Default.DecryptStringAES(String cipherText, String sharedSecret) +231
   ChgPass._Default.Page_Load(Object sender, EventArgs e) +269
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178



due to 1st line below?
Session["userpass"] = DecryptStringAES(Request.QueryString["password"], "abcdef");

        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }



Many Thanks & Best Regards, Hua Min


Formatting Strings In C#

$
0
0

I am pulling data and have two variables d1 (date in yyyymmdd format) and t1 (time in 24 hour format).  I want to format both of the strings so that d1 is in a mm/dd/yyyy format and t1 is in "American" time (so 17:10:00 = 5:10 PM).  

Then once the strings have been formatted I want to print them so they display together like

Console.WriteLine(The date and time are as follows: " + d1 + " " + t1);


And the output you would see is : 01/07/2016 10:42 AM

This is the syntax I am using to extract the values:

foreach (var info in xml.Descendants("Parent"))
{
	d1 = (string)parent.Descendants("POD").FirstOrDefault();
	t1 = (string)parent.Descendants("TOD").FirstOrDefault();
}


And I have tried

DateTime dt = DateTime.ParseExact(d1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
var customdt = dt.ToString("MM/dd/yyyy");


Which throws an error of:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

What do I need to do to format my strings as needed?

*To Sum It Up*- 

format d1 As mmddyyyy = 01/07/2016

format t1 As HH:MM = 10:48

Then combine the strings so output is

The date and time is: 01/07/2016 10:48

C# using Visual Studio 2015

value updateing problem

$
0
0

I am trying to get the value n to update but it will not work for some reason. The code i have so far os

if (coloum.Text == "1")
                {
                    if (i > s1)
                    {
                        MessageBox.Show("There are " + s1 + " stones left in this column.");
                    }
                    else
                    {
                        s1 = s1 - i;
                        coloum.Text = "";
                        stones.Text = "";
                        n = n + 1;
                        if  (n == 3)
                        {
                            n = 1;
                            player.Text = "Player " + n;
                        }

the if (coloum.Text == "1") is true so the stement does run and if (i > s1) then the message box dose show,

s1 = s1 - i;
coloum.Text = "";
stones.Text = "";

this part is also updated however my n value will not update at all.

I have declered private int n; at the start

any help?

I'm using visual studios 2015 c#

Convert Word to HTML with Track Changes

$
0
0

Hello,

I want to convert my word document into HTM Tags with track changes highlighted. I am able to convert word document to html but text present in word document having track changes are resulting as simple plain text in HTML I want to show them in background colour as yellow in HTML please help

            byte[] byteArray = File.ReadAllBytes(@"C:\Users\admin\Desktop\New Microsoft Word Document.docx");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    int imageCounter = 0;
                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        PageTitle = "My Page Title",
                        ImageHandler = imageInfo =>
                        {
                            DirectoryInfo localDirInfo = new DirectoryInfo(@"C:\Users\admin\Desktop\img");
                            if (!localDirInfo.Exists)
                            {
                                localDirInfo.Create();
                            }++imageCounter;
                            string extension = imageInfo.ContentType.Split('/')[1].ToLower();
                            ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                extension = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "gif")
                                imageFormat = ImageFormat.Gif;
                            else if (extension == "bmp")
                                imageFormat = ImageFormat.Bmp;
                            else if (extension == "jpeg")
                                imageFormat = ImageFormat.Jpeg;
                            else if (extension == "tiff")
                            {
                                extension = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "x-wmf")
                            {
                                extension = "wmf";
                                imageFormat = ImageFormat.Wmf;
                            }
                            if (imageFormat == null)
                                return null;

                            string imageFileName = @"C:/Users/admin/Desktop/img/ image" +
                                imageCounter.ToString() + "." + extension;
                            try
                            {
                                imageInfo.Bitmap.Save(imageFileName, imageFormat);
                            }
                            catch (System.Runtime.InteropServices.ExternalException)
                            {
                                return null;
                            }
                            XElement img = new XElement(Xhtml.img,
                                new XAttribute(NoNamespace.src, imageFileName),
                                imageInfo.ImgStyleAttribute,
                                imageInfo.AltText != null ?
                                    new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                            return img;
                        }
                    };
                    XElement html = HtmlConverter.ConvertToHtml(doc, settings);
                    File.WriteAllText(@"C:\Users\admin\Desktop\New Microsoft Word Document.html", html.ToStringNewLineOnAttributes());
                };
            }

C#, TCP/IP data display problem.

$
0
0

Hello,

I have problem with correctly  display string. Its app for robot. App in C# connect via TCP/IP to raspberry pi python server.

In Form it is ok, but in WPF display bad. Can U help me with this?

Here are screens from C# form and WPF: https://1drv.ms/f/s!ApP5VZnNduYwg3t7cY4zVQ_XapGE

Calculate Number Of Days Between Two Dates Excluding Saturday And Sunday

$
0
0

In C# how can I calculate the number of days between two dates BUT exclude Saturday & Sunday. 

If date1 = 01/04/2017 and date2 = 01/09/2017

Then I would want the number returned to be 4 because

01/04/2017 = Wednesday

01/05/2017 = Thursday

01/06/2017 = Friday

01/07/2017 = Saturday

01/08/2017 = Sunday 

01/09/2017 = Monday

What C# syntax would accomplish this?

Catch To Never Return A Negative Number

$
0
0

Is this the best check to use to never allow a variable to return a negative number? (it shows 0 instead of a negative)

return (int)(i/2f + Math.abs(i)/2f)


Val() in C#

$
0
0

What is the equivalent in C# to the Val() function in Visual Basic? Also, what do the Right() and Left() functions do?

Here is my code:

Dim Num As Byte
Dim File As String
Num = Val(Right(Left(Right(File, Len(File) - i), 8), 3))


Storing multiple variable types in a list?

$
0
0

Hi everyone. So I have a strange question. Is it possible to store a bunch of different data types into a list? Something like the following...

List<Object> list = new List<Object>{new {type=DateTime, name="Date Sent"}};

The above code doesn't work at all. Does it make sense what I am trying to do? I could use some help. Thanks!


In Calculus, 1+1=0.

Images are not loaded in visual-studio 2015

Timers on a dedicated background thread?

$
0
0

Hello, for a bit of C# fun, I adapted a "timer thread" set of classes I originally made in Visual C++ to C#. It is here in GitHub:

https://github.com/terrymci/TimerThread

It is basically a way to have any number of timers, each with a configurable delay, period, and optional finite event count, and all of them processed on a dedicated background thread. When I developed this in C++, I needed this for serial communications with embedded-ish peripheral devices that required a lot of cyclical activities, and special case timed events (e.g. when communications broke down due to a power suspension, there needed to be some delayed and limited retries to re-establish communications.) It worked very well, and was reused in a few similar contexts. I made the C# adaptation of this as an exercise, to see how it might be done differently with C# versus C++, particularly to see if the .Net framework already implemented the same thing. I didn't see much of anything like this. The closest equivalent is the System.Threading.Timer class. It has the same idea of an initial delay and finite count; more sophisticated than the "WM_TIMER" message from straight Windows API and MFC days. But the timer handlers are called via the managed thread pool, so you don't control which thread will run them. For serial communications, this is a problem. Multiple threads dealing with a serial connection seems like a recipe for chronic threading bugs.

I would like to know if my C# project is reinventing a wheel that's already been created? The other timer mechanisms in the .Net framework besides System.ThreadingTimer appear to be for UI thread operations (per this MSDN page: https://msdn.microsoft.com/en-us/library/zdzx8wx8(v=vs.110).aspx) 

Thanks,

Terry McIntyre

Set parent of a Windows Form as a Store Application Window is not working(Windows 10).

$
0
0
Hi Experts,

I am trying to set the owner or parent  of a  Windows form as  store app window.
using the ShowDialog() method - Passed store app window handle to ShowDialog().

Its not working once I set the owner(storeappwindow) then form is not visible any more.

I override the CreateParams() and set parent then also its not working.

Does anybody know why its not working in Windows Forms.
Please share the solution

Additional findings

 -  Its working fine with OpenFileDialog(Windows Common Dialog - Unmanged).

   If I set the owner of OpenFileDialog as store app window its working fine

 - Its working fine with a MFC dialog application

    If I set the parent of CDialog as store app window its working fine.

Thanks,
Bhash


Need Help with array and objects

$
0
0

Basically I'm a student who needs help. Im trying to define 'species codes' to a zookeeper but it always gives a 'System.IndexOutOfRangeException' error.

My class:

class zookeeper
    {
        string zkid = "ZK00";
        string zkname = "Default";
        int zkhpnum = 12345678;
        int zkage = 0;
        string[] zkspecode = { "XX" };


        public string _Zkid
        {
            get { return zkid;}
            set { zkid = value; }
        }
        public string _Name
        {
            get { return zkname; }
            set { zkname = value; }
        }
        public int _HpNum
        {
            get { return zkhpnum; }
            set { zkhpnum = value; }
        }
        public int _Age
        {
            get { return zkage; }
            set { zkage = value; }
        }
        public string[] _ZKSpeCode
        {
            get { return this.zkspecode; }
            set { zkspecode = value; }
        }

        public void DisplayAllZK()
        {

        }
    }
Im trying to load it when i start my program but the error happens at "A2" below:
        private void Form1_Load(object sender, EventArgs e)
        {


            for (int i = 0; i < 99; i++)
            {
                ZK[i] = new zookeeper();
            }

            // Assign details to the first Zookeeper
            ZK[0]._Zkid = "ZK01";
            ZK[0]._Name = "Michael Gou";
            ZK[0]._HpNum = 84285392;
            ZK[0]._Age = 81;
            ZK[0]._ZKSpeCode[0] = "A1";
            ZK[0]._ZKSpeCode[1] = "A2"; <--------Error
            ZK[0]._ZKSpeCode[2] = "A3";
            ZK[0]._ZKSpeCode[3] = "A4";

            // Assign details to the second Zookeeper
            ZK[1]._Zkid = "ZK02";
            ZK[1]._Name = "Tommy High";
            ZK[1]._HpNum = 98584828;
            ZK[1]._Age = 59;
            ZK[1]._ZKSpeCode[0] = "A5";
            ZK[1]._ZKSpeCode[1] = "A6";
            ZK[1]._ZKSpeCode[2] = "A7";
            ZK[1]._ZKSpeCode[3] = "A8";
            ZK[1]._ZKSpeCode[4] = "A9";

        }

Viewing all 31927 articles
Browse latest View live


Latest Images

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