C#

93K

Solutions

25K

Contributors

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

I have a c#  application which needs to write into sqlserver  and postgresql  databases.

I  use Dapper  ORM

I have been able to specify my connection string   for sqlserver  and it works

Now i am trying to specify  the equivalent  for  PostgreSQL  and I am getting the

Error   " OLE DB Provider  not Specified in the Connection String "

I have tried the following 3  providers

providerName="Npgsql2" />
providerName="Npgsql" />
providerName="SQLOLEDB" />

with same error message

Whats should be my provider string  for a c# application  connection to a

PostgreSQL database  using Dapper

Please Note that  I have Dapper  and   Npgsql installed in my application using Nuget

Attached please find error screen using the debugger and my connection string PostgreSQL

I will be grateful for an assistance

O.A.  Oluwole
OLE-DB-PROVIDER--24-09-2018.docx
0
Microsoft Azure 2017
LVL 12
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

I'm reviewing this junior developer's code and he's used Session. I think there's a better way of doing this and not use Session. I also read somewhere, a while back, not to use Session.

He doesn't clear the session.

  if (search.Schedule.Invoices.Any())
            {
                Session["leaseSched"] = search.Schedule.LeaseNoSchedule;
            }

and then in a link

<div class="btn-group pull-right">
    <h5>@Display <a href="@Url.Action("Detail", "Schedule", new { @id = Model.ScheduleID })">@Session["leaseSched"].ToString()</a></h5>
</div>

Any arguments against using Session in MVC?
0
I'm running into this error message when I'm calling this following method...

Argument Exception “Item with Same Key has already been added”

        public static Dictionary<string, int> GetOrdinals(this SqlDataReader reader)
        {
            Dictionary<string,int> returnDictionary = new Dictionary<string, int>();

           

            for (int i = 0; i < reader.FieldCount; i++)
            {
                returnDictionary.Add(reader.GetName(i).Trim().ToUpper(), i);
            }
            return returnDictionary;
        }

Open in new window



