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

I am using EPPLUS to populate Excel.

If, using C#, I MessageShow the contents of a cell that looks like "12-Feb" it will display "2/12/2019 12:00:00 AM".  So, this looks like a date.

Now I want to throw into a variable the day portion of that cell... the 12.

Any idea on the conversion needed here?
0
I tried to find exampl c# codes to get Geo Google API and response address.
I have Lat/Lng in my database and try to get the address response back.

Thanks
0
Hi,

I am working on C# and used Linq.

How can I factor my below code? It has too many foreach


        foreach (var category in Model.ArrivalBooking.AvailableProducts.Where(t => t.Products.Any(x => ((x.IsVisible == true) && (x.ProductType == "C")))).OrderBy(b => b.SortOrder))
                {
                    if (category.CategoryCode == "MNG" || category.CategoryCode == "TRN")
                    {
                        foreach (var product in category.Products.Where(t => t.ProductType == "C" && t.IsVisible == true).OrderBy(x => x.Rate))
                        {
                            if (coreServicesRules.ProductCodeList.Contains(product.ProductCode))
                            {
                                productDetailsInGrid = productDetailsInGrid.Replace("@@PRODUCTCODE@@", product.ProductCode);
                                productDetailsInGrid = productDetailsInGrid.Replace("@@PRODUCTCODEAEDRATE@@", product.Rate.ToString());
                            }
                        }
                    }
                }

Open in new window


Please advise.
0
Hi,

I am working on C# .Net project.

How I will make Linq query if I need to find the data from List object which is inside List?

public class CoreServicesRules
    {
        public List<CoreServicesProductDetails> CoreServicesProductList { get; set; }
    }


    public class CoreServicesProductDetails
    {   
        public List<string> ProductCodeList { get; set; }
        public string ReplaceProductCodeFromString { get; set; }
        public string ReplaceProductRateWithString { get; set; }
    }

Open in new window

     
      Now I wanted to check data from
      
	public List<string> ProductCodeList { get; set; }

Open in new window

     

      and I have object for CoreServicesRules
      
      
      I wanted to see if ProductCodeList contains "My product Code".
      
      Please help me with the query.
0
I have a simple enough line of code:
AssemblyName[] referencedAssemblies = Assembly.LoadFile(@"C:\Program Files (x86)\MyTestApplication\test.dll").GetReferencedAssemblies();

Open in new window

This returns a valid list of referenced assemblies but I need to go deeper. I need to get all the referenced assemblies of the referenced assemblies (excluding GAC assemblies if possible) but I don't have a full path of the referenced assemblies to load their references. How do I recursively get assembly references like this?
0
I have mvc / razor app using ajax to make some transactions. everything is working fine.
But just we will add more parameters in data and It is going to super long list. so I want to find better way to handle this codes below.
I am thinking using json format passing value from front to the back. but do not know how to do it.

my question is:

1. is it best practice to use json format to pass list of value back and forth? If yes, can you show me how to do it with my codes below?
2. If json is not, can you suggest me what to do?
3. On the end - code behind. I do have lead class. and hope the best will be JsonResult CreateLead(Domain.Lead l) so I do not have to worry too much about list too long.


Thanks


