[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More







C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Cannot send a content-body with this verb-type error in statement:
Regel 25:             using (Stream stream = requestObjGet.GetRequestStream())

Why Diversity in Tech Matters
LVL 12
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Why does this code return 2 and not 4?  The new keyword makes no difference except for a warning message when I remove it.
I could get 4 if I made the class A method virtual and the class B method an override.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
    public delegate void Foo();
    class Program
        static void Main(string[] args)
            A obj = new B();
        class A
            public  void Foo()
        class B : A
            public new void Foo()

Open in new window

I have a non-generic way of filling a grid with non-related items.

So, for example I have an entity called Stock and an entity called CustomerTypes

They are both IRepositories.

I have a third entity called StockPrice

This table is very simple – it has a StockId, CustomerTypeId, IsPrimary and StockPrice, Stockname, customertypename

The concept is based off the devexpress project available on github here:

In other words it is ripped and modified from there (The WinForms project)

I have attached a word document showing my code. I'm attempting to make something non-generic to generic but need a helping hand.question.docx
Hello all!

I have 15 combo boxes that are connected to an access db with the following code:

 public void Form1_Load(object sender, EventArgs e)
            //Create OleDB connection
                OleDbConnection connection = new OleDbConnection();
                connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sccalla\Desktop\accessdb.accdb;
                Persist Security Info=False;";
                //Select all information from TaskNames Table
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "Select * From TaskNames";
                command.CommandText = query;

                //Display Tasks in Comboboxes
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())

Open in new window

I have a c# application and need to run a stored procedure in local  postgresql database

Postgre 9.5.1 is installed on my PC  and

I have tried the stored procedure .  It works ( Its a simple select statement)

Below  are the following:

1. My connection  string
2.  Segment that  generated the error
3. Details of the error
4. Screen Print of where error occured using the Visual Studio Debugger

1. Connection String

<add name="Tournaments" connectionString="Server=(localhost:5432);Database=Tournaments;Integrated Security=true;Provider=PostgreSQL;" providerName="System.Data.OleDb.OleDbConnection"/>

2. Error on Output =  Line

public List<AbseCodeModel> getabsecode_all()
            List<AbseCodeModel> output;
            using (IDbConnection connection = new System.Data.OleDb.OleDbConnection(GlobalConfig.CnnString(db)))
                output = connection.Query<AbseCodeModel>("spgetabsecode_all").ToList();
            return output;

3. Detailed Error

  Message=Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
   at System.Data.OleDb.OleDbServicesWrapper.GetDataSource(OleDbConnectionString constr, DataSourceWrapper& datasrcWrapper)
   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection …
I have a text box, for user input. I read the user input,  and run a sql query in the back end , as such
select * from table where column like "%userinput%".

what should I do before including , the user input to the sql query , in order to prevent sql injection.

I am using C# and oracle database.
Hello all,

I cannot seem to find the answer that I am looking for so... I have a combo box with the DropDownStyle set to DropDown. I want users to be able to type and get the suggested options, but I do not want user's to type and leave a value that is not on the list. I have the SuggestAppend set for AutoComplete, but users can set the combo boxes text value to something that is not on the list.  Originally, I had the DropDownStyle set to DropDownList but the color change bothered me and all the solutions I found did not seem to let me change the BackColor. Can some please help me with getting the BackColor changed to "white" for a DropDownList  combo box or help me programically change the behavior of the combo box to not allow the value to equal something that is not on the list?

**Change the FlatStyle property to Popup is not an option.

Thank you for your assistance.

I have this webrequest looking like this:

 Public Sub SendFile(ByVal filename As String)
            coRequest = CType(WebRequest.Create(sURL), HttpWebRequest)
            coRequest.ProtocolVersion = TransferHttpVersion
            coRequest.Method = "POST"
            coRequest.ContentType = "multipart/form-data; boundary=" & BeginBoundary
            coRequest.Headers.Add("Cache-Control", "no-cache")
            coRequest.KeepAlive = True
            Dim strFields As String = GetFormfields()
            Dim strFileHdr As String = GetFileheader(filename)
            Dim strFileTlr As String = GetFiletrailer()
            Dim info As FileInfo = New FileInfo(filename)
            coRequest.ContentLength = strFields.Length + strFileHdr.Length + strFileTlr.Length + info.Length
            Dim io As System.IO.Stream
            io = GetStream()
            WriteString(io, strFields)
            WriteString(io, strFileHdr)
            Me.WriteFile(io, filename)
            WriteString(io, strFileTlr)
            coRequest = Nothing
        End Sub

