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

Bind DataTable To BindingSource

$
0
0

I am querying an access table and returning the data to a DataTable - I then want to bind that DataTable to a BindingSource, I see my rows in my DataTable look like this 

[0] = "Jorge"
[1] = "Active"
[2] = "Maine"
[3] = "Year 3"

and the DataTable is being populated like this:

string sqlQuery = "Select * from [Get Data];";

dataTable1 = //results of this query above

What I am unable to figure out is How would I bind the rows of the DataTable to fields using my binding source? This does not work, gives an error, but should illustrate my question

txtField1.DataBindings.Add("Text", _bs, [0]);


Can I storing over 100,000 files in a single folder without problems?

$
0
0

I have a database with about 6 "file" tables. These files are stored in a SQL Server column of type VARBINARY(MAX). To save or retrieve files the code uses a stream to get binary array either from a file to store in column, or from the column to write to file.

I need to remove these files from the database for many reasons. So I am wanting to store them in the file system on a Window 2016 server running IIS. The files will then be saved and retrieved via a web browser by the users so they can be accessed anywhere from a browser.

The file location required to retrieve the files will be stored in a table instead of the varbinary data. 

Am I going to run into any issues doing this? Either with C# or the windows file system itself?

How to Get Name Changes for Textbox to Change in the Code

$
0
0

I'm using C#, and I recall that in VB the code for the Textbox, referencing the name of the object, would change when I'd type in a name change for a textbox.  For example, it might originally read "textbox24", but I'd change that to "conductor" and the code would then reference "conductor".

Am I nuts?  Is that not how VB responded?  

I'd like C# to do the same thing, but it keeps the code it initially writes for the textbox as "textbox24" instead of changing it to the new name I've given the textbox (say, "cablesize").

How do you fix this, or is it not possible?

Read a file, remove line containing word 'bad', write the file to a new file.

$
0
0

I am reading a large text file to a list then searching for the line that contains the word 'bad'. How do I write the file without that line back to a new file?

Here is my code;

namespace ReadAndWriteFile
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> theWholeFile = File.ReadLines(@"C:\Users\Desktop\Current Projects\ReadAndWriteFile\ReadAndWriteFile\bin\Debug\01Aug.txt").Reverse().Take(5).ToList();
            foreach (string line in theWholeFile)
            {
                if ( line.Contains("bad"))
                {
                    theWholeFile.Remove(line);
                    File.WriteAllLines(@"C:\Users\Public\Success", theWholeFile.ToArray());
                }
            }
            Console.Read();
        }
    }
}



ManualResetEvent - AutoResetEvent

$
0
0
Hello,
what is the different between 'ManualResetEvent' and 'AutoResetEvent' ?
AutoResetEvent can be the Reset function?
   I think makes no sense?
   When do I initiate with 'true'?
public class AutoResetEventSample
{
	private ManualResetEvent manualReset = new ManualResetEvent(false);

	public void RunAll()
	{
		new Thread(Worker1).Start();
		new Thread(Worker2).Start();	
		manualReset.Set();
		Thread.Sleep(1000);
		manualReset.Reset();
	}

public class AutoResetEventSample
{
	private AutoResetEvent autoReset = new AutoResetEvent(false);

	public void RunAll()
	{
		new Thread(Worker1).Start();
		new Thread(Worker2).Start();
		autoReset.Set();
		Thread.Sleep(1000);
		autoReset.Set();
	}
For my understanding.

AutoResetEvent only Set and WaitOne(1000) // wait 1000ms, then timeout exception
     If I call Set, is automatically low Level, is a trigger-and-wait-maximum-time
 auto
ManualResetEvent Set, Reset and WaitOne(1000) // wait 1000ms, then time outexception
     If I call Set, is 1 until I call Reset, is a signal edge that is 1 until reset. 
  manu
Do I have to pay attention, if I have one thread, callback version or if I have multiple threads?

With best regards Markus


How to write code inside Parallel.ForEach Loop

$
0
0

This is my pseudo code of Parallel.ForEach where i am assigning data and incrementing data, assign data to cell using EPPlus libraray. so please guide me how to write code inside Parallel.ForEach loop as a no dead lock should appear or no weird scenario should occur because multiple thread will try to execute each line at same time. please see my code and guide me how to write it inside Parallel.ForEach loop. thanks

