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

Is the a better way to do this ArrayList search

$
0
0

I and calling a simple procedure to pull back 12 values per row. It seems to put it into an array list of objects. This is what I am doing....Is there a better/faster way?

        private void buildDynamicSort(string o)
        {
            ArrayList al = new ArrayList();
            if (ddr == null)
            {
                ddr = GenericCommand.ExecuteReader("GetTrkCustomField");
                while (ddr.Read())
                {
                    object[] values = new object[ddr.FieldCount];
                    ddr.GetValues(values);
                    al.Add(values);
                }
                foreach (var item in al)
                {
                    string[] arr = ((IEnumerable)item).Cast<object>()
                                  .Select(x => x.ToString())
                                  .ToArray();

                    switch (arr[12])
                    {
                        case "Numeric":
                            Console.WriteLine("Case 1");
                            break;
                        case "Text":
                            Console.WriteLine("Case 2");
                            break;
                        case "Dropdowns":
                            Console.WriteLine("Case 3");
                            break;
                        case "Date":
                            Console.WriteLine("Case 4");
                            break;
                    }
                }
            }
        }


www.helixpoint.com


Creating an app for the Desktop

$
0
0

Hi friends,

I am trying to develop a to do list app for my windows 10 desktop. I want this app to be visible on the desktop at all times; pretty much behave like a gadget. Is there an API that gives access to the desktop?

If I can't get it to behave like a gadget, I will settle for writing to my to dos to the desktop.

Thanks.


The best things in life are free, but the most valuable ones are costly...use opportunities well for there are others, like you, who deserves them, but don&#39;t have them...

Linq to SQL use Distanct to get only one instance of each last name

$
0
0

Hi everyone:

Linq to sql database table in windows from application

Data in the sql database table Mates

Name     Age

Smith      22

Adams    42

Smith     32

Toms       18

Smith       72

I want to only get the result

Smith

Adams

Toms

Use Distinct to get the unique items into a listbox 

the code below gives all the  6 names?  I only want one of each name

Namedatacontext db = new Namedatacontext();

Var qry = from be in db.Mates

              Select be.Distinct;

Foreach (t in be)

              Listbox1.items.add(t.Name);

Need help

JereTheBear

Reading registry value from HKEY_LOCAL_MACHINE

$
0
0

My code read from HKEY_LOCAL_MACHINE\\SOFTWARE\\MyApp.

I created keys & values in HKEY_LOCAL_MACHINE\\SOFTWARE\\MyApp using RegEdit.exe.

However wrong value is read when I read using LocalKey.GetValue("ID");

In case of HKEY_CURRENT_USER, I can read correctly but not in HKEY_LOCAL_MACHINE.

How could I read correctly?



Math Problems Solving Application (Desktop) Using C#

$
0
0
Hello everyone. In our university we have to submit a term project in C#. For that I am thinking about an app which can solve math problems like Integration, derivation, limits , matrices and some other things like these. Now I am good at maths and I can solve these problems but the problem is that I'm not sure that this can be done effectively in C#. So I need Suggestions for you guys that it is a good decision and worth it. Please I need your contribution. And also that what kind of this can be like editor.     

Retirement of Exam 70-483

$
0
0

Hello

Is it worth it to get a certification that is being retired next year March???

Get address property for USB Bulk device

$
0
0

Hello,

I'm developing an application under c# which interacts with ARM development boards acting as BULK devices. When I connect two or more there is no way to know which card I'm talking to unless I know the "address" property. Is there any way to obtain that property? could be any example. Actually I was trying with the online example but those are working with Win32_PnPEntity but that property is not available.

Is there any other way to get that information?

Thanks

Passing argument to CMD, CMD returns "parse error"[solved]

$
0
0

Hello,

I'm hoping someone can point me in the right direction. I need to call an elevated cmd to copy a folder from a specified location to another. Sadly the Target location tends to need admin rights to modify.

string CmdString = "xcopy /I /E"+ " " + "\"" + SourcePath +"\""+" "+"\""+ TargetPath +"\"";

ProcessStartInfo copy = new ProcessStartInfo("cmd.exe");
                copy.UseShellExecute = true;
                copy.Verb = "runas";
                copy.Arguments = "/K" + "\""+ CmdString + "\""; // /K Goes There Apparently.
                Process.Start(copy);

