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

How to iterate in xml data using XmlDocument class

$
0
0

suppose my sample xml is 

<?xml version="1.0" encoding="utf-8"?><root><Folder><path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki</path><name>Tinkiiiii</name></Folder><Folder><path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki\New folder</path><name>New folder</name></Folder><Folder><path>C:\Users\bsushil\Documents\Sharpdesk Desktop\Tinki\New folder (1)</path><name>New folder (1)</name></Folder></root>

now tell me how could i iterate in xml data for path and name ?

i found few good sample url

https://social.msdn.microsoft.com/Forums/en-US/cf1b9d51-b1d3-49cd-b6b6-cad0c504d899/how-to-loop-through-certain-xml-nodes?forum=csharpgeneral
https://www.codeproject.com/Questions/1232542/How-to-iterate-XML-file-using-Csharp
https://answers.unity.com/questions/513582/how-to-iterate-through-every-node-in-xml.html
https://www.experts-exchange.com/questions/28897804/XML-Loop-through-nodes-via-C.html
https://forums.asp.net/t/2094931.aspx?Loop+through+XmlNodeList+with+C+
https://stackoverflow.com/questions/2915294/iterating-through-all-nodes-in-xml-file


Line break

$
0
0

How to make it keep going with the line breaks but will keep write :


Passing argument from user control's event to the parent Form

$
0
0

I want pass argument from user control's event from the parent form.

Here is the code snippet of the user control.

public class ConfigDeviceControlEventArgs : EventArgs
{
    private int m_selectedtabindex;
    public int SelectedTabIndex 
    {
        get { return m_selectedtabindex; }
        set { m_selectedtabindex = value; }
    }
}

public partial class ChildConfigDeviceControl : UserControl { public event EventHandler <ConfigDeviceControlEventArgs> TabControlDeviceSelectedIndexChanged; protected virtual void OnTabControlDeviceSelectedIndexChanged(ConfigDeviceControlEventArgs e) { EventHandler<ConfigDeviceControlEventArgs> handler = TabControlDeviceSelectedIndexChanged; if (handler != null) handler(this, e); } protected virtual void tabControlDevice_SelectedIndexChanged(object sender, ConfigDeviceControlEventArgs e) { e.SelectedTabIndex = tabControlDevice.SelectedIndex; OnTabControlDeviceSelectedIndexChanged(e); } . . .

And here is the parent form's code.

<Degigner>
this.tabControlDevice.SelectedIndexChanged += new System.EventHandler<ConfigDeviceControlEventArgs>(this.tabControlDevice_SelectedIndexChanged);<Form>
private void MyConfigDeviceControl1_TabControlDeviceSelectedIndexChanged(object sender, ConfigDeviceControlEventArgs e)
{
    int tabpage;
    tabpage = e.SelectedTabIndex;
}

However, an error occurs at Designer code's "this.tabControlDevice_SelectedIndexChanged" like following.

Cannot implicitly convert type 'System.EventHandler<ConfigDeviceControlEventArgs>' to 'System.EventHandler'.....	
Can anybody help me to fix this error?



string array's and byte array's

$
0
0

Hello All,