 Parallel.ForEach(OrderWiseLineItem, data =>
 {
string section = data.Section;
string li = data.Lineitem;
string broker = data.Broker;

int rowNumber1 = -1;
int coutstdformula = 0;
string columnheader = GetExcelColumnName(columnIndex + 1);

if (dataresult.AvgComment.Trim() != string.Empty)
{
worksheet.Cells[rownumber + 1, columnInde5Q + 2].AddComment(dataresult.AvgComment.Replace("##",(dataresult.HistoryValue.Trim()!="" ? dataresult.HistoryValue : dataresult.StandardValue)), "Cell Comments");
}

rowNumber1++
});

How to increment by 5 using Interlocked.Increment

$
0
0
i saw Interlocked.Increment. does it always increment by 1 ? what to change as a result Interlocked.Increment does the increment by 5 or 10 ?

Wrongful acces database insertion

$
0
0

I'm having trouble with inserting information in a database, i'm working on a project where i need to be able to store the location of trainwagons in a database. Each column stands for a different track but when i insert a train in column the next one i insert in a different column will be in the next row and this can't happen, they need to be able to be in the same column. I will also post my insert code that i wrote in c#. So my question is, does anybody know how i can fix this ?.

Kind regards Arno.

ps. I wasn't able to put in the picture because my account isn't verified. I hope it's clear enough.

static void Insert(string data,string spoor) // Insert wagons in the database { OleDbConnection connection = new OleDbConnection(); connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Arno\Documents\Code\Visual Studio\Database_GIP20161.accdb; Persist Security Info=False;"; connection.Open(); string query = String.Format(@"INSERT INTO Posities({0}) VALUES ('{1}');", spoor, data); OleDbCommand command = new OleDbCommand(); command.Connection = connection; command.CommandText = query; command.ExecuteNonQuery(); connection.Close(); }


Test error in Visual Studio 2017

$
0
0

I am getting an error when I try to run a test.  The solution builds but gets the following error when I try to run the test:

System.MissingMethodException: Method not found: 'Int32 Int32 DataAccessMVC.Interfaces.IDb2DataAccessWrapper.ExecuteNonQuery(System.String, System.String, System.Collections.Generic.IEnumerable`1<IBM.Data.DB2.DB2Parameter>, System.String)'.

IDb2DataAccessWrapper is a method that was added.  Can you help me?

Why is copying 10 items to an observable collection so slow and how to speed up?

$
0
0

This code operates in a .NET WPF C# environment. The basic code creates a collection of about 10 objects. The collection is sorted and then copied. When the copy happens the time to execute adds an astonishing 7 seconds. The observable collection does not have any subscribers at this point so one would not expect any time to be lost due to broadcast change notifications.

The application is based on a WinForm used to create a System Tray Notification item. When the tray icon is clicked upon a WPF window is shown. At the time that the WPF window becomes visible a DispatcherTimer is created and started. A short delay after that and a web service call is made which collects information which is written into userItems, a local variable. This collection will be passed back to the caller who will put it into a class property that will be bound to the source for a ComboBox. This code works well and fast. There is a problem with it, however, in that the contents of the ComboBox drop down list are not sorted. I thought that it would be trivial to handle that by sorting the contents of the userItems before it is passed back to the caller. Not so, sneaker breath. Here's the important part of the code:

// A local variable is declared.
ObservableCollection<UserItem> userItems = null;

// Snipped from the code is the initial population of userItems.

// A sorted copy of userItems is created. This is quick.
List<UserItem> lui = userItems.OrderBy( a => a.user_id ).ToList();

// The original collection is emptied so that it can be populated with the
// sorted elements.
userItems.Clear();

// The sorted list of items, only about 10 objects, is copied back to userItems.
// This is where the time is being spent, an astonishing 7 seconds to copy 10 items.
// If the copy is commented out then the code runs in almost no time at all.
for (int x = 0; x < lui.Count; x++)    userItems.Add( lui[x] );

Any ideas why the above code fragment runs so slowly and how can I speed it up?


Richard Lewis Haggard


C# How would i get the Mouse Coordinates?

$
0
0

Hello, i'm currently working on a auto clicker which captures Cps. (Clicks per second.)

How Would i make a form transparent which would record the X, Y,  Mouse Position coordinates in a text-box.

Thanks!

ShellExplorerAPI.SHGetFileInfo() is displaying "?????" for other language folders.

$
0
0

I use "SHGetFileInfo()" and the structure "SHFILEINFO" to get the name of the folders and drives which present in windows operating system.

If a localized operating system to change the setting "Current language for non-Unicode programs", these functions return a value "??? ?????????" for Japanese language folders.this is my reference code to get the file name.