$.ajax({
                                url: "/Home/CreateLead",
                                datatype: "text",
                                data:
                                {
                                    'firstname': document.getElementById("first-name").value,
                                    'lastname': document.getElementById("last-name").value,
                                    'phonenumber': document.getElementById("phone-number").value,
                                    'emailaddress': document.getElementById("email-address").value,
                                    'totalcountadult': document.getElementById("total-count-adult").value,
                                    'totalcountkid': 

Open in new window

0
I have object call Lead and a static method just like email template.
insid of using statement. is it possible to loop the Lead object and get the list of child object?
like this:

body = body.Replace("{displayname}", l.childname);

I have very long list and do not want to type line one by one.

Thank


public static string CreateEmailBody(Domain.Lead l, string templatePath)
        {
            string body = string.Empty;
            using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath(templatePath)))
            {
                body = reader.ReadToEnd();
            }
            body = body.Replace("{FirstName}", l.FirstName);
            return body;
        }

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

namespace Domain
{
    public class Lead
    {
        [DisplayName("LeadID")]
        public int LeadID { get; set; }
        [DisplayName("Subject")]
        public string Subject { get; set; }
        [DisplayName("FirstName")]
        public string FirstName { get; set; }
        [DisplayName("LastName")]
        public string LastName { get; set; }
        [DisplayName("Email")]
        public string Email { get; set; }
        [DisplayName("MobilePhoneNo")]
        public string MobilePhoneNo { get; set; }
        [DisplayName("LeadStage")]
        public string LeadStage { get; set; }
        

Open in new window

0
Following on from previous questions
About  serialize and deserialize XML the data is from The Movie Database API

How might I force an element to be refreshed?
Setting it to NULL fetches new data but  doesn't remove the old first resulting in duplicate entries

// ...  Code above locate tv show and season

                  Episode episode = season.Episodes.Where(ee => ee.EpisodeNumber == Epnum).FirstOrDefault();
                            if (checkBox1.Checked == true)
                            {

                                episode = null;
                            }
                            if (episode == null)
                                    {

                                            // fetch data from from The Movie Database API 
                                    var NewEpisode = client.GetTvEpisodeAsync(TMDBid, SeasonNumber, Epnum).Result;
              // Add new episode
                                    episode = new Episode()
                                    {
                                        EpisodeNumber = Epnum,
                                        EpisodeName = NewEpisode.Name,
                                        Overview = NewEpisode.Overview,
                                        BackDrop = NewEpisode.StillPath,
                                        FullPath = path
                    

Open in new window

0
Hi ,
Advance thanks!
Am using .net framework 4.6.1 and class library project using c#. This project doesn't have config, startup.cs or global.ascx where i enforce string transport security (hsts ) on endpoints.
How to add the header  to configure Strict Transport Security (HSTS). I think i should do something like below in the application but not sure how to do that. Please help....
Response.AddHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");

Kind regards,
Pooja
Response.Headers.PNG
0
We use https://geo.ipify.org/
and get the string from their Geo API as follow:

{"ip":"16.81.253.114","location":{"country":"US","region":"California","city":"Los Angeles","lat":33.2342,"lng":-117.9063,"postalCode":"90032","timezone":"America\/Los_Angeles"}}

1. Is it a Json format?
2. how to use c# foreach statement to get list of object (country, region, and postcode)?

Thanks
0
Directory.Exists(C# DotNet) returns true, but actually, the path is not existing in explorer windows. However, when I type in the unc or change directory using DOS command the directory appears.  Although "Directory.Exists" find the directory, it does not copy the directory. It only copies folders and files shown in explorer. I assume these folders\files were deleted but somehow is being seen by "Directory.Exists". How can I get "Directory.Exists" to ignore these folders\files? Also, if these are not deleted files, please explain why they are not shown in explorer. If they are deleted files that still exist on my computer, will they cause performance issues with the filesystem? Could this cause a directory search to take longer?
0
Hi,
Am using .net framework 4.6.1 and the class library project using C#. Need to enforce HTTP Strict Transport Security (HSTS) in all public facing http endpoints.I did configuration settings but it doesn't help me. Please help me about how to enforce HSTS on project and how to verify the site has hsts settings.
Have attached Properties window of the project, web.config, startup.cs .Please help...


Kind regards,
Pooja
Properties.PNG
Startup.cs
Web.config
0
Compare a List with an Array (in .NET)

Please list the pros and cons of each.

Thanks
0
Not sure why it always return 0 on last two decimal. like 4.00 5.00... I hope to see 4.23 e.g.

 @{ 
                                decimal totalRate=0;
                                foreach (Domain.Review fReviewItem in rv.ReviewSummary(f))
                                {
                                    totalRate = decimal.Parse(string.Format("{0:F2}",(fReviewItem.TotalRateCount / fReviewItem.TotalReviewCount))); 
                                } 
                                @totalRate;
                            } 

Open in new window

0
What are some common conversational terms used when discussing the BigO notation?

I think this wold be a good way to give me more exposure to learn the meaning of common terms used when discussing the BigO notation.

Please provide as many as come to mind...

Thanks
0
What performance consideration (for sorting) are there in .NET regarding various List Types? Arrays? Other?

What options are there when choosing a list type to use to hold large amounts of data? And what are the advantages of one of the other in a quick sort-time is required?

And, besides sorting, where would performance be a consideration?

Thanks
0
I got the third one wrong . I have my explanation in the code.

protected void Page_Load(object sender, EventArgs e)
		{
			string weather = "rainy";
			ChangeTheString(weather);
			var p = weather; //*** this comes out as "rainy" because string is a reference type so even tho the function changes the value, we'll still get "rainy"

			string[] rainydays = new[] {"Monday", "Friday"};
			ChangeTheArray(rainydays);
			var t = rainydays; //*** this comes out as "Monday" and "Sunday". string array is a value type? (I don't think this is correct even tho I got the answer right)

			Forecast forecast = new Forecast {Temp = 700, Pressure = 20};
			ChangeTheClassInstance(forecast);
			var s = forecast.Temp; //*** this is 35. I got this wrong. I a new instance of Forecast is created and passed. If "class" is a reference type, why didn't I get 700?
		}

		public class Forecast
		{
			public int Temp { get; set; }
			public int Pressure { get; set; }
		}

		public static void ChangeTheString(string weather)
		{
			weather = "sunny";

		}

		public static void ChangeTheArray(string[] rainyDays)
		{
			rainyDays[1] = "Sunday";

		}

		public static void ChangeTheClassInstance(Forecast forecast)
		{
			forecast.Temp = 35;

		}
	}

Open in new window

0
I'm going over some sample code for my interview on Friday... code practices I'm finding.

This is the sample code. I run it and I get errors on 2 lines but I'm not quite sure about the explanation. I'll add my comments in the code below as to why I think the error occurs.

protected void Page_Load(object sender, EventArgs e)
		{
			object car = new Car {MaxSpeed = 180};
			object processor = new Processor { MaxSpeed = 2500 };

			Vehicle v1 = (Vehicle) car;
			int speed = v1.MaxSpeed;

			Vehicle v2 = car as Vehicle;
			int s2 = v2.MaxSpeed;

			Vehicle v3 = (Vehicle)processor; //** error here with invalid cast. Why can't I cast processor to vehicle...because processor is not inheritng from Vehicle?
			int s3 = v3.MaxSpeed;

			Vehicle v4 = processor as Vehicle; //*** this comes out as null. I think because inheritance is "is a" relationship but processor is not a vehicle. Is this correct?
			int s4 = v4.MaxSpeed; //*** null error here because v4 is null
		}

		public class Vehicle
		{
			public int MaxSpeed { get; set; }
		}


		public class Car :Vehicle{}

		public class Processor
		{
			public int MaxSpeed { get; set; }
		}

Open in new window

0
This code is ingesting data from the table into a data table.  What's the best way to use a dictionary instead of a data table?
The addressID should be the key.  The other fields from the table should be a list hence Dictionary<string, List<string>> dict2 = new Dictionary<string, List<string>>();  


                Dictionary<string, List<string>> dict2 = new Dictionary<string, List<string>>();
                string ConnectionString = @"Data Source=.\SqlExpress;Initial Catalog=WebAPIDB;Integrated Security=True;MultipleActiveResultSets=True";// + "providerName = System.Data.SqlClient";
                using (SqlConnection sqlCon = new SqlConnection())
                {
                    using (SqlCommand sqlcmd = new SqlCommand())
                    {
                        using (SqlDataAdapter sqladp = new SqlDataAdapter())
                        {
                            using (DataTable dt = new DataTable())
                            {
                                sqlCon.ConnectionString = ConnectionString;
                                sqlcmd.Connection = sqlCon;
                                sqlcmd.Parameters.Clear();
                                sqlcmd.CommandType = CommandType.StoredProcedure;
                                sqlcmd.CommandText = "select AddressID,AddressLine1,AddressLine2,City,StateProvinceID,PostalCode,SpatialLocation,rowguid,ModifiedDate  from person.Address";
                                

Open in new window

0
Using React and inline styles.  I have a div that I want to eliminate the bottom padding or margin.

This does not work:

const divStyle = {
    color: 'red',
    paddingBottom: 0

};

                        <label className="col-xs-1">
                            <div style={divStyle}>*</div>
                          First Name
                        </label>
0
I am using HighCharts and when loading the View, the source for Highcharts is loaded after the DOM.  The chart does not display.

My View looks like this:

@{
    ViewBag.Title = "Warranty Expiration Chart";
}

<div class="jumbotron">

    <div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>

</div>

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("GetMaintenanceExp", function (data) {

            Highcharts.chart('container', {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                },
                title: {
                    text: 'Maintenance Expiration Chart'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }

Open in new window

0
Hello all,

I need a connection string from c# to SQL server 2008.

The code below doesn't work.

Provider = SQLOLEDB; Server = ServerName; User id = UserName; Password = ThePassword; Database = TheDB

I get Invalid connection string attribute

I'm using ADODB.
0
how do I do this with a lambda expression?
int[] n1 = new int[18] { 5, 9, 1, 2, 3, 7, 5, 6, 7, 3, 7, 6, 8, 5, 4, 9, 6, 2 };
            var nQuery =
            from VrNum in n1
            group VrNum by VrNum into y
            select y;
            foreach (var i in nQuery)
            {
                Console.WriteLine("Number " + i.Key +" appears " +i.Count()+" times.");
            }

Open in new window

0
Can anyone tell me the voodoo needed to test for BACKUP<DIV is contained in str?

str is declared as a string.

These attempts throw VS errors

if (str.IndexOf("BACKUP<DIV")) != true)
if (str.IndexOf("BACKUP<DIV")) <> true)
if (str.IndexOf("BACKUP<DIV")) != 0)
if (str.IndexOf("BACKUP<DIV")) <> 0)
0
I'm trying to start a new visual studio 2017 C# project and have selected it to be an MVC project with the web API checkbox checked.  I've also checked the add unit test checkbox and changed the authentication to single user.  After I click OK I'm getting this message.

the specified path file name or both are too long. the fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.  The fully qualified file name is D:\OneDrive\Documents\Courses\QAASPNETMVC\Labs\04  DataStorage\01 Setup Projects\Begin\QAForumSolution which is 103 characters.
Why am I getting this message?
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).