        I am re-submitting the link to my project.

I am trying to get the values of Multi- strings and Binary.

When I click on the entry of the section then in the values drop down list,

for a multi string, it should show (string[])value.

for a Binary, it should show (byte[])value

Registry Utility

Please check out the project.

it returns all values, except string [] and byte[]

need it fixed.

Thank you

data protector

$
0
0

I am studying the cryptography classes in .net and ran across data protectors (https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.dataprotector?view=netframework-4.7.2)

I get the concept of encryption algorithms but do not understand what is a data protector.  The microsoft documentation does not explain what it is and how it is different from the encryption algorithms.  

Disable a program in Windows through C# for a period of time.

$
0
0

Hello guys. I am having a school project in Windows Forms App and I have to make an app that ask the user to pick a period of time and then choose some apps. After this the program should lock this apps(they can't be opened or instead of opening them a message is shown with text like "The app you want to open is locked for .... time." for example). Any ideas how could i disable this apps and/or if they are open at the momment find them, kill them and disable them.

Thank you very much.

LINQ and Except

$
0
0

I'm using Except to select all records (call them delta records) in one file (today's) that were not in another file (yesterday's). These files always grow by zero or more records each day and records are never removed but some may change and some may get added.

The LINQ Except works fine however I also need to report the line number (in today's file) of each record we process from the delta records.

I do this simply by calling todays.IndexOf(record) which works but has a 60% CPU cost in the app I'm writing. The files contains upwards of 75,000 records (yet the delta records may be just 2,000 or so).

I tried creating a list of these record numbers once (at the same time I do theExcept) and then getting the record number is just a matter of looking up theIndexOf on the much smaller list (2000 or so). But the CPU went up because we're doing - overall - more work in total.

So I wanted to know is there anything like Except that can give me not just the records from A that are not in B but also the index of the record within A.

Thanks

c# TCP IP client and server no respond error

$
0
0

i have a simple TCP/IP client and server that does not work: i want to use it to transfer data between some clients and a server

on server side i have:

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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;

namespace TCP_IP_Server
{
    public partial class frmMain : Form
    {
        private ArrayList nSockets;
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
            lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
            nSockets = new ArrayList();
            Thread thdListner = new Thread(new ThreadStart(listnerThread));
        }

        public void listnerThread()
        {
            TcpListener tcpListener = new TcpListener(8080);
            tcpListener.Start();
            while(true)
            {
                Socket handlerSocket = tcpListener.AcceptSocket();
                if(handlerSocket.Connected)
                {
                    Control.CheckForIllegalCrossThreadCalls = false;
                    lbConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + " Connected.");
                    lock (this)
                    {
                        nSockets.Add(handlerSocket);
                    }
                    ThreadStart thdstHandler = new ThreadStart(handlerThread);
                    Thread thdHnadler = new Thread(thdstHandler);
                    thdHnadler.Start();
                }
            }
        }

        public void handlerThread()
        {
            Socket handlerSocket = (Socket)nSockets[nSockets.Count - 1];
            NetworkStream networkStream = new NetworkStream(handlerSocket);
            int thisRead = 0;
            int BlockSize = 1024;
            byte[] dataByte = new byte[BlockSize];
            lock (this)
            {
                Stream fileStream = File.OpenWrite(@"%userprofile%\desktop\SubmitedFile.txt");
                while(true)
                {
                    thisRead = networkStream.Read(dataByte, 0, BlockSize);
                    fileStream.Write(dataByte, 0, thisRead);
                    if (thisRead == 0)
                        break;
                }
                fileStream.Close();
            }
            lbConnections.Items.Add("File Written.");
            handlerSocket = null;
        }
    }
}

and on Clinet side:

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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace TCP_IP_Client
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            ofdBrowse.ShowDialog();
            txtFile.Text = ofdBrowse.FileName;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            Stream fileStream = File.OpenRead(txtFile.Text);
            byte[] fileBuffer = new byte[fileStream.Length];
            fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
            TcpClient tcp = new TcpClient(txtServer.Text, 8080);
            NetworkStream networkStream = tcp.GetStream();
            networkStream.Write(fileBuffer, 0, fileBuffer.GetLength(0));
            networkStream.Close();
        }
    }
}

i am running the server on a VPS that hase statick IP adress and the client on my own pc, but after hiting send button an exception occures:

"

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond **.**.**.**:8080"

Windows Runtime Components

$
0
0
Hi,
There is an idea that Windows Runtime Components can be used to encapsulate C++ code so that it can be naturally consumed from either C++ or C#. I love the idea, and I've wanted to try to re-write my C# game engine in that fashion for a while. I would get the benefit of C++ performance at the engine/renderer level, while working in C# for game code.

SharpDX is coming to an end because the project administrator doesn't have time to even correctly monitor submissions, as he's working on the Unity team now. So I have to consider changing to native DirectX or just giving up on software development, because I've invested so much time into C# but without a low level rendering technology, I'm not likely to keep making games.