I was trying to write the following logic but I do get lost...

    if (returnDictionary.ContainsKey(....) then don't add it....


I changed my logic as follow:


            Dictionary<string,int> returnDictionary = new Dictionary<string, int>();

           

            for (int i = 0; i < reader.FieldCount; i++)
            {

                if (!returnDictionary.ContainsKey(reader.GetName(i).Trim().ToUpper()))
                {
                    returnDictionary.Add(reader.GetName(i).Trim().ToUpper(), i);
                }
               
                   
            }
            return returnDictionary;
0
Hello,
There are 2 COM interfaces whose implementation is proprietary

I need to create a COM object (either in C++ or C# com server) and invoke it to use their functions from a c# client console application

How should i approach the task?

Thank you
0
I'm currently getting a list of all access points available using:

            IEnumerable<AccessPoint> accessPoints = wifi.GetAccessPoints();
            // for each access point from list
            foreach (AccessPoint ap in accessPoints)
            {
                //check if SSID is desired
                if (ap.Name.StartsWith("MY-SOCIAL"))
                {
                   
                  //get IP here

                }
            }

Open in new window


Is there a way to get an IP address of the AP?

I'm not married to do it this way, I just need to find a way to match up an AP name with the correlating IP address. Any ideas?
0
I have 2 tables

Groups
GroupLogs

On first load of webpage I need to just pick the firstordefault group, and load all LOGS for that GROUP

here is the query i have so far
     var _getHistoricalData = (
                    from pGroup in _mme.t_Groups
                    join pLog in _mme.t_GroupLog on pGroup.Group_ID equals pLog.fk_Groups_Id
                   where (pLog.LogTimeStamp < DateTime.Now.AddDays(-7))

Open in new window


This returns all groups and all logs
How would i select the first Group and its logs only?
0
In c#,
let us consider a character arrays of "c" and "d".
I need to convert this character arrays into string. obvisouly we had many ways to convert it into string from char array.
Here, Iam performing char array into string is
string e=c.ToString();,string f=d.ToString();
Iam getting output which is different when i write string e=new string(c);,string f=new string(d);  
 please let me know what is the difference between
1. string f=new string(d);  
2 .string f=d.ToString();
thanks in advance
0
I built a wpf application for a screen resolution of 1920*1080 ...
however the user will sometimes use a resolution 3810*2160.
How to i make my application so it keeps its aspect ratio in a way that if in a screen resolution of 1920*1080  occupies 80% of screen then in a screen resolution of 3840*2160 it also occupies 80% of screen.
I will be looking into font sizes and all that stuff too... but at least for now I need that the grids, windows and controls all resize accordingly.

Regards.
0
I need to refresh a serial port connection in case it randomly closes. I seem to only be able to refresh it if I refresh my WPF application.
I have two questions.
1.)Using c# code how do i refresh a wpf application? something like this.Refresh() in windows forms.
2.) using c# code how do I refresh a serial port connection?

regards.
0
Need a Windows Forms User Interface to enable OCR User Error Checking

I am in the process of writing a Windows Forms application (in C#) that will use an external OCR module to perform OCR on a PDF containing scanned financial documents. So, I expect there to be errors. But, I want to provide the scanned results to the user in a format where the results can be cross-checked by the user.

Clearly, typing over with the corrected value is key.

What is the easiest way to do this in a Windows Forms program?

Various forms will have different values, so I want this as generic as possible.

Shall I just display the whole block of data as a multi-line text input field?

Any other ideas?

Thanks
0
Become a Certified Penetration Testing Engineer
LVL 12
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Getting Input String Was not in a correct Format
.Actually I had written a method in webservice as method name as caculator
 [WebMethod]
   public int caculator(int firstNumber,int secondNumber,string operation)
    {
        int result = 0;
        switch(operation)
        {
            case "+": result = firstNumber + secondNumber;
                break;
            case "-": result = firstNumber - secondNumber;
                break;
            case "*": result = firstNumber * secondNumber;
                break;
            case "/":result = firstNumber / secondNumber;
                break;
        }
        return result;
    }
and Iam consuming this in webapplication where I have written as
private void BindData()
        {
            string operation = txtOperation.Text;
            WebService1 objWebService = new WebService1();
            int result=objWebService.caculator(int.Parse(txtFirstNumber.Text), int.Parse(txtSecondNumber.Text), operation);
            if (result != 0)
                Response.Write(result);
        }
 in this iam getting error at this line
int result=objWebService.caculator(int.Parse(txtFirstNumber.Text), int.Parse(txtSecondNumber.Text), operation);

i doesn't understand why iam getting error here. Even though i converted it into string
could you please suggest as soon as possible
0
Hi,

I want to do order by in linq
if SortOrder is null then sorder by name in asecding order
If SortOrder is there then order by SortOrder.

Please advise how to set order by in my below query.
In below Query I am setting error at el.Element("SortOrder").Value as null object.

Error Below:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XContainer.Element(...) returned null.


even getting above error in
el.Element("Name").Value

XElement xml = XElement.Load(Server.MapPath(ConstantKeys.CountryCurrencyFilePath));
            IEnumerable<XElement> titleElements = from el in xml.Elements(elementName)
                                                  orderby el.Element("SortOrder").Value ascending, el.Element("Name").Value ascending
                                                  select el;

Open in new window



Sample XML below. You can see SortOrder element is available for AUD and AZN. But it is not available for others.
Please advise us on the query.

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Row>
    <Code>AFN</Code>
    <Name>Afghani</Name>
  </Row>
  <Row>
    <Code>AOA</Code>
    <Name>Kwanza</Name>
  </Row>
  <Row>
    <Code>ARS</Code>
    <Name>Argentine Peso</Name>
  </Row>
  <Row>
    <Code>AUD</Code>
    <Name>Australian Dollar</Name>
    <SortOrder>1</SortOrder>
  </Row>
  <Row>
    <Code>AZM</Code>
    <Name>Azerbaijan Manat</Name>
  </Row>
  <Row>
    <Code>AZN</Code>
    <Name>New Azerbaijan Manat</Name>
    <SortOrder>2</SortOrder>
  </Row>
</Root>

Open in new window


Regards,
0
I have a series of Comboboxes (ComboBox1 to 10) and I need to enable a button called "System Reset" if ANY of them has SelectedIndex <> 0 (in other words, if any combobox selected value is not the first one - if all of them have the first value selected then button should be disabled, otherwise enabled).

Is there any way to do this elegantly or should I check each and every Combobox change event and, if not the very first item selected then enable the Reset button ?

Thank you very much
0
I am trying to figure out a way to implement on a WCF Service that is version agnostic basically.

[DataContract]


public class TestResponse
{

    [DataMember]
    public string StudentNo {get; set} 

    [DataMember}
   pubiic ClassVersion VersionOfClass [get; set;]

}

[DataContract Name="Class A"]
public class TestClass
{
      [DataMember]
      public string Tools {get; set;}

      [DataMember] 
      public string Name {get; set;}

}


[DataContract Name="Class B"]
public class TestClass
{
      [DataMember]
      public string LocationType {get; set;}
      [DataMember]
      public string Name {get; set;}
      [DataMember]
      public int NailDepth {get; set;}

}

Open in new window



Now, I want to be able to use that TestResponse and the ClassVersion object be for the ClassA or ClassB.


Is that possible to be done if is go how? I don't think a Generic would work. Would a typeof?


Any information on this would be greatly appreciated.


Thanks!
0
Hello Experts,

I'm using asp.net 4.0 charts(ChartType: Bubble). I have X-axis shows States (values like AL, FL, NY,...) and Y-Axis is a Date(01/01/2018,02/01/2018,..) The date range on the Y-axis is from 01/01/2018 to 12/31/2018. One of the X-axis has two Y-Values. For instance NY has 01/01/2010,03/01/2018, I cannot show two DataPoints for 1 X-Axis item. I  tried this and still not working
series.CustomProperties = "IsXAxisQuantitative=True";
 DataPoint dp = new DataPoint();

dp = new DataPoint(i, val);
dp.SetValueY("01/01/2018");
dp.XValue = chart.Series["DateSeries"].Points.Count() * 2;
 dp.ToolTip = "First Date - 01/01/2018";
 chart.Series["DateSeries"].Points.Add(dp); 

dp.SetValueY("03/01/2018");
dp.XValue = chart.Series["DateSeries"].Points.Count() * 2;
 dp.ToolTip = "Second Date - 03/01/2018";
 chart.Series["DateSeries"].Points.Add(dp); 

Open in new window


The above code show only the tooltip twice ( the last one it got set i.e. Second Date - 03/01/2018), but not the two datapoints on Y axis. What I'm missing, please help.

Thanks,
ASPDEV
1
In XAML / C# - is it possible to add a custom attribute or property to a <Button/> that is an enumeration?

 
     <Button x:Name="acButton"
                Content="/"
                Margin="5"
                Grid.Row="1"

[b]Kind="Division"[/b]


                Grid.Column="0"/>

Open in new window


"Kind" would give intellisense (code completion) options of "Addition, Subtraction, Multiplication, Division"

In the C# code behind, something like this:

  public enum SelectedOperator
    {
        Addition,
        Subtraction,
        Multiplication,
        Division
    }

Open in new window




How do you code it?  Do you inherit from Button?
0
Looking at a piece of code and seeking to alter it as below. Any help appreciated.

      private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var doc = webBrowser1.Document;
            var results = doc.GetElementsByTagName("OL")[0];
          foreach (HtmlElement result in results.Children)
            {
                if (result.TagName != "LI")

                {
                    continue;
                }
 
                var publishedInfo = new PublishedInfo();

                publishedInfo.Title =
                    result.GetElementsByTagName("H2")[0].InnerText;
             
          var Link =
                result.GetElementsByTagName("H2")[0].GetElementsByTagName("A")[0].GetAttribute("href");

I now want to navigate to this link and extract information from this link page. How do I do this?

Do i need to set up a new browser page? Any example of how to do this so i am in a position to extract new html elements from the link page will be great. Thanks.
1
threading.timer does not always start.
i start one threading.timer   that should check after 80 miliseconds if a write to serial port is stuck.  if it is stuck, it purges the comm port and tries to write again.
the problem is that sometimes it works,  and some times the thread does not start.  does anyone know about this behavior ?  and can this be fixed ?
it is running on a win ce  with visual studio  2005.
the write takes 3 miliseconds,  but when it get stuck,  it can take from 10 seconds to 20 seconds,  so checking after 80 miliseconds  seems good.
the code:

               If g.timerStarted = False Then            'starting the timer only one time
                    tTimer = New Threading.Timer(AddressOf tTimerTick, Nothing, CInt(80), CInt(80))
                    g.timerStarted = True
                Else
                    tTimer.Change(CInt(80), CInt(80))
                End If
             
                    doWriteToComm(InSendStr, InDevType, CommResult, RealWriteBytes)      
           
           
                tTimerClose()   '  here i change the timer to  tTimer.Change(Timeout.Infinite, Timeout.Infinite)

thanks.
1
I have a winforms ERP software built using C# dotnet. Database is sql server. My issue is with installation at client side. It is taking huge time to install. Major time consuming is the installation of MSSQL server and its Management Studio. Is it necessary that I should install sql server at client side? Is there any option where I can copy the mdf and ldf files of the sql database to the system and connect with my application (like we do with access database)
1
Become a CompTIA Certified Healthcare IT Tech
LVL 12
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

How to resolve culture problem of decimal and thousand separator  of number of excel using c#
1
Need help calling the generic method.

We have a method 'DeserializeToModel' that takes in [a string (an encoded Json) and a reference type] and deserialized it into the reference type model.

public class DeserializedJsonToModel 
  {
      public T DeserializeToModel<T>(string encodedJson, T model) where T : class, new()
      {
          DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
          settings.UseSimpleDictionaryFormat = true; //This is needed to read in the dictionary in HospitalAffiliations class

          T deserializedModel = new T();
          MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(encodedJson));
          DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedModel.GetType());
          deserializedModel = ser.ReadObject(ms) as T;
          ms.Close();
          return deserializedModel;
      }
  }

Open in new window

 
 The problem is calling the generic method on line 49 in this unit test: 'SuperHero' is a type, which is not valid in the given context      
'SuperHero' is a type, which is not valid in the given context
Here's the test class:
    [TestClass]
    public class DeserializedJsonToModelTest
    {
        private SuperHero hero;
        private DeserializedJsonToModel deserializer;

        [TestInitialize]
        public void Setup()
        {
            hero = new SuperHero()
            {
                FirstName = "Barry",
                LastName = "Allen",
                HeroName =

Open in new window

0
I have the following method below and I'm having a hard time understanding what does the following notation mean... The following code is reading from a table and converting it to a variable just not sure why the 9?

requiredFields[9] == 'T',  why a 9?

public static GeneralSetupProgramJobParameter GetProgramJobParameters(
            GeneralSetupProgramJobParameter item,
            string reqdfields,
            string prodparam,
            string chngparam,
            string estutilfld,
            bool defaultStatus0For2ndPrgm
            )
        {
                var requiredFields = reqdfields.ToCharArray();
                var productionDefaults = prodparam.ToCharArray();
                var changeParams = chngparam.ToCharArray();
                var estUtilFields = estutilfld.ToCharArray();

                item.DefaultToStatus0For2ndProgram = defaultStatus0For2ndPrgm;

                item.ProgramJobRequiredFields = new ProgramJobRequiredFields
                {
                    IsRequiredDateSold = requiredFields[9] == 'T',
                    IsRequiredSalesPerson = requiredFields[11] == 'T',
                    IsRequiredSource = requiredFields[10] == 'T',
                    IsRequiredSize = requiredFields[16] == 'T',
                    IsRequiredRoute = requiredFields[14] == 'T',
                    IsRequiredCancelDate = requiredFields[12] == 'T',
                    IsRequiredCancelReason = requiredFields[13] == 'T',
                    

Open in new window

0
Hello Experts,
I have a Forget Password link in the Login Page.  When clicked, I received an email with a link to Reset the password.  In email, it contains a link, which will take you to the page where you can reset it. The problem is when I click on the link, the page error ed out with the following error message.  Any idea what is going on.  Any idea how to debug the page when loaded directly from the link?  Please let me know if you can.  Thank you in advance.

Thank You!

Server Error in '/' Application.

Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
1
I've tried, Directory.Exist. I have tried some P/Invoke Marshalling from Win32 API Functions. They all seems to work, but the issue here is when i come across a share that doesn't exist it can take as long as 120 seconds to get a response back. I minimized the amount of times I perform the check by only running the check if the remote server exists, if it doesn't then we know the share doesn't exist.

Currently I am utilizing this piece of code to check if a share exists. What this does in essence is only allow the thread to run for 10 seconds and force an abort, but the abort may not work forcing the thread to run until the function finishes. The issue i have with that is since after 10 seconds I exit the code and unblock the calling thread but i never get the true result of the function since i am no longer waiting for it, which in some cases shows that the share exists but but with a weird error such as Error 1396 for example.

I have about 3,000 of these shares to check so if I didn't use a timed thread the checks could potentially take forever to complete.

Does anyone have any ideas on how to make this faster, whether its a different check function or how i go about using the thread logic?

Thanks

protected static void CheckResource(String strLink, ref String shareStatus)
    {
        String shareStatus1 = "NOT ACTIVE";

        Thread t = new Thread(new ThreadStart(delegate () {
            IntPtr pZero = IntPtr.Zero;
            IntPtr pSid = pZero;

Open in new window

0
I need to get the selected value of a listview that has 2 columns. I think this should be simple, but I am not getting the value I need. I have a winforms application, in C#. I populate the list view like this:
foreach (var item in documents)
{
	lstMyList.Items.Add(item.Name + "\t\t" + item.Value + "\t\t");
}

Open in new window

It displays the list with the values side by side. When I select a value from the list, I want to capture just the item.Name value. How can I do that?
0

C#

93K

Solutions

25K

Contributors

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).