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

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

Sign up to Post

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
Hi,

I need your help please!!!

 I want to say if the user enter in GroupTxt a range from 10 -30 the linq query will return the result within that range.


HTML Code
<select name="GroupListID" class="btn btn-default dropdown-toggle" id="GroupListID">
                            <option value="">Select an Option</option>
                                    <option value="3">Dx</option>
                                    <option value="5">Group ID</option>
                                    <option value="4">NPI</option>
                                    <option value="6">Plan Code</option>
                                    <option value="1">Px</option>
                        </select>


                         @Html.TextBoxFor(x => x.GroupTxt, new { @class = "form-control", @style = "width:100%" })

Open in new window



Database
Table: RuleDetail
if (model.SelectedGroupID != null && model.GroupTxt != null)
                     list = list.Where(x => model.GroupTxt.Any(m => Equals(x.ConditionAttributesAndValues, m)));
              
                      // here I want to say 
                      //  and 
                      // and if the user enter a range in the textbox then filter all that are within the range.

Open in new window



ConditionAttributesAndValues is varchar(1000)

the data inside the ConditionAttributesAndValue looks like this:

<br> IF Dx = aa (299.00,<br>299.01,<br>299.80,<br>299.81,<br>299.90,<br>299.91,<br>99999)  <br> AND Dx Between Range (10 - 30) <br>(aa22)<br>"aa55"<br>

Open in new window


so is there a way to search for Dx range and see if what the user enter in the textbox is within the range in the database field called ConditionAttributesAndValue?
0
Hi,

I'm working with linq and need your help please.

I have a string[] SelectedVersion that I pass from my view to the controller.

I want the linq to return query that contain the string SelectedVersion[]

list = _unitOfWorkCABusinessRules.RuleDetailRepo.GetAll().ToList();

list = list.Where(x => x.Version.Contains(model.SelectedVersion));

model.SelectedVersion is a string array 
x.Version is a string 

Open in new window



the error says: " I cannot convert string [] to string "

how can I solve this syntax?
0
Hi,

I have a small method that pulls the largest number out of a Column that is in a table.  It then displays it in a couple of text boxes.

The code works good, but in testing I want a decimal number (xx.x) but only getting an integer right now.

Here is the complete Method:


using (MySqlCommand cmd = new MySqlCommand("SELECT MAX(TDNumber) FROM bbb.traveldocuments", con1))
            {

                con1.Open();

                object result = cmd.ExecuteScalar();
                result = (result == DBNull.Value) ? null : result;
                decimal blah = Convert.ToDecimal(result);
                MessageBox.Show(blah.ToString());   // something to show me what the value of blah is at this point
                txtBox_TD_MAX_NUMBER.Text = blah.ToString();
               
                con1.Close();

                decimal newtd = blah + 1;
                txtBox_TD_nextTDNumber.Text = newtd.ToString();


            }

It's a little complex since my original code was crashing if the value was null (empty database).  Now I get a zero, which isn't bad, just wondering if it's because my Database is empty and the 0 is actually a null?

The format of the Column is 10.1 decimal unsigned.

Thanks!

G
0
Hello Experts,

After lot of efforts I did my SSIS pkg working in my local, which connects to Oracle DB using Oracle.ManagedDataAccess.Client dll(32-bit). After deploying it to 2016 server it says below and also I was using script task in the SSIS pkg 2017 and the target version is sql serer 2014.

Cannot load script for execution.



Thanks,
ASPDEV
0
var request = new HttpRequestMessage(HttpMethod.Post, "/token"){ Content = content };
                var responseToken = httpClientToken.SendAsync(request).Result;
                var resultToken = responseToken.Content.ReadAsStringAsync().Result;
                var jsonResult = JObject.Parse(resultToken);

                var httpClientCreateSurvey = new HttpClient();
                httpClientCreateSurvey.BaseAddress = new Uri("https://clear.pandolink.com");
                httpClientCreateSurvey.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                httpClientCreateSurvey.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", jsonResult["access_token"].ToString());
                var responsePando = httpClientCreateSurvey.PostAsync("/api/extension/survey-account",
                    new StringContent(surveyJson, Encoding.UTF8, "text/json")).Result;
                var result = responsePando.Content.ReadAsStringAsync().Result;
                jsonResult = JObject.Parse(result);
                var pandoAccountId = jsonResult["AccountId"];
                return pandoAccountId.ToString() == "0" ? "" : pandoAccountId.ToString();

