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 have a default image i want to use in C# application

I stored  the default image  in c:\crystal\images\defaultimage.png

I am trying to point to  it in my application as my default image but

somehow pointing  to the file with pbxPhoto.Image = ("C:\Crystal\Images\defaultimage.png");

 gives a syntax error (see attached)

Please note that i am getting the error in the code even before running

How can i resolve this error
ImagePath230319.PNG
0
Announcing the Winners!
LVL 13
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

I have the following code that returns one record. I need to convert this to a list and return single or more than one.

public string GetApproverEmail()
        {
            try
            {

                var user =  (from x in DB.tbl_User
                        where x.Approver == true
                        select x).Single();

                var email = (from x in DB.tbl_GlobalUser
                                  where x.ID == user.UserID
                                  select x.Email).Single();

                return (email);

            }

            catch
            {
                return null;
            }
        }

Open in new window


This sends the email:

public static void Approve(tbl_ChangeRequest cr)
        {
            User user = new User();
            Email mail = new Email("Approval");
            string Email = user.GetApproverEmail();

            string body = ("This is an automated email.<br />" + "" +
                "text here"" +
                 " is ready for approval. <br />" + "<br />" +
             );

            mail.SetBody(body, true);
            mail.AddTo(Email);
            mail.AddCC("");

            mail.Send();
        }

Open in new window

0
I have an asp.net web application with a grid.  One column has a bulleted list with displaytype as Hyperlink. It is databound. I return some folder paths in this list. If the path is a share on a server all works find as example 1.

In example 1 the spaces are replace by %20.

But for some reason in Example 2 when the actual drive letter is used the spaces are replaced by %2520 which then does not work.

1.file://server1/scanned/ASB/DE/AGOPSOWICZ,%20DANIEL/AGOPSOWICZ,%20DANIEL%202018%2011%2014


2.file:///Q:/ASB/DE/AGOPSOWICZ,%2520DANIEL/AGOPSOWICZ,%2520DANIEL%25202019%252002%252021


What causes this %2520 to happen? In example 1 with %20 the link works.

It looks like an encoding issue in the Bulleted list Hyperlink. It is adding the %2520 on the Example 2.

Thanks,

Roger
0
When I try to update a document exists on SOLR7 I got this message:

TransactionLog doesn't know how to serialize class java.util.UUID; try
implementing ObjectResolver?

With the stack trace:


{"data":{"responseHeader":{"status":500,"QTime":3},"error":{"metadata":["error-class","org.apache.solr.common.SolrException","root-error-class","org.apache.solr.common.SolrException"],"msg":"TransactionLog 
doesn't know how to serialize class java.util.UUID; try implementing 
ObjectResolver?","trace":"org.apache.solr.common.SolrException: 
TransactionLog doesn't know how to serialize class java.util.UUID; try 
implementing ObjectResolver?\n\tat 
org.apache.solr.update.TransactionLog$1.resolve(TransactionLog.java:100)\n\tat 
org.apache.solr.common.util.JavaBinCodec.writeVal(JavaBinCodec.java:234)\n\tat 
org.apache.solr.common.util.JavaBinCodec.writeSolrInputDocument(JavaBinCodec.java:589)\n\tat 
org.apache.solr.update.TransactionLog.write(TransactionLog.java:395)\n\tat 
org.apache.solr.update.UpdateLog.add(UpdateLog.java:524)\n\tat 
org.apache.solr.update.UpdateLog.add(UpdateLog.java:508)\n\tat 
org.apache.solr.update.DirectUpdateHandler2.doNormalUpdate(DirectUpdateHandler2.java:320)\n\tat 
org.apache.solr.update.DirectUpdateHandler2.addDoc0(DirectUpdateHandler2.java:239)\n\tat 
org.apache.solr.update.DirectUpdateHandler2.addDoc(DirectUpdateHandler2.java:194)\n\tat 
org.apache.solr.update.processor.RunUpdateProcessor.processAdd(RunUpdateProcessorFactory.java:67)\n\tat 

Open in new window

0
Our application built with C# and SOLR search.

One of my requirement to implement partial updates with SOLR.I am getting an error while posting JSON data into SOLR server.

Error Response from SOLR API:

{
    "responseHeader": {
        "status": 400,
        "QTime": 30
    },
    "error": {
        "metadata": [
            "error-class",
            "org.apache.solr.common.SolrException",
            "root-error-class",
            "org.apache.solr.common.SolrException"
        ],
        "msg": "Atomic document updates are not supported unless <updateLog/> is configured",
        "code": 400
    }
}

Open in new window

0
I'm getting below error while compiling the below code

HttpClient' does not contain a definition for 'DefaultRequestHeaders'
HttpClient' does not contain a definition for 'GetAsync'

Project details:
Microsoft Visual C# 2012
.Net framework 4.5.2
Windows service

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

var client = new HttpClient();
 client.BaseAddress = new Uri(ConfigurationManager.AppSettings["uri-path-port"].ToString());

 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           

Open in new window


HttpClient' does not contain a definition for 'DefaultRequestHeaders'
HttpClient' does not contain a definition for 'GetAsync'

To fix this issue I  have tried the below  form package manager console:

Install-Package Microsoft.AspNet.WebApi.Client

I got this error:

Install-Package : Unable to find package 'Microsoft.AspNet.WebApi.Client'.
At line:1 char:1
+ Install-Package Microsoft.AspNet.WebApi.Client
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
0
I'm writing a basic web API.  The code below is in the values controller and should put two rows from the data table into a JSON file.
How do I amend the code, so that it produces the file?
What URLs will work?

        public DataTable Get(string EmployeeName="Joe",string EmpCode="AR")
        {

                string ConnectionString = ConfigurationManager.ConnectionStrings["WebAPIDb"].ConnectionString;
                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 = "EmployeeTable";
                                sqlcmd.Parameters.AddWithValue("@Operation", "S");
                                sqlcmd.Parameters.AddWithValue("@FirstName", "Joe");
                                sqlcmd.Parameters.AddWithValue("@Empcode", "AR");
                                sqladp.SelectCommand = sqlcmd;
                                sqladp.Fill(dt);

Open in new window

0
I am pulling data from an API and I believe it is returned as a JSON string, how can I read certain data from the string ?  There are rows of data I want to loop through and put in a datatable, but can not figure out how to extract the data.

I have attached 3 files - the first 2 is the data I want to access, the third is the name of the columns.

Path to Column NamesWhere the data is - Label and Value are two fields inside I want to access.Path To Data
0
How to add a reference to Microsoft.Web.Management.Server reference in my c# project?
0
I choose to print numbers 1 to 5 in this code.  When I step through it using F11 I get to the line
return stval;

Open in new window

It goes to the end of the routine, but does not go back to the calling command  
printNatural(1, ctr);

Open in new window

Instead it goes back to  this line of code
return printNatural(stval + 1, ctr);

Open in new window

several time before it goes back to the static main method.
Why does it not go straight back to static main after
return stval;

Open in new window


using System;

namespace ConsoleApp10
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("\n\n Recursion : Print the first n natural number :\n");
            Console.Write("---------------------------------------------------\n");
            Console.Write(" How many numbers to print : ");
            int ctr = Convert.ToInt32(Console.ReadLine());
            // Call recursive method with two parameters.	
            printNatural(1, ctr);
            Console.Write("\n\n");

        }
        static int printNatural(int stval, int ctr)
        {
            if (ctr < 1)
            {
                return stval;
            }
            ctr--;
            Console.Write(" {0} ", stval);
            return printNatural(stval + 1, ctr);
        }
    }
}

Open in new window

0
Starting with Angular 5
LVL 13
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Hi

I'm extracting links from html using HtmlAgilityPack  but i'm getting a lot of unwanted rubbish

I have a list of wanted hosts how might I filter the links against this list?

using System;
using System.Xml;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

					
public class Program
{
	public static void Main()
	{
		var html =
        @"<body>
    <div class='content'>
      <div id='post_message_30829575'>
        <a href='https://example.com/foo/123adj'><img src='https://example.com/foo/123adj/thumb.jpg'></a>
        <a href='https://example.com/foo/bar'>Link to foo bar</a>
        <a href='https://wanted.com/foo/bar'>Link to foo bar</a>
        <a href='https://rubish.com/foo/bar'>Link to foo bar</a>
      </div>
    </div>  
  </body>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);
		string [] hosts = {"exasmple", "wanted"};

         var HTMLBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
            foreach (var Node in HTMLBody.DescendantsAndSelf())
			{
				var linkNodes = Node.Descendants("a");
				foreach (HtmlNode linkNode in linkNodes)
				{
					HtmlAttribute link = linkNode.Attributes["href"];
					HtmlNode imageNode = linkNode.SelectSingleNode(".//img");
                                       // Don't need images
					if(imageNode == null)
					{
						Console.WriteLine("Link value: {0}", link.Value);
					}
				}
			}
		
		
	
	}
}

Open in new window

0
I have searched on Google about creating view without controller but most of them shown me I can do it using redirect so I try out.

the result is because the app redirect so many time n it ends up it time out or generate error message.

if you have the same situation please show me how to handle this.

the reasons we don't want to use controller is because we will create many landing page from our web designer. and there is no need to generate any model, but we do want to use cshtml to do some server side work.

thanks
0
i have  @Html.Partial("~/Views/Shared/_ListingsSubEvent.cshtml", "13") on razor
how to capture the value(13) on _ListingsSubEvent.csthml?
0
What "transcribe wav file to text" locally installed (non-cloud) software recommendations do you have since I have about 10 .WAV files I want to save as text in notepad/etc and do not want to spend over $50 for everything ?

Examples
 1. https://www.youtube.com/watch?v=hp_hBuq7sys
 2. http://www.lrc.columbia.edu/free-technology-transcribing-audio-interviews-with-transcriber-and-audacity/

Below are some CLOUD solutions (I want non-cloud if possible for SECURITY reasons)
 1. https://www.ibm.com/watson/services/speech-to-text/
 2. https://cloud.google.com/speech-to-text/