Whenever this is ran an elevated cmd prompt appears correctly but all it displays is "parse error" and waits for the next command. If I write my CmdString string to console and copy it directly into the cmd window it works exactly as expected.

I'm terribly sorry if this is an obvious answer. I have been searching for a couple of hours now and cannot wrap my head around what I have done wrong.

Edit: If I add the \K switch it changes the error code to "'/K' is not recognized as an internal or external command, operable program or batch file." So the only somewhat hopeful result my searches turned up doesn't work.

Edit2: Turns out I am indeed an idiot and the /K switch had to be prepended to the copy.arguments value rather than the CmdString. I'll leave this up incase anyone else makes a stupid mistake like I.

Thank you for reading.Sorry for wasting your time.








Set label location on full screen

$
0
0

Hello,

I have to make milionare game,

I have a layout and my idea is to add to some fields labels with question and answers. I set my form on maximalized and when I start my label is not in place where it was on form[design] how to do it correctly?

Also a size is changing if game is maximalized.

Should i calcuate this from screen resolution or is easier way to do it ?


Piotr Robak



Windows Phone 8.1: "No suitable method found to override" - but there is one

$
0
0

Hello.

I have base class with navigation logic:

using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Microsoft.HockeyApp.Common; namespace View { public abstract class CommonPage : Page { private readonly NavigationHelper navigationHelper; private readonly ObservableDictionary defaultViewModel; public CommonPage() { defaultViewModel = new ObservableDictionary(); navigationHelper = new NavigationHelper( this ); navigationHelper.LoadState += NavigationHelper_LoadState; navigationHelper.SaveState += NavigationHelper_SaveState; } public NavigationHelper NavigationHelper { get { return navigationHelper; } } public ObservableDictionary DefaultViewModel { get { return defaultViewModel; } } protected virtual void NavigationHelper_LoadState( object sender, LoadStateEventArgs e ) { }

protected virtual void NavigationHelper_SaveState( object sender, SaveStateEventArgs e ) { } protected override void OnNavigatedTo( NavigationEventArgs e ) { navigationHelper.OnNavigatedTo( e ); } protected override void OnNavigatedFrom( NavigationEventArgs e ) { navigationHelper.OnNavigatedFrom( e ); } } }

And I have child class:

using Microsoft.HockeyApp.Common;

namespace View.Chats
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ChatPage : CommonPage
    {
        public ChatPage()
        {
            InitializeComponent();
        }

        protected override void NavigationHelper_LoadState( object sender, LoadStateEventArgs e )
        {
            base.NavigationHelper_LoadState( sender, e );
        }
    }
}

But I have next error in compile time:

Error CS0115 'ChatPage.NavigationHelper_LoadState(object, LoadStateEventArgs)': no suitable method found to override

Who knows how to fix it?

Please, help :)

C# Program takes all of the memory

$
0
0

Hi there, 

The below program takes a very big HTML (4GB), my laptop has 16GB of memory.

When I run the program, it does the job, but it gradually takes more and more memory (looking at the TaskManager).

Why would that be since the file is only 4GB in size ?

What am I doing wrong please ?