Open in new window




What would be the RestSharp equivalent?

I am struggling with what would be the RestSharp equivalent of ReadAsStringAsync( ).   I am glossing over that when serializing the response.Content but I am not getting away with it.


Particularly, I am struggling with the extraction of the value of "AccountId" from the jsonResult var:

 var pandoAccountId = jsonResult["AccountId"];
                return pandoAccountId.ToString() == "0" ? "" : pandoAccountId.ToString();

Open in new window




Here is my attempt so far:


Open in new window

0
I have a method that should get data from SQL Server.

This method should put the data into the specified variable or class. It can be a single column, or multiple columns.

This is a example code (that has nothing to do with SQL server):

      internal static T GetValue<T>(T value) where T : new()
      {
         if (typeof(T).GetType().IsValueType)
         {
            return value;
         }
         else
         {
            T dummyClass = new T();
            return dummyClass;
         }
      }

Open in new window


It works perfectly with int, long and other value types, and classes. But NOT with string.

This works:

var test = Globals.GetValue<int>(1);

Open in new window


This gives a compiler error:

var test1 = Globals.GetValue<string>("2");

Open in new window


How can I get it to accept strings also, so it can return string ?
0
Hi Experts!

Need your help.
In C# LINQ how do you get the latest enrollment and return a List that's ordered by PerId?

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{

    internal class Enrollment
    {   public int  PerId;
        public string Class;
        public Nullable<System.DateTime> DateFrom;
    }

    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void LinqQuery()
        {
            //Arrange
            List<Enrollment> latestEnrolled = new List<Enrollment>()
            {
                new Enrollment() {PerId = 1, Class = "Chemistry", DateFrom = new DateTime(2018, 1, 1)},
                new Enrollment() {PerId = 1, Class = "Modern Drama", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 1, Class = "Math 302", DateFrom = null},
                new Enrollment() {PerId = 3, Class = "Physics", DateFrom = new DateTime(2016, 1, 1)},
                new Enrollment() {PerId = 3, Class = "Comp 101", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 3, Class = "Music", DateFrom = new DateTime(2017, 6, 1)},
                new Enrollment() {PerId = 2, Class = "Leadership", DateFrom = null},
                new Enrollment() {PerId = 2, Class = "Film Study", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 2, Class = "Microbiology",

Open in new window

0
How do I only display certain fields in sql query on a aspx c# page?  see code below using this in a load pdf page.

   
 
        }
        void LoadData()
        {
            var st = from s in db.Design_Tables select s;
            GridView1.DataSource = st;
            GridView1.DataBind();
0
I have a Grid called dgvDetailsTables in my C# application

I need to populated 2 columns of the Grid   (Department and Division)

from a list . Currently A click puts the whole record into the Department column.

The code below loads the Combo within the Grid  and also gives me  a list within the Combo  to select from

 dgvcmbDepartment.DataSource = GlobalConfig.Connection.GetResponsibleMgr_All();
 dgvcmdDepartment.DisplayMember = "FullCodeName"


 public string FullCodeName => $"{divisioncode}  {deptcode }  { deptdesc} ";


See  the Grid with the Combo loaded  elements of "FullCodeName"

Combo Withing the Grid already having a list"

I now need to cast the content of "FullCodeName"  so that the first element   goes into column 6  (Division )

and the Second element goes into coulmn7 (Department)

I am trying to Cast the content of FullCodeName such that i can achieve this goal

but i know my cast statement has an error  ( See Code below )

Wrong  Cast  Statement
Can someone please help to look at the Cast statement and how i should modify it

so that on Click event  I get the 2 columns into the grid columns desired.

Thanks


Olukay
0
How do I declare a read only value in an interface and properly declare it in a class that uses the Interface?

 public interface ISalesForceRepository
    {
        string SecurityToken { get; }
        string ConsumerKey { get; }
        string ConsumerSecret { get; }
        string Username { get;  }
        string Password { get; }

     ...

...

    }

Open in new window



public class SalesForceRepository : ISalesForceRepository
{



Says "Error	CS0535	'SalesForceRepository' does not implement interface member 'ISalesForceRepository.ConsumerKey.set'	SalesForceRepository":

string ISalesForceRepository.ConsumerKey
{
            get
            {
                return "3MVG9fMtCkV6eLhf5nAFy1[truncated].";
            }            
}

}

Open in new window



Says "The name 'Consumer Key' does not exist (same for the other params)":
await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

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