0
(I don't know where to put this so I put in C#/ASP.Net category)..

For those of you who've been helping me and know I've been dealing with an abusive and moody manager for almost a year... I accepted an offer today.  I've been practicing my resignation since my manager blew up on me in January...over some silly SQL indentation... can you believe it?!...but now I'm not happy about it. Why is it so easy for companies to see good people come and go but so hard to dicipline a manager? (I'm the 3rd one leaving this company). Why is it so easy to see good people come and go but so hard to send a manager to training?

The position I accepted is a little outdated in technology. They said it's Web Forms and Crystal Reports but open to upgrades.  Another developer does Angular and web stuff. Someone else does other stuff. Solid company and the owner also spoke with me. Seemed like a really nice person and my future manager said he has no tolerance for bad behavior.

I had another potential offer that with more recent technologies but they were taking their time and they're like a startup. They've already had layoffs and the company has been bought out. I chose the solid company with a good 401K (I'm getting older and not younger :)) , 3 weeks of vacation and a little increase in my salary. I chose a manager over technology (I read an article on LinkedIn about it). They did say they're looking into AI and new stuff. I do side projects so I can keep up with newer technologies.
9
I'm writing a .NET Core application in Visual Studio 2017.
This code generates a list from a comma separated set of string values.  How can I unit test it?  I think my difficulty is that the list is of type card rather than a simple string.

 
//2H,3C should generate a list
//2H3C should generate an exception as there is no comma
//2H,2H should generate an exception as the cards are duplicated
//2H,JR,JR,JR should generate an exception as there are more than two jokers

CardApp.Controllers.CardsController ScoreTest1 = new CardApp.Controllers.CardsController();
            List<CardApp.Models.Card> Deck = new List<CardApp.Models.Card>();
CollectionAssert.AreEqual(new List <CardApp.Models.Card>(){ }, ScoreTest1.SetUpList( "2H,3C"));

Open in new window



        public List<Card> SetUpList(string s)
        {
            


                for (int i = 2; i < s.Length; i += 3)
                {
                    if (s.Substring(i, 1) != ",")
                    {
                        throw new Exception ( "Deck must consist of two digit card followed by comma");
                        
                    }
                }
            List<Card> cards = new List<Card>();
            foreach (string item in s.ToUpper().Split(',').ToList<string>())
            {
                Card temp = new Card(item);
                bool cardExists = cards.Any(x => x.Value == temp.Value && x.Type == temp.Type);
                if (!cardExists)
                {
                 

Open in new window

0
Hi,

I have following codes.
I have myCollection variable that contains all the Web elements.  I am using two paths using XPath and or('|') operator because I need different things from the objects that these two different paths gives.
From the elements from the first path(//div[@role='region' and //@my-label] ), I want to get Text properties.
From the elements from the second path(//button[@role='button' and //@my-label]), I want to get the values of 'my-label' attributes. (the Text properties for this elements are "")
After that, I want to put all these too myList<string>.
Obviously I am getting errors on my Linq query(at Select statement).
What's should I do to accomplish this?


public IReadOnlyCollection<IWebElement> myCollection => _driver.FindElements(By.XPath("//div[@role='region' and //@my-label]  | //button[@role='button' and //@my-label]"));

var myList = new List<string>();
myList = myCollection
                    .Select(a => a.Text or a => a.GetAttribute("my-label").ToString()) 
                    .Reverse() // Newest item first
                    .Where(a=>!String.IsNullOrEmpty(a))
                    .Where(b=>!String.IsNullOrEmpty(b))                              
                    .ToList();

Open in new window

0
Can someone help me with the logic of looping through an array.
I would like to identifying like strings in a specific location [i,2] and add the associated values in [i,3] and save the results into a new array or list.

Graphically trying to do this.

Example
Thanks for any assistance.

Regards,
Jed-
0
How can I convert a (Base 64) UTF16 string to a standard string  in vb (or C#)
0
Introduction to R
LVL 13
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Why is this answer correct?

Revenue for Q2 is 300. Cost is 250. So profit is 300,000-250,000 = 50,000 but then Q1 and Q3 are also the same.

h3.png
0
No way this is that hard but I've been doing all this math stuff all afternoon and my brain is fried....

X is gas price
Increased by 15% so  X * .15
the price is now 3.91 ..I'm missing something

h1.png
0
For this one...
There are 15 even days. 15 odd days in a month.
On Even days, doctor works for 7 hours
On Odd days , doctor works or 7:30 hours

Nothing jumps out at me to see why 4 hours is correct... not sure how to go about this one...


t5.png
0
for this one... this is how I went about it

From 12 AM to 5 PM... we lose 5 mins each hour so that's 165 mins = 2.75 hours. But this doesn't get 3:35... I'm missing some calculation.



t4.png
0
The answer is 25% decrease. From the graph, I eliminated the 4 answers because the graph for "food and beverages" and "services" has decreased.

Why is it 25%? For example, food & Beverages went from 60 Million to 50 Million and Services went from 20 million to 10 million. I wanted to say... what percentage of 50 million is less than 60 million...

t1.png
0
Why is the answer to this is 100?

That's 500 mins of free call in the grid... it's not 500 per min. One year is 12 months.... hmmm... I don't know how 100 is correct.

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