C#

94K

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

I have a working code but I would like to convert a block of code into a class a just call the classs. See code below.
DataTable results = dataAccess.Billing.GetDataTable(selectQuery);

                // Convert Table to List
                List<Service> serviceLines = new List<Service>();
                serviceLines = (from DataRow dr in results.Rows
                                select new Service()
                                {
                                    MemberNbr = dr["MEMBER_NBR"].ToString(),
                                    AffNbr = dr["AFF_NBR"].ToString(),
                                    AmtAllowP = Convert.ToDecimal(dr["AMTALLOW_P"]),
                                    AmtCharge = Convert.ToDecimal(dr["AMTCHARGE"])
                                }).ToList();

Can I remove this block of code and make a class or constant in another file so it is easy to maintain and just call it?
0
Hi Experts!

Need your help with the following query.

In jobHistories, for each City, for each Perid, how would you filter the linq query to return the following condition: if Hired = "Y" then select one of the record with Hired = "Y" and ignore the rest of the records for PerId. If there are no Hired= "Y" then just select one record for the PerId
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{

    [TestClass]
    public class UnitTest3
    {
        internal class JobHistory
        {
            public int PerId;
            public string JobTitle;
            public string Address;
            public string Hired;
            public string City;
            public Nullable<System.DateTime> CreatedOn;
        }

        [TestMethod]
        public void Extract_HiredThenEverythingElse_CorrectPicks2()

        {
            // Arrange
            List<JobHistory> jobHistories = new List<JobHistory>()
            {
                new JobHistory() {PerId = 1, JobTitle = "Knight", Address = "123 Street", Hired = "Y", City = "Yokohama", CreatedOn = new DateTime(2011, 6, 1)},
                new JobHistory() {PerId = 1, JobTitle = "Cook", Address = "234 Street", Hired = "Y", City = "Yokohama", CreatedOn = new DateTime(2012, 6, 1)},
                new JobHistory() {PerId = 1, JobTitle = "Mechanic", Address = "345 Street", Hired = "N", City = "Yokohama", CreatedOn = 

Open in new window

0
Hi Experts!

Need help with the following linq query:

            //For each City, For each person, if the JobTitle is EITHER Knight, Cook, Mechanic we want to take all the records for the Person for that City,

            //For each City, For each person, if there's a duplicate JobTitle with the same address then just take one

Below is a mock up unit test with test data.


using Microsoft.VisualStudio.TestTools.UnitTesting;

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace UnitTestProject2

{

 

    internal class JobHistory

    {

        public int PerId;

        public string JobTitle;

        public string Address;

        public string City;

        public Nullable<System.DateTime> CreatedOn;

    }

 

    [TestClass]

    public class UnitTest2

    {

        [TestMethod]

        public void Extract_PersonByJobTitleByCriterias_Success()

        {

            // Arrange

            List<JobHistory> jobHistories = new List<JobHistory>()

            {

                new JobHistory() {PerId = 1, JobTitle = "Knight", Address = "123 Street", City = "Sapporo", CreatedOn = new DateTime(2011, 6, 1)},

                new JobHistory() {PerId = 1, JobTitle = "Cook", Address = "234 Street", City = "Sapporo", CreatedOn = new DateTime(2012, 6, 1)},

                new JobHistory() {PerId = 1, JobTitle = "Mechanic", Address = "234 Street", City = "Sapporo", CreatedOn = new DateTime(2012, 12, 1)},

 

              

Open in new window

0
Hi,

I'm writing a program using c# and MariaDB, I'm having an issue with an error with my Binding.

The program works fine, I bind the Database to some text boxes, and I can navigate through the records just fine.

In the application I get the end user to press a 'Load' button to load the database, the problem happens when the end user hits the Load button a second time and it kicks out with the error:


System.ArgumentException: 'This causes two bindings in the collection to bind to the same property.
Parameter name: binding'



So the problem, I think is obvious, I can't rebind something, since the first click did the binding the first time.

I'm was just wondering what is the best way to trap this type of error?  
I just want nothing to happen when the end user hits the button multiple times.

Here is my code:

private void btn_CommodityTab_LoadRefreshCommodityTable_Click(object sender, EventArgs e)
        {
            MySqlCommand authorsCommand;
            MySqlConnection con21 = new MySqlConnection(@"datasource = localhost; port=3306;username=root;pwd=;");

            con21.Open();

            authorsCommand = new MySqlCommand("Select * from bbb.commodities where TDId = " + txtBox_TD_Current_ID.Text + " Order by TDId ", con21);

            authorsAdapter = new MySqlDataAdapter();
            authorsAdapter.SelectCommand = authorsCommand;
            authorsTable = new DataTable();
            …
0
I copied the following codes from mvc/razor angular c# web app. I would like to learn that usually how the {User.FirstName} got the data source from.  

Just hope to get someone who know about mvc/angular.

Thanks



<ul class="nav navbar-nav" id="centeredInNav"><li><a href="tel+:112222">for questions Call 
                {{User.FirstName}} {{User.LastName}} at {{User.Phone | tel}}
            </a></li></ul>

Open in new window

0
I can call the following 3 methods, which all achieve the same delay of 2 seconds, in 12 different ways.

I'm interested in the underlying details of these 12 different calls differ under the hood. Exactly what does each do behind the scenes and how do they differ?

        private async Task AsyncDelay()
        {
            await Task.Delay(2000);
        }

        private void FooSleep()
        {
            Thread.Sleep(2000);
        }

        private void TaskDelayWait()
        {
            Task.Delay(2000).Wait();
        }


            FooSleep();
            TaskDelayWait();
            AsyncDelay().Wait();
            Task.Run(() => FooSleep()).Wait();
            Task.Run(() => TaskDelayWait()).Wait();
            Task.Run(() => AsyncDelay()).Wait();
            Task.Run(async () => await AsyncDelay()).Wait();
            await AsyncDelay();
            await Task.Run(() => FooSleep());
            await Task.Run(() => TaskDelayWait());
            await Task.Run(() => AsyncDelay());
            await Task.Run(async () => await AsyncDelay());

Open in new window

0
using VS C# what is the proper way to rename objects? I have a screen I want to make more generic and I want to rename all the labels, text objects as well as the form itself. Is it as simple as highlighting each one and selecting rename? Will this rename the objects throughout the entire project? This is VS 2017 and 2019.
0
Hi

I have a windows form application that gathers info about my Movies using the TMDB API

the form shows info about people with the movies they are in How might I overlay the movie poster with a tick box (see Picture for mock up of what I want to do) if it is in the database?

The Poster image is from the internet https://image.tmdb.org/t/p/w92/2QoLPgwWphEO2eVDm6ehGxCWoXV.jpg
and the green tick is a transparent gif or png

Each movie is loaded via a UserControl this is where I'd put the code with a bool InDB = true/ false

using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MoviesDataModel;
using TMDbLib.Client;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Movies;
using TMDbLib.Objects.TvShows;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.People;

namespace FilmsDB
{
    public partial class KnownForMovies : UserControl
    {
        TMDbClient client = new TMDbClient(ConfigurationManager.AppSettings.Get("API_Key"));
        string ImgPath = ConfigurationManager.AppSettings.Get("ImgPath");
        static string ImgURL = ConfigurationManager.AppSettings.Get("ImgURL");
        string OriginalImgPath = ConfigurationManager.AppSettings.Get("OriginalImgPath");
        string 

Open in new window

0
Hello Experts,
I am working with Visual c# and windows 10.
I need to show a circle (200 pixels diameter) somewhere in the form.
The circle can be dragged and change position inside the form:

Up until here, I am ok, can do it...

Now the circle has to be divided into four equal parts,
Each part different color.
Each part has to perform a different task when clicked or right click
nad if outside the circle the same event does nothing.

So far I can do everything with rectangles since PictureBox is like that
But how can I have objects with a different form than a rectangle?
Or any ideas on how to do the last with the actual tools?

Regards,
0
I'm thinking I need a lookaround expression for this but the exact syntax is escaping me. I need a Regular Expression that will match on the word "then" but only once and only if the word "else" doesn't come before it. I'm using it for syntax highlighting and I want to make sure it highlights correctly for one and only one case. For example:

if (condition) then "something" else "something else"

Open in new window

should be 100% valid but

if (condition) else "something else" then "something"

Open in new window

should definitely fail

Things should also fail if the word "then" appears more than once unless that word is enclosed in double quotes. That one is probably a bit tricky.
0
Hello everyone,

I need your help please.

How can I have an if statement inside my list
I want to say if the selectedFilterList contain "status" then display the status field on my grid.

I have a dropdown list for the user to select a specific fields to display in my grid.


 modelList = list.ToList().Select(x => new RuleDetail
            {

                if (model.SelectedFilterList.Contains("Status"))  // I need to do the same to all of them if SelectedFilterList contain the string then display it
                {                                                                                 //I have an error here 
                    Status = (Boolean)x.isActive,                            // Can I do an if inside a list? 
                }


                //Status = (Boolean)x.isActive,
                RuleSet = GetRuleset.Where(a => a.RuleSetId == x.RuleSetId).FirstOrDefault().RuleSet,
                RuleIdentifier = GetRuleIdentifier.Where(a => a.RuleIdentifierId == x.RuleIdentifierId).FirstOrDefault().RuleIdentifier,
                Versions = x.Version,
                Environments = x.Environment,
                CommitID = x.CommitID,
                CommitDescription = x.CommitDescription,
              
            }).ToList();

Open in new window

0
Hi

Is the only way to have restrictions on T to make an interface, or are there any other way ?

Since "where T:" can have only one class:

public object Test<T>(int whatType) where T:testclass

Open in new window

0
Hi.

I have a method in C#  that I would like to be more generic.

public List<T> Test<T>(DateTimeOffset afterDate) where T:IType
      {
         string afterCursor = null;
         T data;
         bool morePages = false;
         List<T> retData = new List<T>();

         do
         {
            data = GetData<T>(afterCursor);
            if (data != null)
            {
               foreach (var item in data.Orders.Edges)
               {
                  afterCursor = item.Cursor;
                  retData.Add(item.Node);
               }
               morePages = data.Orders.PageInfo.HasNextPage;
            }
            else return null;
         } while (morePages);
         return retData;
      }

Open in new window


The IType interface is a collection of Orders, Customers and Products classes.

PS: The reason for using the Interface is to restrict the T types. If there is a better way, please let me know.  

The class structure on the top is the same, except for the property Orders. It's called Customers in Customers, and Products in Products. So the data.Orders.Edges will be data.Customers.Edges for Customers, and data.Products.Edges for Products.

So the name after data is the only thing that will change in this method. The rest is the same (Edges, PageInfo etc)

How can I accomplish this  so that it can be used for Orders, Customers and Products?

I know about checking if T is Orders, Customers or Products.
0
I need to get todays date in the format

DDMMYY

and DDMMYYYY

My current syntax  is shown below

Todays Date  Syntax
Whats the correct syntax for these 2 date formats

Thanks


Olukay
0
Hi Experts,
It is possible to delete all the  <li> items from a <ul> where the attribute is data-select-id="SelectState" using jQuery?

<div data-select-id="SelectState">
	<ul class="opts" style="display:none">
		<li> Test1 </li>
		<li> Test2 </li>
	</ul>
</div>

Open in new window


Thanks in advance!
0
Hi,

I'm trying to export my data to an excel document.

this is my first time doing it in MVC C# so I need your help please.

Do I need to create a view document for "ExportToExcel " ?

I'm doing the example that is in this URL:
https://www.yogihosting.com/export-excel-asp-net-mvc/


Thank you for your help ;-)

Filtering the data in my model

    public List<RuleDetail> RuleDetailList(CABRSearchRules model)
        {
            List<RuleDetail> modelList = new List<RuleDetail>();

            IEnumerable<CABR_RuleDetail> list = new List<CABR_RuleDetail>();
            IEnumerable<CABR_HistoryRuleDetail> Historylist = new List<CABR_HistoryRuleDetail>();

            if (model.SelectedCurrentOrHistoryID == 1) //Current
            {
                list = _unitOfWorkCABusinessRules.RuleDetailRepo.GetAll().ToList();

                //Filter Status
                if (model.SelectedStatus != null)
                    list = list.Where(x => x.isActive == model.SelectedStatus);

                //Filter Environment
                if (model.SelectedEnvironment != "All")
                    list = list.Where(x => x.Environment == model.SelectedEnvironment);

                //Filter Version
                if (model.SelectedVersion != null)
                    list = list.Where(x => model.SelectedVersion.Any(m => Equals(x.Version, m)));

                //Filter CQ Ticket
                if (model.SelectedCQticket != null)
                    list = 

Open in new window

0
I have in my c# application a combo box from which i  select a record and then
use the split command to get then items in the combo  (See Screen with the Combo box Below)

Screen Showing Combox box ready for record selection
The problem i have is that ordinarily if i click on a record it show give me the last figure  exchange rate
in the exchange rate box.

What happen right no is that is i just click I dont get anything selected into the exchange rate box (see below)

Screen running straight without the message box
Now when i introduced the message box and just click ok after the messagebox comes up i get the required result

see screen below.

Desired result only after introducing a message box
Definitely i dont want my application to ship out with users having to Click ok on message box

How can i solve this problem.

There must be  a way to get the selection without  the message box

The detailed code is shown below:

[private void glTRANSCurrencyValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Setting index to 0 at form load ensure that script below is not processed during combo initial load
            if (this.glTRANSCurrencyValue.SelectedIndex != 0)
            {
                glTRANSExchrateValue.Text = "0";
                System.Data.DataRowView selected_row = glTRANSCurrencyValue.SelectedItem as System.Data.DataRowView;
                // Always use this TryParse to determin a selected value. Thencomment ou the Message Box once satisfied
                bool isNumeric;
          …
0
This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method. I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):

$(document).ready(function () {
        $('#PurchaseOrderLineItemAddId').click(function () {
            var aPurchaseOrderViewModel = @Html.Raw(Json.Encode(Model));    
            var selectedVendorText = $('#ddlvendors option:selected').text();
            var selectedVendorValue = $('#ddlvendors option:selected').val();  
            var LineItemReqJsonObj = {};

            LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
            LineItemReqJsonObj.VendorText = selectedVendorText;
            LineItemReqJsonObj.VendorValue = selectedVendorValue;

            var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';

                $.ajax(
                    {
                        type: "POST",
                        //data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
                        //data: aPurchaseOrderViewModelStr,
                        data: dataToPass,
                        url: '@Url.Action("PurchaseOrderAddItem")',
            

Open in new window

0
I am getting a error must declare the scalar variable "@qualityControl "

I think it's because in c# i have it as a checkmark box and in sql it is a bit.  how do I arrange the Parameter? see code.

using (SqlConnection SqlConn = new SqlConnection
                     ("Data Source = gcm10; Initial Catalog = Vendor; Integrated Security = True"))
            {
                string query = "Insert into vendor_approval(name, add1, add2, city, state, zipcode, phone_number, fax_number, contact_name, product_vendor, cert_quality, quality_assurance, product_sample, quality_control, specified_inspection, certificate_conformance, inspection_testing, supplier_testing, quality_system)" +
                    "values (@name, @add1, @add2, @city, @state, @zipcode, @phone_number, @fax_number, @contact_name, @product_vendor, @cert_quality, @Quality_Assurance, @Product_Sample, @qualityControl, @specified_inspection, @certificate_conformance, @inspection_testing, @supplier_testing, @quality_Testing)";
                SqlCommand cmd = new SqlCommand(query, SqlConn);
                cmd.Connection.Open();
                cmd.Parameters.AddWithValue("@name", Ven_Name.Text);
                cmd.Parameters.AddWithValue("@add1", Add_1.Text);
                cmd.Parameters.AddWithValue("@add2", Add_2.Text);
                cmd.Parameters.AddWithValue("@city", City.Text);
                cmd.Parameters.AddWithValue("@state", State_list.Text);
                …
0
C#: Please explain relationship between "async" and "await"

I generally see how this code works:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

but need a better understanding of when to use both "async" and "await" together. I was a little confused by the transition of one paradigm to the the better paradigm in this one example...so, a simple explanation would be helpful.

Thanks.
0
Need a C# Web Service to call external Web Services. How?

I need to create a back-end web service which then calls a small handful of external web services in order to complete the calculations. Is this a simple task? Using C# to execute an external web service?

How would I call four different such calls at the same time? Does this qualify as "parallel processing"? Anything fancy needed? Or, can I quickly call one after the other, then get a callback for each?

How does this work?

Thanks
0
Hi!

I'm creating a Maria DB project (MySQL) using C#, and I have a need to get the primary key Id from a row I just insert into a table.

I've looked at several solutions on the internet and I'm not having any success.  They are either unreliable (documented errors) or do not work with MySql/Maria.

This is my last effort:


 MySqlCommand cmd = new MySqlCommand("INSERT INTO bbb.traveldocuments (CustomerID,TDNumber,TDDateCreated,TDMoveStart,TDMoveEnd,TDJobNumber,TDPermitType,TDNotes)" + "VALUES(@CustomerID,@TDNumber,@TDDateCreated,@TDMoveStart,@TDMoveEnd,@TDJobNumber,@TDPermitType,@TDNotes); SELECT SCOPE_IDENTITY() ", con);

.
.
.
cmd.Parameters.AddWithValue("@TDNotes", txtBox_TD_Notes.Text);

cmd.ExecuteNonQuery();
int insertedID = Convert.ToInt32(cmd.ExecuteScalar());


When I run the above code I get:

MySql.Data.MySqlClient.MySqlException: 'FUNCTION SCOPE_IDENTITY does not exist'

Are there any suggestions I can try?

Thank you in advance.

G
0
I have c# application in which i am trying to get records from
a combobox into a string variable.

The combo loads at Form load  ( see screen below )

ComboBox with 3 rows loaded from database
I the tried to select any of the records into a string variable  and some how
my string variable instead of  having data from the combo has an error  statement
about my Model  (see error page )

String  called phrase NOT containing Combo Data
I then tried to  use the debugger to find out if the record i selected is somewhere in memory
and indeed it showed up  (see  debugger output)

Debugged Screen shows record is in memory but not in my variable
How do i get the combo record out to my string variable.

Below is the Script that i am using to select the record from the combo and putting it in a string
variable

[private void glTRANSCurrencyValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Setting index to 0 at form load ensure that script below is not processed during combo initial load
            if (this.glTRANSCurrencyValue.SelectedIndex != 0)
            {
                string phrase = glTRANSCurrencyValue.SelectedItem.ToString();
                string[] words = phrase.Split(' ');
                int i = 0;
                foreach (var word in words)
                {
                    i += 1;

                    if (i == 1)
                    {
                        decimal var1 = Convert.ToDecimal($"{word}");
                        glTRANSExchrateValue.Text = Convert.ToString(var1);

 …
0
Hello Experts,
I am looking for a way to programmatically change the transparency property of the CMD window.
Using visual c#, and windows 10

It has to be programmatically, cant use short cuts or hotkeys or mouse.
maybe with a dos command.
Regards,
0
Hi,

My between date is not working

I'm only getting one record instead of three

I don't know what I'm doing wrong.

I tried without parsing it and that didn't work.

        public DateTime FromCreatedDate { get; set; }
        public DateTime ToCreatedDate { get; set; }

list = list.Where(x => x.CreatedDate >= DateTime.Parse(model.FromCreatedDate.ToString()) && x.CreatedDate <= DateTime.Parse(model.ToCreatedDate.ToString()));

Open in new window

0

C#

94K

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