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've been ask this question in two different interviews...

What is the benefit of using stored proc ? another guy asked... when would you use a stored proc over inline sql

My answer:
Stored proc makes an application database agnostic ... application layer is separate from the data
Stored procs are compiled

----
When do we want to use a SP over inline SQL?  I didn't answer this one.

---
No matter how much I prepare for an interview... there's always something unexpected thrown at me!
0
I have the following codes to locate our website visitor's location. and I think the code below is only reading to our server's location.
It works but I do not think this is something we can get web visitor's current location.

My question is:
1. Above statement. do you think it is right?
2. Do you know any ways I can find our website visitor's current location regardless it is on mobile or PC?  I understood there is some proxy or some router may not indicate the current location. That is something I can live with. But I do need some ways to get their location instead of just our server address.



  public static Domain.IpInfo GetCurrentPosition()
        {
            //https://ipinfo.io/developers/replacing-getcurrentposition
            Domain.IpInfo ipInfo = new Domain.IpInfo();
            try
            {
                string info = new WebClient().DownloadString("http://ipinfo.io/geo");
                ipInfo = JsonConvert.DeserializeObject<Domain.IpInfo>(info);

                RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
                ipInfo.Country = myRI1.EnglishName;

                RegionInfo myCity = new RegionInfo(ipInfo.City);
                ipInfo.City = myCity.EnglishName;

                RegionInfo myState = new RegionInfo(ipInfo.Region);
                ipInfo.Region = myState.EnglishName;

                RegionInfo myZip = new RegionInfo(ipInfo.Postal);
                ipInfo.Postal = myZip.EnglishName;

                

Open in new window

0
I've been reading about anonymous types and I think the answer to this question is the 4th one "new class with properties both set and get methods". Saw an explanation on a site but forgot to bookmark it

b3.png
0
Hoping someone can help as I'm totally confused

I'm trying to create 2 similar but not identical XML files

In the code bellow I don't understand

  • Why I can't loop through the first lists I have  to create second lists to print out the name @ ##1

  • Why I get exception errors when trying to use XmlSerializer @##2

  • How do I make the XmlSerializer so I can feed it either list?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SplitXML
{
    class Program
    {
        // create two logs to hold each list
        static List<History> HistoryLog = new List<History>();
        static List<DownLoadLog> downloadlog = new List<DownLoadLog>();

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            // Dummy varibles;

            int myID = 123;
            int FileCount = 234;
            string ModName = "Hello World";
            string OldDir = @"D:\Path\To\OldPath";
            string NewDir = @"D:\Path\To\NewPath";


            // make a loop just   to test
            // this is to simulate where the infomation will be
            // derived from  
            for (int i = 1; i < 5; i++)
            {
                // history log
                History history = new History();

                

Open in new window

0
Practicing interview questions. Why does the second line throws an error? Is it because an explicit conversation is needed? I read about ValueTypes but still don't understand why it errors out..


IEnumerable<object> objects = new List<string>();
IEnumerable<ValueType> v =  objects; //*** error here.
0
I'm reviewing some interview questions. Why is the first one wrong and the second one correct?

            IEnumerable<string> objects1 = new List<object>(); //*** not correct

            IEnumerable<object> objects = new List<string>(); //correct
0
I had an interview the other day and they let me keep the test. I'm reviewing it to learn more...

One of the questions is: difference between  declaring an argument as "dynamic" vs "object". I answered #2 below. I've been reading about it and I think it's correct because of boxing and unboxing --> dynamic doesn't need it but Object can be cast. Is this correct?

b1.png
0
Hello EE,

I need to count the days intervals in a dictionnary Of(Date, String)

so if row 1 is :     12/01/01/2019,  ABC
row 2 is :   12/01/15/2019, XYZ
row 3 is : 12/02/22/2019, MNP


I need to have results like this somehow:  

15 days
38 days


so there is 15 days interval between row1 and row2 and there is 38 days between dates of row and row 3  (we need also to take into account the 30/31/28 ending days of months)

how can I do that!? Any efficiant ways with LINQ maybe ?
0
I have a website and try to track client IP to locate his/her for better information tracking.
we use c#/mvc/razor.

any suggestions on what we can use?

Thanks
0
i use @HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) but it does not read https. it read http only. how to fix it?
0
Hi,
Thanks!
This is regarding sonarqube complaint. I am using

public async Task<(Guid, string, Guid)> GetAllCategories()
{
    return (Guid.Parse(data["Id"].ToString()),
            data["StatusName"].ToString(),
            Guid.Parse(data["StatusId"].ToString())
    );
}

Open in new window


Sonarqube is complaining "Remove this return statement or make it conditional" . Please help me how to fix this bug..

Kind regards,
Pooja
0
I have a datagridview that contains 5 columns. I have set the width of each column. 90% of the time when the grid is displayed it fits perfectly with no horizontal slider. The other 10% of the time it is either slightly too narrow or too wide so I get gray space or the slider. I think this is happening when there is too much or too little text in the columns and the grid is trying to proportionately space the columns. Is there a way to prevent this? Is there some property of the dgv I can set to insure the grid is always filled?
0
I'm using Visual Studio 2017 with C#.
I want a user to input some letters into a textbox.  A model maps each letter to a number and returns the total.  how can I display the result (Total variable in the model) in a text area in the same view?

Home Controller
public ActionResult Cards()
        {
            return View();
        }
        public ActionResult Cards(CardModel C)
        {
            C.GetScore(C.Deck);
            return View();
        }

Open in new window


Cards View
@{
    ViewBag.Title = "Cards";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<h2>Cards</h2>

    <h2>Please enter a number</h2>

      First name: <input type="text" name="Deck"><br>
      <textarea id="TextArea1" rows="2" cols="20"></textarea>
    <input type="submit" value="Submit">

Open in new window


Model
 public class CardModel
    {
        public string Deck { get; set; }
        public int GetScore(string s)
        {
            int score = 0;
            int totalScore = 0;
            string individualCard = "";
            //loop through each letter in string and convert to a number.
           return Total
}
}

Open in new window

1
I'm practicing some online code examples for my potential interviews and I came across one code sample --> pass in 2 integers and bring back odd numbers between the range, inclusive.

Why is this bringing back 11? it shouldn't

Or, if I pass 96 and 97

List<int> list = new List<int>();

			int l = 3;
			int r = 9;

			List<int> t = Enumerable.Range(l, r).ToList();
			var oddNumbers = t.Where(num => num % 2 != 0);

			foreach (int i in oddNumbers)
				list.Add(i);

			var res = list;

Open in new window

0
I only need to extract certain data from a nested JSON file.

I'm able to do it using VBA and Python but I'm not having much luck using C# with NewtownSoft.JSON.

In the attached file the data I want to extract is  'type' and 'averageSpeedMetersPerSecond' for each node under 'state\tracks\3'.

Hope that makes sense, and apologies if I'm not using the correct terminology.

Oh, by the way here's where I am so far.
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TestJSON
{

    public class Test
    {
        public Newtonsoft.Json.Linq.JObject State { get; set; }
        public Newtonsoft.Json.Linq.JObject CachedValues { get; set; }
    }

    public class Track
    {
        public List<String> Path { get; set; }
        public string Type { get; set; }
        public double Speed { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (StreamReader file = File.OpenText(@"C:\Test\JSON Test\1550370300.json"))
            {
                JsonSerializer serializer = new JsonSerializer();

                Test test1 = (Test)serializer.Deserialize(file, typeof(Test));

                object tracks = test1.State;

                Console.Write(tracks);

                Console.ReadLine();

            }
        }
    }
}

Open in new window

1550370300.json
0
I'm using C# in Visual Studio 2017 and have a generic dictionary <string, Widget>
Without changing the widget class is it possible for the dictionary to store when each key value pair was added?
If it was added more than a minute ago then delete it or at least ignore it.
0
Hi

I need to create 2 separate XML files with some common elements in both but not the same not totally sure the correct term

My thinking is to create a parent class with the  common elements and the 2 children

The code bellow creates Example XML1
How do I separate the creation of a new post out I'm assuming I create 2 separate list<T>?

Please Note I'm not currently able to post actual code at present so I'm using previous examples  

           History history = new History();
            Post post = new Post()
            {
                Name = "Hello World",
                Url = "https://www.experts-exchange.com/questions/29135911/C-Merging-XML-files.html",
                Id = 45678,
                Number = 7,
                ImageCount = 99,
                DownloadedImagesCount = 99,
                Finished = "true"
            };
            history.Posts.Add(post)


    [XmlRoot(ElementName = "history", DataType = "string", IsNullable = true)]
    public class History
    {
        [XmlElement(ElementName = "post")]
        public List<Post> Posts { get; set; } = new List<Post>();
        public static History Load(string file)
        {
            var deserializer = new XmlSerializer(typeof(History));
            using (TextReader reader = new StreamReader(file))
            {
                return deserializer.Deserialize(reader) as History;
            }
        }

        internal static void Save(string file, History source)
 

Open in new window

0
How can I use c# to search the alternate data streams of files? I have XML in the alternate data streams of files (word, powerpoint, excel, text, pdf). I would like to search the XML n the alternate data streams to find a search term. The end result I'm hoping to get to is a windows desktop form that allows users to select a folder, enter a search term then click a button to search the alternate data streams of every file in that folder then return a list of the files that have the search term. Is this possible? Any help is appreciated.
0
I have the codes below to get full address from Geo API google. It works fine
but now I need to get address, city, state, and zip. And I have no idea how to get them in c#.
I read the following article as well but it is in javascript

https://stackoverflow.com/questions/10926420/how-do-i-get-just-the-postal-code-from-a-reverse-geocode-result 

        public static string GetAddress(string latitude, string longitude)
        {
            string locationName = "";
            string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false&key=AIzaSydsfBzalHtsdfsadfsadfasdfdsafTxZaIVQrePIK_Lfbv1QqPC_Xr5c", latitude, longitude);          
            XElement xml = XElement.Load(url);
            if (xml.Element("status").Value == "OK")
            {
                locationName = string.Format("{0}", xml.Element("result").Element("formatted_address").Value);                             
            }
            else
            {
                locationName = xml.Element("status").ToString();
            }
            return locationName;
        }

Open in new window

0
I'm using C# in Visual Studio 2017.  I came across this page outlining the performance of different data structures.
http://bigocheatsheet.com/#data-structures
Is there an article giving use cases for each structure?  At the moment I'm just interested in common structures like arrays, lists, dictionaries, stacks and queues.
Apart from inserting, updating, deleting and viewing records, what criteria are used when evaluating different data structures for a given project?

I saw this online which partially answers my question.  If space is not an issue when would I use a list as opposed to a dictionary?
When should I use something non standard like binary trees?

The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList<TKey, TValue> generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

SortedList<TKey, TValue> uses less memory than  SortedDictionary<TKey, TValue>.

SortedDictionary<TKey, TValue> has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for  SortedList<TKey, TValue>.

If the list is populated all at once from sorted data,  SortedList<TKey, TValue> is faster than SortedDictionary<TKey, TValue>.
0
I'm starting an MVC application in Visual Studio.NET C#.  If I create a new view and set it as the startup page, I get this message in Chrome.  Why do I get the message and how do I remove it.
My first aim is to put a textbox on the view and a button.  The user enters a number in the textbox, presses the button and the page displays double the number.


Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Home/Cards

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0
0
I am using C#.

I have a database field that is a date... an invoice date.

myRecordSet.Fields["finvdate"]

Is there anyway to convert this into a string so i can attempt to parse out the day portion?

string someString = new string(myRecordSet.Fields["finvdate"]);     FAIL

string someString = new string(myRecordSet.Fields["finvdate"].Value);  FAIL

string someString = new string(myRecordSet.Fields["finvdate"].Value.ToString());  FAIL

string someString = new string(myRecordSet.Fields["finvdate"].ToString());   FAIL
0
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

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