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

ShowInTaskbar casing broken named pipe

$
0
0

I have Winform_A connected to Winform_B via a named pipe owned and created by Winform_B. The problem arises when the following statement is added to the Winform_A Resize event:

private void WinformA_Resize( object sender, EventArgs e ) // triggered by minimize and restore
{
  ... 
  if ( WindowState == FormWindowState.Minimized )
    ShowInTaskbar = false;
  ...
}
This causes the named pipe to break with a "Pipe is broken" error. Is there another way for me to accomplish what I want without breaking the pipe? I need the program entry removed from the Windows taskbar dynamically. Thanks.




How to handle comma within string

$
0
0

Hello there,

I have csv file with the following information


i used the following code

using (FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.Read))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
   do
   {
      string line = sr.ReadLine();
      string[] vals = line.Split(',');
   }while (sr.Peek() != -1);
}

Using the above code, i got the following result, (which is this is not what i want)

vals[0] = Test_1

vals[1] = Test 2

vals[2] = t

vals[3] = est

vals[4] = 3

vals[5] = 10

I want the result as below

vals[0] = Test_1

vals[1] = Test 2

vals[2] = t,est,3

vals[3] = 10

The problem is the comma(,) within the string. How to solve this problem?

Thank you.






DataGridView not updating after DataTable applied sorted until a few mouse clicks are dropped

$
0
0

Hello all. It's time consuming dealing with this problem. No solutions. I have a DataGridView bound to a BindingSource and a DataTable (table). Col1 holds serial numbers 1,2,3.. etc. I changed row order by altering the values of Col1 through table.DefaultView. It worked well with table and the order was correct. But DataGridView didn't reflect the new order  I tried to force DataGridView1 to refresh by calling the following  but nothing worked:

bindingSource1.ResetBindings(false);

DataGridView1.DataSource = null;

DataGridView1.DataSource = bindingSource;

DataGridView1.Refresh();

DataGridView1.Focus();

this.Update();

Then I used the mouse to click different places in DataGridView1. DataGridView1 suddenly got refreshed and the order is correct.

So, who was behind the scene and got lazy not doing the updating job ?

How can make sure DataGridView1 refresh everytime. I cannot ask the users to do these clicks every time they finish ordering.

Thanks


Excel File Empty When Code Deployed to Server

$
0
0

Hi

An odd one. I have a C# web application (using .NET 4.7.1) which has a feature to download the data into an Excel spreadsheet. There is a template with all the headers in place, the code creates a temporary file, copies the contents from the template to that file and then populates it using ADO.

This process works without issue when deployed to the testing servers, and if I modify the web.config to point to the 'problem' connection, I get the download as expected (file size is ~5MB), but as soon as I deploy the code to the server, the resulting file is just an empty template. For the resulting download, none of the sheets (there are 12 of them) exceed 80 columns and all but one contain less than 4,000 rows, with that one being ~7,500 rows.

There is a similar process to extract filtered data, and this works without issue (using the same code) though this file is smaller (same number of sheets/columns as above but less rows - file size is ~4.7MB). 

I know it's not database permissions as have had traces applied and all the queries work and return data, so it's something about the resulting file and the web server.

Are there any limitations to ACE/OLEDB? The connection string used is:

$"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={exportFile};Extended Properties='Excel 12.0 xml;HDR=Yes'"

Where {exportFile} is a copy of the template held on the server whilst being populated.

The fact it works locally and on the test servers, plus for the smaller download, to me, proves that the code is sound, but there is just something about the larger export but I have no idea what it could be.

Are there any file size limitations using ACE/OLEDB?

Any help or advice gratefully received

Thanks

Martin

Explain about piece of code in C# - Random Numbers

$
0
0

Hello,

I would generate a sequence between 1 and 49, shuffle them and pick 6 number out of the sequence.

But could you please more explain about 

OrderBy(x => rnd.Next())

in

var rnd = new Random();
var randomNumbers = Enumerable.Range(1,49).OrderBy(x => rnd.Next()).Take(20).ToList();

I'm confused how this code works.  OrderBy(x => rnd.Next())

Thanks

c# Collection was modified. enumeration operation might not execute.

$
0
0

Below is sample code which throwing error called Collection was modified. enumeration operation might not execute.

am i getting this error because i use AsParallel ?

.AsParallel().WithDegreeOfParallelism(5)

string StandardValue = ""

StandardValue = dtFilterDataFromAllData.AsEnumerable().AsParallel().WithDegreeOfParallelism(noofththreads)
	.Where(w => w.Field<string>("BRTab") == BRTab&& w.Field<string>("RowNumber") == RowNumber&& w.Field<string>("StandardDate").Replace("A", "").Replace("E", "") == strPeriod.Replace("A", "").Replace("E", ""))
	.Select(v => v.Field<string>("StandardValue"))
	.FirstOrDefault();