Open in new window

The GetResponse sub looks like this:
Public Overridable Sub GetResponse()
            If coFileStream Is Nothing Then
                Dim stream As Stream
                Dim response As WebResponse

                    response = coRequest.GetResponse()
                Catch web As WebException
                    response = web.Response
                End Try

                If response IsNot Nothing Then
                    stream = response.GetResponseStream()
                    Dim sr As StreamReader = New StreamReader(stream)
                    Dim str As String
                    ResponseText.Length = 0

                    For Each str In sr.ReadLine

                    Throw New Exception("MultipartForm: Error retrieving server response")
                End If
            End If
        End Sub

Open in new window

The coRequest.ContentLength is 100507 and everything seems ok, but I get this error:
you must write contentlength bytes to the request stream before calling begin getresponse

Open in new window

I do the exact same in C#:

Open in new window

We have a site and it has a global search feature which is very very slow. It looks up 4 tables and does a wildcard.

This is how it looks like
select ....
 [dbo].[Unit] AS u
	LEFT join [dbo].[Schedule] AS s
    ON u.[ScheduleID] = s.[ID]
    LEFT OUTER JOIN [dbo].[MasterLease] AS m
        ON s.[MasterLeaseID] = m.[ID]
		INNER JOIN dbo.Portfolio p ON p.ID = m.PortfolioID
u.[Deleted] <> 1
          AND (1 <> s.[Status])
          AND (m.[Deleted] <> 1)
          AND (m.[Active] = 1)
          (s.[Sched] LIKE @searchtext)
          OR (u.[SerialNo] LIKE @searchtext)
          OR (u.[CustomerRef] LIKE @searchtext )
          OR (u.[Model] LIKE @searchtext )
          OR (u.[Manufacturer] LIKE @searchtext)
          OR (u.[SiteAddress] LIKE @searchtext )
          OR (m.[CustomerName] LIKE @searchtext )
          OR (s.[LesseeName] LIKE @searchtext )

Open in new window

1. My manager doesn't want to do a FullText Search
2. We have used indexes
3. The wildcard slows down the search, I think
4. If I join the 4 tables without the where clause, I get 2,827,623 rows. Should we dump this data in a table and just search this table? (update the table every night with fresh data)
5. Tried this as well... I broke down the joins by creating temp tables. First search Units, dumped in the temp table, #Units. Then Schedules in #Scheudles , then MasterLease in #ML.  Then did the join like I have above but what if there's nothing in #Units table...meaning...search didn't bring anything back from and #units is empty. I don't the join going to be correct.

I think #4 is a good option. How do others do a global search?

I have object called productbzAux  and it product type has value "A". I wanted to duplicate the same product with productType as "C" and add it to the same List object productCategoryBEList

My below code is updating the productType for parent and child object i.e., productbzAux  and productbzCore

Also, please advise the best way to write the below code.

The below code is in C#


List<ProductCategoryBE> productCategoryBEList = shoppingCartBE.ArrivalBooking.AvailableProducts;

            if (productCategoryBEList != null)
                ProductCategoryBE productCategoryAUXBE = productCategoryBEList.FirstOrDefault(p => p.CategoryCode.ToUpper().Contains("AUX"));
                ProductItem productbzAux = productCategoryAUXBE.Products.FirstOrDefault(t => t.SubCategoryCode.ToUpper().Contains("bz"));

                if (productbzAux != null)
                    List<ProductItem> products = productCategoryAUXBE.Products;
                    ProductItem productbzCore = new ProductItem();
                    productbzCore = productbzAux;
                    productbzCore.ProductType = "C"; // This is updating the ProductType of parent object i.e., productbzAux.ProductType where as it should be A for parent and C for child.

                    productCategoryAUXBE.Products = products;


Open in new window

Rowby Goren Makes an Impact on Screen and Online
LVL 12
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

I use Dapper in my C# application

My connection strings and the error displayed during run time are in the attached notepad document.

I am connecting to local postgresql installed on my PC

Why is providerName="Npgsql" not seen as the providername.

or is there a conflict some where ?

How can I resolve this error


How to loop through an Array in Java script where i am getting data from c# code as dictionary