But aside from the fact that I've found C++/WinRT WRC's actually impossible to make work because of it's fragility and just ridiculous design (The VS template doesn't even compile for example). I have found other serious issues with the WRC model that just make it not feasible as a solution at all for what I'm thinking of, or for anything come to think of it, these issues arise from all the rules for Windows Runtime Components ..
* Exporting unsealed types is not supported.
* Implementation inheritance is not allowed.
* Nested types cannot be exported to the Windows Runtime.
* Fields can be exposed only by structures.
* WinRT structs can contain only fields.
* Managed types cannot expose operator overloads.
etc

I've only just started trying to rewrite my C# engine as a C# WRC, I haven't even brought in a lot of the code and I'm looking at 2300+ errors. So I would have to almost completely rewrite my engine in this pseudo C#. I would expect the entire engine would require 10,000+ changes. And then it might turn out to not be usable because of the design restrictions or something I can't forsee.
And I should note that Microsoft are telling ppl that they can use WRC's to wrap Direct X in the way that SharpDX wraps it. I don't find that a useful suggestion, as even SharpDX can't be properly maintained by people with years and years of specialized experience. And also that it's inefficient to be calling individual calls as seen by SharpDX's reduced performance when compared with native Direct X.

I'd like anybody's opinion as whether I'm being overly cynical about Windows Runtime Components, or am I correct in realizing that it's mostly unusable. I've been really excited about the possibilites of it. But the difficulty and complexiy of rewriting ANY code as a Windows Runtime Component is beyond the capability of any independent game developer or even small team. It's just too much work just to experiment with something that might be broken by the design limitations of WRC's by the time you get 2 years in.

Build dynamic filter expression

$
0
0

Hi!

Could you help please,

I want to build lamda for filtering list of objects. I want to have builder that will accept list of fields and values and return lambda to use later to filter the list.

I've done the following:

 public class SurveyListFilterBuilder
    {
        public static Func<SurveysQueryResultItem, bool> Build(string[] searchField, string[] searchFieldValue, LogicalOperation operation)
        {
            Expression resultExpression = Expression.Constant(true);

            for (var i = 0; i < searchField.Length; i++)
            {
                var field = searchField[i];
                var fieldFilterExpression = GetFieldFilterExpression(field, searchFieldValue[i]);

                if (operation == LogicalOperation.And)
                    resultExpression = Expression.And(resultExpression, fieldFilterExpression);
                else if (operation == LogicalOperation.Or)
                    resultExpression = Expression.And(resultExpression, fieldFilterExpression);
            }

            return Expression.Lambda<Func<SurveysQueryResultItem, bool>>(resultExpression).Compile();
        }

        private static Expression<Func<MyClass, bool>> GetFieldFilterExpression(string field, string fieldValue)
        {
            switch (field)
            {
                case "name":
                    return x => x.Name.Contains(fieldValue);
                case "description":
                    return x => x.Name.Contains(fieldValue);
                    default:
                        throw new NotSupportedException();
            }
        }
    }

But it doesn't work because it seems I apply ADD operator bool expression and expression of Func:

The binary operator And is not defined for the types 'System.Boolean' and 'System.Func`2[ConsoleApp1.MyClass,System.Boolean]'.'

The question is how can I fix it and achieve correct result?



Alexander

Output file does not display extension even after using GetFiles method.

$
0
0

Hi a problem,

Output file does not display extension. Have to find correct program to reveal file extension. That is the problem. The problem I’m trying to solve is to write all renamed files with time and date to target folder with extensions.

I can’t figure out for the life of me how to output a file by its extension. I know I can use the GetFiles() method but I’m not too sure as how to output it. The problem I've got lies in the RenameFile method... I think?