What would you do differently ?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;




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

        private void button1_Click(object sender, EventArgs e)
        {
              // Open File =====================================================
            string userFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Desktop";

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = userPath;
            ofd.Filter = "html files (*.html)|*.txt|All files (*.*)|*.*";
            ofd.FilterIndex = 2;
            ofd.RestoreDirectory = true;
            ofd.ShowDialog();
            string fName = ofd.FileName;
            label1.Text = fName;
            label1.Refresh();
            string theHTMLFile;
            theHTMLFile = fName;
            int collectedCount = 0;
            string theQuery;
            string con_string = "Server=127.0.0.1;Database=SHARES;Integrated Security=true;";
            // Open File ==========================================================

            // Get numbers ========================================================

            var numbers = new List<int>();
            var lines = new List<string>();
            var lineCount = 0;
            string num;
            int counter = 0;
            int numbersCount = 0;
            int onePercent;


            using (var reader = File.OpenText(fName))
            {
                while ((num = reader.ReadLine()) != null)
                {
                    counter++;
                    numbersCount++;
                    if (num.IndexOf("</tr>") != -1)
                    {
                        //MessageBox.Show("counter: " + counter.ToString() + "num: " + num);
                        numbers.Add(counter);
                    }
                }
            }

            // Get numbers ===============================================================

            int rowNumber = 1;
            int progressBarPercentage;

            for (int x = 1; x < numbers.Count(); x++) // Take another line number 352, 362, 372 etc.
            {
                rowNumber = numbers[x];
                label2.Text = x.ToString();
                label2.Refresh();
                onePercent = ((numbers.Count() / 100));

                // =================================================================================

                string lineOfHTML = "";
                var srhtml = new StreamReader(theHTMLFile);

                for (int y = 1; y <= rowNumber; y++) // read lines one by one and process eight rows when its found at line 352 - 9
                {
                    lineOfHTML = srhtml.ReadLine();
                    lineCount++;
                    if (lineCount == (rowNumber - 9))
                    {
                        while (collectedCount <= 7)
                        {
                            lines.Add(srhtml.ReadLine().Replace("<td valign=\"top\" nowrap=\"nowrap\">", "").Replace("</td>", "").Replace(",", " & "));
                            lineCount++;
                            collectedCount++;
                        }
                        collectedCount = 0;

                        theQuery = "INSERT INTO [SHARES].[dbo].[share" + comboBox1.SelectedItem + "] (LineNumber ,[Path] ,[Account] ,[Type] ,Directory_Owner ,Permission_Simple ,Apply_To ,Inherited ,Permissions_Advanced) VALUES (" + rowNumber.ToString() + ", '" +
                                                       lines[0].Replace("'", "") + "', '" + lines[1].Replace("'", "") + "', '" + lines[2].Replace("'", "") + "', '" + lines[3].Replace("'", "") + "', '" +
                                                       lines[4].Replace("'", "") + "', '" + lines[5].Replace("'", "") + "', '" + lines[6].Replace("'", "") + "', '" + lines[7].Replace("'", "") + "')";

                        SqlConnection conn = new SqlConnection(con_string);
                        conn.Open();
                            SqlCommand cmd = new SqlCommand(theQuery, conn);
                            cmd.ExecuteNonQuery();
                        conn.Close();

                        lineCount = 0;
                        lines.Clear();
                        break;
                    }
                }
                // =================================================================================
                // ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar

                if (x >= onePercent)
                {
                    //progressBarPercentage = (x / numbersCount) * 100.0;
                    progressBarPercentage = (100 * x) / numbers.Count;

                    label3.Visible = true;
                    label3.Text = progressBarPercentage.ToString() + "%";
                    label3.Refresh();

                    //progressBar1.Value = progressBarPercentage;
                    progressBar1.Value = (100 * x) / numbers.Count;
                    progressBar1.Refresh();
                }
                // ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar  ProgressBar
            }

            progressBarPercentage = 100;
            label3.Text = progressBarPercentage.ToString() + "%";
            label3.Refresh();

            //progressBar1.Value = progressBarPercentage;
            progressBar1.Value = progressBarPercentage;
            progressBar1.Refresh();

            MessageBox.Show("Done !");

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label3.Visible = false;
            string[] s = {"E","F","G","H","I"};
            comboBox1.DataSource = s;
        } //button
    }
}

How to input in DataGridView cell Only Double ...

$
0
0

Hi All ,
I want to input in DatagridView Cell , Only Double Like 2.36 or 0.035 .thanks to give any help !

RGDS!

Can someone explain this to me?

$
0
0

Hi I have some code, and what it outputs, but what I don't understand quite so clearly is how it gets those answers. 

If someone would be so kind as to explain what happens in the code to get what it writes (the how), it'd help me out a lot :)

Thanks!

int result = 0;

for (int a = 5; a > 1; a-=2) {

   for (int b = 1; a * b < 15; b++) {

        Console.WriteLine("a=" + a + " and b=" + b);

   }

}

Outputs:

a=5 and b=1

a=5 and b=2

a=3 and b=1

a=3 and b=2

a=3 and b=3

a=3 and b=4


DataTable DateTime column format error

$
0
0

We started having the following error out of sudden in 1 of our Production system. This happened in a Web Service hosted under IIS.