   [DllImport("shell32.dll")]
     public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribs, out SHFILEINFO psfi, uint cbFileInfo, SHGFI uFlags);

public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        public string DisplayName
        {
            get { return m_strDisplayName; }
            set { m_strDisplayName = value; }
        }

 For getting file path File path, I'm using below constructor to call every time to get path . but "shInfo.szDisplayName"  isreturn a value "??? ?????????" instead of Japanese folder name in En-Us Operating system.

  public ShellItem()
   {
             DisplayName = shInfo.szDisplayName;  /////This is one used to get the file path
           
    }

      Find the below image to show the application folder name with respect to windows explorer.  Please help me on this                                                                                                                                                                                    




VS2017 SSIS Script Task losing changes to Framework

$
0
0

The Script Task within my SSIS package defaults to .NET Framework v4.5. I'm trying to use v4.5.2 in order to use the newer version of MySQL.Data from NuGet. I go into the Script Task properties and change the framework from v4.5 to v4.5.2, add the MySQL.Data NuGet package, and then save all changes. If I then close the script editor and return to the package designer, and then re-open the script, the .NET Framework for the script reverts back to v4.5 and the references to the MySQL.Data packages are lost. This is occurring in VS2017 on Windows 10.

What is causing the script files to be regenerated each time? How do I disable this from happening?

On a side note, if I attempt to test the package I get a random error saying UnsafeInvokeInternal. I can't determine why this is happening as the script is only attempting to open and close a connection to the MySQL database.


Resuming download in C# WPF

$
0
0

Hi Everyone,

I’m developing a WPF application which downloads some MSI files which are greater than 100 MB. While downloading, if the internet is disconnected, the currently downloading file has to resume from where the download was interrupted. I used the WebClient and Cookies for downloading the files. The files are not resumed if the internet was disconnected and connected again.

using (CookieAwareWebClient client = new CookieAwareWebClient())
{
        client.DownloadProgressChanged += WebClientDownloadProgressChanged;
   client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);      
  client.DownloadFileAsync(url, fileName);
 }

static void WebClientDownloadProgressChanged(object sender, 
DownloadProgressChangedEventArgs e)
    {
        Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);      

    }

    static void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        Console.WriteLine("Download finished!");
    }       

}

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}

I have also tried the below code using webRequest.AddRange. It doesn't work for me. Consider 10 MB file has to be downloaded. If 5 MB of file was downloaded and while downloading again, calling the GetWebrequest method initializes the file size to zero and webRequest.AddRange downloads the remaining file. i.e AddRange downloads the remaining 5 MB file. So, only 5MB file will be downloaded as the first downloaded 5 MB was initialized to zero in calling GetWebrequest method.

public class WebclientEx:WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest webRequest = base.GetWebRequest(address) as HttpWebRequest;
            if (downloadedsize> 0L)
                webRequest.AddRange((int)downloadedsize);
            return (WebRequest)webRequest;
        }

    }

Can anyone provide suggestion for resuming the file download?

Thanks,

Manivannan S. 

timer not tick-ing

$
0
0

I have an .Tick timer event enabled in my mainform but while much-much work is going on during load up time its .Tick event is not happening(probably because the app is so busy elsewhere) can I make my work pause long enough for the timer event to kick in? Or is there something else I need to do?

BadButBit


my code is perfect until i don't find a bug


Windows task scheduler wont write to SQL database from C# console app