private Dictionary<string, object> _dic = new Dictionary<string, object>();

        public Dictionary<string, object> dic
                return _dic;
            protected set
                _dic = value;
 public string MyDictionaryToJson()
            string jsonString = (new JavaScriptSerializer()).Serialize((object)_dic);
            return jsonString;
            //var entries = _dic.Select(d =>
            //    string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
            //return "{" + string.Join(",", entries) + "}";
        private static Random random = new Random();
        public static string RandomString(int length)
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        private DataTable BindData()

            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ColId", typeof(string));
            dataTable.Columns.Add("ColValue", typeof(string));

            for (int i = 0; i < 50000; i++)
                dataTable.Rows.Add(i.ToString(), RandomString(5));


Open in new window

Hello Folks,

I'm expanding my knowledge in learning classes in powershell... I have written this basic  PS example

class Books {

$books1 = [books]::new()
$books1.title = "Harry Potter"
$books1.author = "JK Rowling"
$books1.pages = 309

$books2 = [books]::new()
$books2.title = "Scott Pilgrim vs. the World"
$books2.author = "Bryan Lee O'Malley"
$books2.pages = 168

$books2 | ? {$_.title -like "*scott*"}

Open in new window

this will display the book from book 2 titled like "scott"...
Does anybody have any idea on how can I tell the program to search within all the books and find any "X" Title... I was thinking "foreach" but i'm not sure I could squeeze it in...? or if you have a c# approach that would be great also :)

Thanks in advance!
I'm following this example https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.1
to learn .Net Core.

I know LINQ to SQL is not supported in .Net Core. Is LINQ to Entities (LINQ to Entities ) supported? is my only option is to use Entity Framework?

(I really liked LINQ to SQL. Too bad it's not supported)
Hi Expert
I have added the web service to the Class Library file and created the DLL file.
so my issues are when I added to another project to this DLL file the web services classes method is can call from DLL file.
I need to hide the web service method from the new project. I need to allow only a few methods I have created.
How to do that.if any idea much appreciated.
Hello Experts,
I am trying to generate an output file using StreamWriter in C# which contains Credit Card (CC) numbers.  As long as the CC Number is 15 digits long, the StreamWriter works just fine.  But when the CC Number length is 16 digits long, the StreamWriter replaces the last digit with 0 (zero).  Any idea how to fix it?  Please try to help.

Thank you very much in advance!
I have legacy code in C#, Web Forms and LINQ to SQL.

I want to upgrade this code and I want to move the data layer to ASP.Net Web API. I found this link

I wanted to keep LINQ to SQL code (DBML) to make the upgrade go faster. Looks like LINQ to SQL is not supported in .Net Core.L2S not supported lin

What should I do? I have DBML, stored procs. How can I do my upgrade?
I pull data from a .CSV file that I dump into a multi-dim array.
I reformat array (into the final array) and then create an excel file and set all the column/row formatting.
In the final process, I dump parts of the array into structures columns.
I am using using Excel = Microsoft.Office.Interop.Excel;

The interaction with Excel seems to take longer than it should.

Using Interop to communicate with excel the most efficient/fastest way?

    int j = 2;
    oSheet.Range["A7:P" + rplUpdatedData.GetLength(0)].Borders.LineStyle = XlLineStyle.xlContinuous;
    for (int i = 7; i < rplUpdatedData.GetLength(0); i++)//i for Column index.

	oSheet.Cells[i, 1].value = rplUpdatedData[j, 0];
	oSheet.Cells[i, 2].value = rplUpdatedData[j, 3];
	oSheet.Cells[i, 3].value = rplUpdatedData[j, 4];
	oSheet.Cells[i, 4].value = rplUpdatedData[j, 15];
	oSheet.Cells[i, 5].value = rplUpdatedData[j, 24];
	oSheet.Cells[i, 6].value = rplUpdatedData[j, 6];
	oSheet.Cells[i, 7].value = rplUpdatedData[j, 26];
	oSheet.Cells[i, 8].value = rplUpdatedData[j, 8]; 
	oSheet.Cells[i, 9].value = rplUpdatedData[j, 28];
	oSheet.Cells[i, 10].value = rplUpdatedData[j, 30];
	oSheet.Cells[i, 11].value = rplUpdatedData[j, 12];
	oSheet.Cells[i, 13].value = rplUpdatedData[j, 26];
	oSheet.Cells[i, 14].value = rplUpdatedData[j, 16];
	oSheet.Cells[i, 15].value = rplUpdatedData[j, 1];
	oSheet.Cells[i, 16].value = rplUpdatedData[j, 2];


Open in new window

These two lines of vb6 code I am trying to translate to C#:

mskFromDate.Text = Format(Date - TimeSerial((iNumDaysBefore * 24), 0, 0), "Short Date")
    mskToDate.Text = Format(Date + TimeSerial((iNumDaysAfter * 24), 0, 0), "Short Date")

I have this so far. I know it is not right.

var dt = string.Empty;
                dt = Convert.ToString(DateTime.Now.ToOADate() - (NumDaysBefore * 24));
                this.dtFromDate.Text = Convert.ToDateTime(dt).ToShortDateString();

Anybody have thoughts? I can't believe in vb6 they let folks subtract dates and numbers.
Learn SQL Server Core 2016
LVL 12
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

I am using Microsoft.Extension.Logging.Log4Net.AspnetCore.
I want to separate default framework logoutput into a separate file from the logoutput that I program the application to output.

Is this possible, and how?
I saw this question on when to use multi tasking rather than multithreading.
When are tasks not going to work, so that we must use multi threading?
I'm using C# version 6 with Visual Studio 2017.
I have a batch file as below:
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat"
cd C:\AutomationTestSamples\AutomationTestSamples\bin\Debug
start cmd /k vstest.console.exe AutomationTestSamples.dll /Logger:trx;LogFileName=%1/UnitTest1.trx /testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1.trx

Open in new window

I want to read a batch file line by line and if the line contains "UnitTest1.trx",
I want to replace "/testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1" with "/test".

I tried the following code but when I opened the file nothing was replaced.  Any idea please?
string[] str = File.ReadAllLines(@"C:\Test\test.bat");
            for (int i = 0; i < str.Length; i++)
                if (str[i].Contains(trxName))
                    str[i].Replace(str[i].Substring(str[i].IndexOf("/testcasefilter")), "/test");                    

Open in new window

For some reason I cannot get the URI to locate a file.

Stream stream = Application.GetResourceStream(new Uri("D:\\MultipageDocument.pdf", UriKind.Relative)).Stream;

Here is where it bombs regardless of what I try to use; we have tried embedding into the app, use a drive letter, Relative, Absolute, nothing works.  We are getting "Cannot find resource" when it is truly there.

Stream stream = Application.GetResourceStream(new Uri("Viewer_PDF, PDF/MultipageDocument.pdf", UriKind.Relative)).Stream;

Any help would be greatly appreciated.
hi i try to use https://pdfium.patagames.com/c-pdf-library/

I found above api/pdf tool that using for (Search for a Text in a PDF File). and return x and y coordiate value.
and I bulit my own codes which is almost the same.

The return is always 0,0 which look like the search keywords feature does not work well.
And anyone try and tell me how your test about?

 public static Tuple<float,float> ExtractTextInfo(string keyword)
            //Initialize the SDK library
            //You have to call this function before you can call any PDF processing functions.
            //Open and load a PDF document from a file.
            float x = 0;
            float y = 0;
            using (var doc = Patagames.Pdf.Net.PdfDocument.Load(@"C:\Users\ry24234u.23423\Documents\Workspaces\RNsadfasd\AppStore\ApsdfpMot324orHomeS3423hares\document\rentalcontract.pdf"))
                //Enumerate pages
                foreach (var page in doc.Pages)
                   var found = page.Text.Find("This", FindFlags.MatchWholeWord, 0);
                   if (found == null)
                       return new Tuple<float, float>(0,0);
                        var textInfo = found.FoundText;
                        foreach (var rect in textInfo.Rects)

Open in new window

Hi All,
I have a C# DLL which was written for me to interface with my VB6 program.  The DLL is COM-Visible and the Register for COM interop selected.  The DLL has 3 methods Initialization, Up and Dn.

I have a small VB6 test program which access the DLL.

I'm using VS 2017 (run as administrator) to build the DLL
I have Visual Studio (VB6) on the same machine - A Windows 10 PRO system.

In my VB program I have a reference to the DLL (actually the TLB).  Intellesense works fine - I can see all three methods.
My startup code is:
Public Sub Main()
    Dim AM as AudioManager
    Set AM = New AudioManager       ' <<<==== Error here
End Sub

Open in new window

When I run the program I get an error at the Set statement - Runtime 429 - "ActiveX component can't create object".
I've done quite a bit of research on the web about this, and most of the similar issues are when someone tries to move a project from a development environment.  In my case , I'm getting this on the development system.
I have tried:
Tlbexp AM.DLL /out:AM.tlb
Regasm /tlb:AM.tlb AM.DLL
Gacutil /i AM.DLL
So far nothing seems to work.  I have put the DLL and TLB into the System32, SYSWOW64 and my VB6 application folders (registering it in each after removing from the previous location) - doesn't help.
Anyone have any ideas?
Thanks in advance






C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).