String was not recognized as a valid DateTime.Couldn't store <11/19/2016 23:44:22> in CMISUpdatedTime Column.  Expected type is DateTime.

  • This system was set up identical to another system with the same IIS and System Settings.
  • The windows Regional format was set to en-US and the IIS culture settings were set to the defaults.
  • The same application was deployed to both systems and the application was running without any issues until this morning where this error started occurring.

Below is the code where this error is occuring :

patientDataset.Tables["P_MED_GetPatientHeaderInfo"].Rows[0]["CMISUpdatedTime"] = strSplitParams[3];

This code was working without any issues until this morning 3:11 am where the error started appearing. The last successful hit of this method which was at 2:11 am didn't have any issues. The same code is also running in an identical system without any issues.

So far, we have investigated and done the below :

  1. Checked whether there are any changes in System or IIS settings (No changes found)
  2. Checked Event Log and found Application Pool was restarted at 2:16 am (Not sure whether this causes any issue?)
  3. Restarted the IIS (Error persists)

We are currently exploring the following options :

  1. Manually recycle the Application Pool
  2. Set the Culture for this Application in IIS Settings to en-US

The above options require permissions from the System Admin. So, we need to provide evidence whether the issue will be solved by doing them.

We are currently running out of ideas. Any suggestions for this scenario?


Can anybody tell whats wrong with the argument?

$
0
0

Here is the code and I am trying to get rid of the red squiggle line that is marked bold in the code text.Error, I really need help to put this error out of it's misery.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace ChatMessenger
{
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint epLocal, epRemote;
        byte[] buffer;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //set up socket
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //get user IP
            IP_tbx.Text = GetLocalIP();
            remIP_tbx.Text = GetLocalIP();
        }

        private void connect_btn_Click(object sender, EventArgs e)
        {
            //binding socket connection
            epLocal = new IPEndPoint(IPAddress.Parse(IP_tbx.Text), Convert.ToInt32(localPort_tbx.Text));
            sck.Bind(epLocal);
            //connect to the user remote IP
            epLocal = new IPEndPoint(IPAddress.Parse(remIP_tbx.Text), Convert.ToInt32(remPort_tbx.Text));
            sck.Connect(epRemote);
            //Listenign the specific port
            buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        }
        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                byte[] receivedData = new byte[1500];
                receivedData = (byte[])aResult.AsyncState;
                //Converts byte to string
                ASCIIEncoding aEncoding = new ASCIIEncoding();
                string receivedMessaage = aEncoding.GetString(receivedData);

                //Adding the bytes to the message box
                message_box.Items.Add("Friend: " + receivedMessaage);
                buffer = new byte[1500];
                sck.BeginReceive(buffer, 0,buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void send_btn_Click(object sender, EventArgs e)
        {
            //Convert string to byte
            ASCIIEncoding aEncoding = new ASCIIEncoding();
            byte[] sendingMessage = new byte[1500];
            sendingMessage = aEncoding.GetBytes(message_box.Text);
            //Sending the encoded message
            sck.Send(sendingMessage);
            //add to the list
            message_box.Items.Add("me: " + ChatBox_tbx.Text);
        }

        private string GetLocalIP()
        {

            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    return ip.ToString();
            }
            return  "127.0.0.1";
        }
    }
}



Need Help (again)

$
0
0

Hey guys Need some help with this C# assignment:

Create a project named RecentlyVisitedSites that contains a Form with a list of three LinkLabels that link to any three Web sites you choose. When a user clicks a LinkLabel, link to that site. When a user's mouse hovers over a LinkLabel, display a brief message that explains the site's purpose. After a user clicks a link, move the most recently selected link to the top of the list, and move the other two links down, making sure to retain the correct explanation with each link.