$
0
0
Hello

This is something ive never done before so i apologise if this is a silly question.

I have a c# console app which when ran locally it works perfectly. However, when I try and run it from task scheduler part of it runs but it wont write to the SQL database.

My folder has permissions to read and write. Also the task is running as administrator and with the highest privileges. When I check the task history it says its complete with no errors.

Any help would be appreciated 

Thanks

Printing XPS documents limited to 64 characters for the description?

$
0
0

Hi,

my application is printing XPS documents, and whatever I set the job description to, if its over 64 characters, it gets truncated to be 64 characters.

I've tried printing in numerous different ways, but they all boil down to the same issue.

System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
printDialog.ShowDialog();
XpsDocument xpsDoc = new XpsDocument(textBox1.Text, System.IO.FileAccess.Read);
var docName = "A document name that is longer than 64 characters cuts off here and doesnt display the rest";
printDialog.PrintDocument(xpsDoc.GetFixedDocumentSequence().DocumentPaginator, docName);

The print job will be shown in the queue as "A document name that is longer than 64 characters cuts off here"

Is this a known bug? Is there any work around?

Thanks,

Chris

how to find the min and the max and its position without using math+ while using while

$
0
0

I wrote

using System;
class MainClass
{
publicstaticvoid Main (string[] args)
{
int max=0,min=0,minp=0,maxp=0,num;
Console.Write("give me a positive number: ");
num=int.Parse(Console.ReadLine());
while(num!=0)
{
if(num!=0)
{
if(max<num)
{
max=num;
maxp++;
}
if(min>num)
{
min=num;
minp++;
}
Console.Write("give me a positive number: ");
num=int.Parse(Console.ReadLine());
}
}
Console.WriteLine("the Max is: {0} and his position is:{1}",max,maxp);
Console.WriteLine("the Min is: {0} and his position is: {1}",min,minp);
}

}

and the result was when I entered:

2,4,6,9,0

The Max is : 9 and his position is : 4

The Min is : 0 and his position is : 0

how to make it right?..


How to get a part of text selection of pdf file on axAcroPDF control and put it into Clipboard.SetText(the selected)

$
0
0

I read through most of Youtube content and a week search into Google.

I failed to set the Clipboard to the selected texts from axAcroPDF control.

Problem: The document part of Adobe Reader DC has the same class to other multiple children.

              Namely, it doesn't have a unique class name, but a unique caption.

Approach 1 : EnumWindows    ---> Its use shall be made by the unique Caption Name, not common class name.

Approach 2: Similarly to My.Computer.Clipboard, we should use master window handle detection.

                   Even in this case, there's the problem of the multiple same classed children with a unique caption name.

Approach 3: Is there any way of getting some selected texts using iTextSharp? In my opinion, it has no such property or method.

Searching in 3d arrays using Linq

$
0
0

Hello I have such model:

public enum MainKeys
{
A,B,C,D,E,F
}


public enum SecondKeys
{
Q,W,E,R,T,Y
}

public static ConcurrentDictionary<MainKeys,Model2> PrimaryList = new ConcurrentDictionary<MainKeys,Model2>();

public class Model1
{
  public string Name{get;set;};

  public ConcurrentDictionary<int,Model2> SecondLevelList = new ConcurrentDictionary<int,Model2>();
}

public class Model1
{
  public string SubName {get;set;};

  public ConcurrentDictionary<SecondKeys,Model3> SecondLevelList = new ConcurrentDictionary<SecondKeys,Model3>();
}

public class Model3
{
  public TextBlock TextInstance {get;set;} = null;
}

Now I need to search if anyone has TextInstance not null.

public void start(MainKeys mk, SecondKeys sk) {

if(PrimaryList[mk].SecondLevelList.Any(st => st.SecondKeys[sk].TextInstance != null) == true)

{

Debug.WriteLine("found");

}

else

{Debug.WriteLine("notfound");

}

}

Problem is it always fails, what I'm missing here? It fails with any, FirstOrDefault, does that mean it fails to search in int type concurentdictionaty, how can I solve it?

Viewing all 31927 articles
Browse latest View live


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