public partial class Form1 : Form
    {
        static string[] _dropppedFiles;
        string _strSourcePath;
        string _strTargetPath;
        string _strfileName = string.Empty;
        string _strDestFile = string.Empty;

        public Form1()
        {
            InitializeComponent();
            readLabelMsg();
        }

        private string getFileName( string path)
        {
            return Path.GetFileName(path);
        }

        private string getDirectoryName(string path)
        {
            return Path.GetDirectoryName(path);
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            //TAKE dropped items and store in array.
            _dropppedFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            //LOOP through all droppped items and display them
            foreach (string file in _dropppedFiles)
            {
                lstDragDrop.Items.Add(file);
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
            {
                e.Effect = DragDropEffects.All;
            }
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            _strTargetPath = txtFolderPath.Text;
            RenameFile(_strTargetPath);
        }

        public void RenameFile(string targetDirectory)
        {
            //Get file regardless of specific extension.
            _dropppedFiles = Directory.GetFiles(targetDirectory);
            foreach(string file in _dropppedFiles)
            {
                if (!lstDragDrop.Items.Contains(_dropppedFiles.Length))
                {
                    _strSourcePath = getDirectoryName(file);
                    _strfileName = getFileName(file);
                   
                    //GET Creation Date and time from file.                    
                    _strfileName = File.GetCreationTime(file).ToString("yyyy'-'MM'-'dd hh'\u0589'mm'\u0589'ss tt", CultureInfo.InvariantCulture);
                    _strDestFile = Path.Combine(targetDirectory, _strfileName);
                    //Copy file with extension to output directory.
                    File.Copy(file, _strDestFile, true);
                }
                else
                {
                    Debug.WriteLine("Source path does not exist!");
                }
            }
        }
    }

storing asymmetric keys

$
0
0

I am studying .net crypto functions.  The following link (https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-store-asymmetric-keys-in-a-key-container) on storing asymmetric keys is a bit unclear.  I noticed that the GenKey_SaveInContainer and GetKeyFromContainer methods are identical.  Therefore how do you know if an asymmetric key already exists in the key container or if you just generated a new key?

 public static void GenKey_SaveInContainer(string ContainerName)  
    {  
        // Create the CspParameters object and set the key container   
        // name used to store the RSA key pair.  
        CspParameters cp = new CspParameters();  
        cp.KeyContainerName = ContainerName;  
        // Create a new instance of RSACryptoServiceProvider that accesses  
        // the key container MyKeyContainerName.  
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);  
        // Display the key information to the console.  
        Console.WriteLine("Key added to container: \n  {0}", rsa.ToXmlString(true));  
    }  
    public static void GetKeyFromContainer(string ContainerName)  
    {  
        // Create the CspParameters object and set the key container   
        // name used to store the RSA key pair.  
        CspParameters cp = new CspParameters();  
        cp.KeyContainerName = ContainerName;  
        // Create a new instance of RSACryptoServiceProvider that accesses  
        // the key container MyKeyContainerName.  
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);  
        // Display the key information to the console.  
        Console.WriteLine("Key retrieved from container : \n {0}", rsa.ToXmlString(true));  
    }  

Opening a web browser from c#

$
0
0

HI ,

I am using a below code to open ,  

I have a specific logic within my console application to open a web browser from my console application , and below is the way I coded in c# to open in a browser. 

Process.Start(new ProcessStartInfo("chrome.exe", "\"" + $@"http://testwebsite1/"));

But this will always opening in a new browser tab,what I wanted is without opening a new tab just use the existing tab ? 

how do we do this ? 

thanks 


XSLT transformation-split strings by considering nearest whole word

$
0
0
I am trying to achieve XSLT transformation with below rules while transforming 'Description' text. I have achieved the straight forward splitting of text into 35 characters strings but could not achieve below adjustments.

The free text 'Description' will be split among each of the 5 'Description' line text fields.
At most each field should accept 35 characters.
Ideally the free text string should be split on the nearest whole word or “,” to prevent a word being split over multiple lines.
However if the word is greater than 35 characters this will not be possible. The free text 'Description' will be truncated to a total of 175 characters (5*35).
Based on number of characters after above adjustment, output should be displayed as below

    <Description1>This is First Line Of Text With</Description1>
    <Description2>Large Word Added Here</Description2>

Please help me.Thanks in advance.

A. V. Sant

Send text and go to the next line

$
0
0

I am sending text to a ftp server and i want after sending the text it iwll go one line down all the time and i dont want to type every time "\r\n" text

"\r\n" + "\r\n" text

not like this


C# ReoGrid performance issue when binding datatable with formula

$
0
0