Here's the code of the GUI Form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCroftonRecentlyVisitedSites
{
    public partial class Form1 : Form
    {

        LinkLabel[] links = new LinkLabel[3];

        public Form1()
        {
            InitializeComponent();
            /*LinkLabel[] links = new LinkLabel[3];
            links[0] = new LinkLabel();
            links[0].Text = "google.com";
            links[0].Location = new System.Drawing.Point(100, 25);
            links[0].Links.Add(0, 0, "www.google.com");
            this.Controls.Add(links[0]);*/

            LinkLabel[] links = new LinkLabel[3];
            links[0] = googleLabel;
            links[1] = facebookLabel;
            links[2] = twitterLabel;
            Controls.Add(links[0]);
            Controls.Add(links[1]);
            Controls.Add(links[2]);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void googleLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", "http://www.google.com");
            links[0] = googleLabel;
            Controls.Remove(links[0]);
            Controls.Add(links[0]);
        }

        private void facebookLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", "http://www.facebook.com");
            links[0] = facebookLabel;
            Controls.Remove(links[0]);
            Controls.Add(links[0]);
        }

        private void twitterLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", "http://www.twitter.com");
            links[0] = twitterLabel;
            Controls.Remove(links[0]);
            Controls.Add(links[0]);
        }

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {
            Controls.Add(links[0]);
            Controls.Add(links[1]);
            Controls.Add(links[2]);
        }
    }
}

So far I got everything done. But I need help in moving the recently clicked link up top and the other two down when I click on it. Any help would be best.

Aasynchronous looping using Async Await

$
0
0

Hi All

I am trying to achieve asynchronous looping using async await. Below is my code block

static void Main(string[] args)
{
     var z = Enumerable.Range(1, 5000).ToList();
     z.ForEach(async (i) => { await displaynum(i); });
}

 public static async Task<bool> displaynum(int x)
 {

            Console.WriteLine("Before For : " + x);
            for (int y = x;y<x+5;y++)
            {
                Console.WriteLine("In DisplayNum : "+y);
                displayc(y);
                //await Task.Delay(1); I tried to use it for making the function call to asynchronous but it increases the execution time.

            }
            return true;
 }
 public static void displayc(int f)
 {
            Console.WriteLine("In Displayc : "+ f);
  }

From output I can see its running synchronously, how can I make it to run as asynchronous with Code change would be helpful.


 

what is factory design pattern

$
0
0
please help me to understand what is factory design pattern with example. thanks

Identify the reference in a function

$
0
0

Hi,

So Few days ago my friend asked me to help him in a project in C#, i admit i am not so good at it,
Never mind, i found a function that linked from a class to another class, it's difficult to explain it,
Allow me show you the code:

private RelayCommand _loginCommand;

public RelayCommand LoginCommand
        {
            get
            {
                RelayCommand arg;
                if ((arg = this._loginCommand) == null)
                {
                    arg = (this._loginCommand = new RelayCommand(new Action<object>(this.LoginCmd)));
                }
                return arg;
            }
        }

public void LoginCmd(object o)
        {
            try
            {
                string Name = NameBox.Text;
                string Pass = PassBox.Text;
                AuthorizeStatus authorizeStatus = this.Client.Channel.Authorize(Name, Pass);
                if (authorizeStatus != AuthorizeStatus.Ok)
                {
                    MessageBox.Show("Login Fail, " + authorizeStatus);
                }
                else
                {
                    MessageBox.Show("Login Success!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

RelayCommand is a Class as a CommandExecuter and has some other stuff inside it.

What i want is to call the LoginCmd function, how can i do that ?


I'm thankful for any help can be provide.

Trying to save image into a folder. ERROR: A GENERIC ERROR OCCURS IN GDI+

$
0
0
 

When I added if (System.IO.File.Exists(fileName)) to the method where SaveToFolder is called, the codes inside the method was totally skipped. I do not have to check System.IO.File.Exists(fileName) anyway.

private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
        {
            // Get new resolution
            Size imgSize = NewImageSize(img.Size, newSize);
            using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
            {
                using (MemoryStream MS = new MemoryStream())
                  {
                newImg.Save(Server.MapPath(pathToSave), img.RawFormat); //A GENERIC ERROR OCCURS IN GDI+
                    }
             }
        }
        public Size NewImageSize(Size imageSize, Size newSize)
        {
            Size finalSize;
            double tempval;
            if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
            {
                if (imageSize.Height > imageSize.Width)
                    tempval = newSize.Height / (imageSize.Height * 1.0);
                else
                    tempval = newSize.Width / (imageSize.Width * 1.0);
                finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
            }
            else
                finalSize = imageSize; // image is already small size
            return finalSize;
        }
    }

Viewing all 31927 articles
Browse latest View live


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