if (StandardValue != null && StandardValue.ToString() != "")
                {
                    //update Standard Value after processing
                    StandardValue = ProcessValue(StandardValue ?? "", strUnits, false, TabName, StandardLineItem, strPeriod.Replace("A", string.Empty).Replace("E", string.Empty));

                    dtFilterDataFromAllData.AsEnumerable().Where(w => w.Field<string>("BRTab") == BRTab&& w.Field<string>("RowNumber") == RowNumber&& w.Field<string>("StandardDate").Replace("A", "").Replace("E", "") == strPeriod.Replace("A", "").Replace("E", ""))
                        .ForEach(w =>
                        {
                            //update parent StandardValue
                            w["StandardValue"] = StandardValue;
                        });
                    dtFilterDataFromAllData.AcceptChanges();
                }
can't i use .AsParallel in my above code ? thanks

How to convert Excel sheet to data table dynamically in simple way..

$
0
0

I want to convert excel to data table.

Input template

Output data table

Note : eliminate the first 9 rows from the input template for the output. for output data, we need to consider only from row no. 10



ShowInTaskbar causing broken named pipe

$
0
0

I have Winform_A connected to Winform_B via a named pipe owned and created by Winform_B. The problem arises when the following statement is added to the Winform_A Resize event:

private void WinformA_Resize( object sender, EventArgs e ) // triggered by minimize and restore
{
  ... 
  if ( WindowState == FormWindowState.Minimized )
    ShowInTaskbar = false;
  ...
}
This causes the named pipe to break with a "Pipe is broken" error. Is there another way for me to accomplish what I want without breaking the pipe? I need the program entry removed from the Windows taskbar dynamically. Thanks.





how to use dragon speech recognition sdk tools in to c#

$
0
0

hello everyone

 

I want to use the Dragon speech recognition SDK tools (without Dragon Bar) in c#. Can anybody tell me some tips regarding this. i also need some helpful article or e-books about this. 

 

 

. Getting error C2079: IDBConnection uses unknown class

$
0
0

I am porting an application from VC6 to VS2015. when I am building after including all the header files I am getting the following error

Error C2079 'IDBConnection' uses undefined class 'MIDBODBC::__MIDBODBC_EXPORT_MODE__'

I have included the header file.. but still I get this.

The class where IDBConnection is declared is like this:

namespace MIDBODBC
{
class __MIDBODBC_EXPORT_MODE__ IDBConnection : public CObject
{
protected :
 CDatabase* m_pDBPtr;
 CMIPLOG  m_pLog;
 int   m_nDBConnectionIndex;
 int   m_nDBPoolWorkerIndex;

.....

.....

}

Can someone pl suggest how to tackle this error

DTS Script task Runtime Error During ssis script task Execution

$
0
0

Hi all,

I'm trying to develop an ssis packages which includes for loop & script task in it. I'm trying to look at file file in folder using script task(C#) , if flat file is present in folder , should execute other task. If flat file is not present in folder the process should wait for some minutes and check the folder again for the file. For this i'm using Visual studio 2019, SQL server 2016 as target version, Microsoft Visual C#2015 in script task.

When i'm executing the package i'm getting below error message.

    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean                      constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[]                       arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[]                  parameters,CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target,                  Object[]providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

below is script code

#region Namespaces
using System;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Threading;
#endregion

namespace ST_c937e73bb1724a9bae78f2ac13d34ca3
{
	[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
	public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
	{     
        public void Main()
        {
            string FileLocation;
            string[] Files;
            Int32 DelayTimer;
            Int32 result;

            result = 1;
            DelayTimer = (Int32)Dts.Variables["User:: DelayTimerInMS"].Value;
            FileLocation = (string)Dts.Variables["User::FileFolder"].Value.ToString();
            Files = Directory.GetFiles(FileLocation);
            string filepath = Dts.Variables["User::FileFolder"].Value.ToString();
            if (
                File.Exists(filepath))
            {
                MessageBox.Show("Data File Name:" + Files[0].ToString());
                Dts.Variables["User:FileExist"].Value = true;
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            else
                Thread.Sleep(DelayTimer);

            Dts.TaskResult = (int)ScriptResults.Success;
        }

        #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

    }
}

Thanks

How can you compare 2 text files and only populate list key value pair with only the matching keys and values

$
0
0

ok i have 2 text files and they are diffent formats one is all on one line and one is in brakets examples below 

file 1 << the one that is the template one i want to match the other 2 

template

the file i want to compare againt ( so check the file above for all text to the left side if there is a match in the file below add the key and value to list key value pair ) 

file 2 

File to compare

so in the program i can add the value of the pair to template above im going to add to my program so as example 

i know both file contain DisplayName blahblah so when it finds that those 2 files share the name be something like this 

"displayName" "Nrg" 

say i name the list key value pair 

elfenlist so would want something like this 

displayName = elfenlied[displayName];

but not sure how to check files and get all occorences of the same names in both files

send file hyperlink

$
0
0

i have a document management software which reads the contents of the file and picks following information from the document for example order_no and saves the files with name order_no.pdf and stores it in a folder called https://myfolder/order_no.pdf , i need to send this path to oracle database field in a table where order_no is a column. Is ther a way to do it.

How to debug LINQ query in VS2013 or higher IDE

$
0
0

i often write LINQ to search data in list or data table and also do join between datatables. when those line execute then a inter loop occur i guess and we can not debug and check values in each iteration. so tell me how could i grab each iteration? what tools and technique available in VS2013 or Higher version of IDE which allow me to see each iteration.

when we set break point in for loop then we can see each iteration same way how to do the same for linq query? any way exist?

Ajax Control toolkit ComboBox - prevent from adding new item to the dropdownlist

$
0
0

Hi,

I set up Ajax Control toolkit ComboBoxes on a web form with DropDownStyle="DropDown" and AutoCompleteMode="Suggest". User is allowed to type in the input box, but if the input value does not match any of the existing list items, the new value will be appended to the list. How to stop the appending? The list items should not be modified.

Thanks ahead for your help!


How many maximum thread i can run in my pc

$
0
0
Environment.ProcessorCount return 8 but if i need to run say 50 thread then how do i know how many maximum thread i can run in my pc.

any way available to know it. thanks

If an exception is thrown inside a lock() {}, will the lock be released or not?

$
0
0

If an exception is thrown within a lock block is the lock released or not?

Example of a class wherein exceptions will easily be thrown while a lock is in effect:

namespace Utils
{
    public class ThreadSafeDictionary<TKey, TValue>
    {
        private object LockObj = new object();
        private Dictionary<TKey, TValue> Dic = new Dictionary<TKey, TValue>();

        public TValue this[TKey key] 
        { 
            get
            {
                TValue val = default(TValue);

                lock(LockObj)
                {
                    // What if an exception happens?
                    // Will LockObj be released?
                    val = Dic[key];
                }

                return val;
            }
            set
            {
                lock (LockObj)
                {
                    // What if an exception happens?
                    // Will LockObj be released?
                    Dic[key] = value;
                }
            }
        }
    }
}


Richard Lewis Haggard


Using a DataAdapter

$
0
0

Hi,
This i my first attempt to use a data adaptor. I want to load the data in to a datagridview,edit the data in the datagridview and then save it. This is what i have. The loading part works. the saving part not. (Give a warning: the object is not in the right state).

private string TableName = "GRN_EENHEID";
        private OracleDataAdapter OraDa;
        private DataSet DsEenheid = new DataSet();

        public void grn_eenheid()  //load the data
        {
            dataGridView1.DataMember = TableName;
                        
            // 1. instantiate a new DataSet
            DataSet dsEenheid = new DataSet();
            // 2. instantiate DataAdapter with select command and connection
            using (OracleDataAdapter da = new OracleDataAdapter("select CODE, NAAM from grn_eenheid", this.Conn))
            {               
                // 3.fill in insert, update, and delete commands
                OracleCommandBuilder cmdBldr = new OracleCommandBuilder(da);

                // 4. fill the dataset
                da.Fill(dsEenheid, TableName);

                DsEenheid = dsEenheid;
                OraDa = da;
            }

            dataGridView1.DataSource = dsEenheid;
        }

private void button7_Click(object sender, EventArgs e)  //save the data
        {
            OraDa.Update(DsEenheid, TableName);
        }

What is wrong?

Greatings, Hans

IEqualityComparer and GetHashCode in C#

$
0
0

Hello,

I should return the following code but How can write these? because we can return one of these.

return obj.Name.GetHashCode();

and

            return obj.Family.GetHashCode();

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace ConsoleApp2
{
    class CustomerNameComparer : IEqualityComparer<Customer>
    {
        public bool Equals(Customer x, Customer y)
        {
            return (x.Name == y.Name) && (x.Family == y.Family);
        }

        public int GetHashCode([DisallowNull] Customer obj)
        {
            return obj.GetHashCode();
        }
    }
}


Get Unique Ids from service and use it as batch

$
0
0

Hi,

I have  a requirement to get the unique ids

I do get it from a service as 1000 at a time. Example: GetIds(1000) - I get it from 1-1000. For next call GetIds(1000) I get it as 1001 to 2000

I want to user these 1000 Ids as a batch in my c# code once I reach to 999 I want to call GetIds to get my next bacth.

Create batch for 1000 everytime, use all ids and call the service after every 1000.

How can I do this as batch operation?

Viewing all 31927 articles
Browse latest View live


Latest Images

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