Here i am asking about 3rd party component but please do not avoid to answer. if possible see my code and tell me is there anything in my code which causing slow loading of data in ReoGrid. please read my explanation.

I have populated my data table with random values and formula like =SUM(A1:A2)when there is 150 columns and 4000 rows in datatable then ReoGrid taking approx 20 minute to be populated.

when i am populating ReoGrid without formula then it takes few second to populate ReoGrid but the moment many SUM formulas are being assigned to cell dynamically then ReoGrid take long time to populated.

Here i am sharing my code. so my request please guys see my code logic and tell me is there any flaw when assigning formula to many cell of ReoGrid.

please tell me how could i simplify the logic to populate grid with formula. Is there way to increase the performance of my code with formula as a result ReoGrid can be populated with in few sec or few minute.

Looking for suggestion and guide line. ReoGrid is free component for winform application https://reogrid.net/.


Here is my code
private void btnBindTable_Click(object sender, EventArgs e)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";

    int startsum = 0;
    int currow = 0;
    bool firstTimeSum = true;

    int NumRows = 4000;
    int NumColumns = 150;

    var sheet = reoGrd.CurrentWorksheet;
    sheet.Resize(NumRows, NumColumns);  // resize 

    DataTable dt = new DataTable();

    for (int col = 0; col < NumColumns; col++)
    {
        strColName = GenerateColumnText(col);
        DataColumn datacol = new DataColumn(strColName, typeof(string));
        dt.Columns.Add(datacol);
    }


    for (int row = 0; row < NumRows; row++)
    {
        dt.Rows.Add();

        for (int col = 0; col < NumColumns; col++)
        {
            if (row < 2)
            {
                dt.Rows[row][col] = new Random().Next(1, NumRows).ToString("D2"); 
            }
            else
            {
                if (firstTimeSum)
                {
                    if (row - currow == 2)
                    {
                        currow = row;
                        startsum = 0;
                        firstTimeSum = false;
                    }
                    else
                    {
                        startsum = 1;
                    }
                }
                else
                {
                    if (row - currow == 3)
                    {
                        currow = row;
                        startsum = 0;
                    }
                }


                if (startsum == 0)
                {
                    strColName = GenerateColumnText(col);
                    strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
                    strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
                    dt.Rows[row][col] = strSum; 

                    string cellname = GenerateColumnText(col) + (row + 1).ToString();
                    var cell = sheet.Cells[cellname];
                    cell.Style.BackColor = Color.LightGoldenrodYellow;
                }
                else
                {
                    dt.Rows[row][col] = new Random().Next(1, NumRows).ToString("D2"); 
                }
            }

        }

        startsum = 1;
    }

    sheet["A1"] = dt;

    stopwatch.Stop();
    TimeSpan timeSpan = stopwatch.Elapsed;

    MessageBox.Show(string.Format("Time elapsed: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds));

}

Thanks

Having issues with validation in an MVC application using .Net 4.6.1 and EF 6.0.0

$
0
0

Okay My application is using database first. I create my models from the existing database ... this is a temporal table



So I have three columns that are created by the database: RecipientKey, ValidFromTs, ValidToTs.  If there is any value in the field it states that I can't insert into a column that has "Generated Always" so I added the DatabaseGenerateAttribute to the model which fixed the issue but now I am getting validation errors.

Schema.ini and trim

$
0
0

Hello,

I am using a schema.ini to upload files to SQL server. I have some values that contain "spaces" at the begining or the end ( which i need to keep).

When i upload a csv or a txt using the schema.ini, i get trimmed values. When i am using an xlsx file and thus without the schema.ini i am getting the values with spaces ( as wanted ).

How can i stop the trim that schema.ini is making ?

Thank you for your time

Selecting contextual menu item in c#

$
0
0

Hello,

I want to write a program in C# which will select a menu item from a contextual menu.

How can I do this?

How to check my UWP app in iOT without any iOT device

$
0
0

Hi,

I have developed my UWP app. I need to ensure my app working fine with iOT or not. But I don't have any iOT device. I have another one laptop for testing. Please help me. I am using VS2017. 


Thanks, Muneesh.

Viewing all 31927 articles
Browse latest View live


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