C#

93K

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

Hi,

I want to do order by in linq
if SortOrder is null then sorder by name in asecding order
If SortOrder is there then order by SortOrder.

Please advise how to set order by in my below query.
In below Query I am setting error at el.Element("SortOrder").Value as null object.

Error Below:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XContainer.Element(...) returned null.


even getting above error in
el.Element("Name").Value

XElement xml = XElement.Load(Server.MapPath(ConstantKeys.CountryCurrencyFilePath));
            IEnumerable<XElement> titleElements = from el in xml.Elements(elementName)
                                                  orderby el.Element("SortOrder").Value ascending, el.Element("Name").Value ascending
                                                  select el;

Open in new window



Sample XML below. You can see SortOrder element is available for AUD and AZN. But it is not available for others.
Please advise us on the query.

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Row>
    <Code>AFN</Code>
    <Name>Afghani</Name>
  </Row>
  <Row>
    <Code>AOA</Code>
    <Name>Kwanza</Name>
  </Row>
  <Row>
    <Code>ARS</Code>
    <Name>Argentine Peso</Name>
  </Row>
  <Row>
    <Code>AUD</Code>
    <Name>Australian Dollar</Name>
    <SortOrder>1</SortOrder>
  </Row>
  <Row>
    <Code>AZM</Code>
    <Name>Azerbaijan Manat</Name>
  </Row>
  <Row>
    <Code>AZN</Code>
    <Name>New Azerbaijan Manat</Name>
    <SortOrder>2</SortOrder>
  </Row>
</Root>

Open in new window


Regards,
0
Learn SQL Server Core 2016
LVL 12
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Need help calling the generic method.

We have a method 'DeserializeToModel' that takes in [a string (an encoded Json) and a reference type] and deserialized it into the reference type model.

public class DeserializedJsonToModel 
  {
      public T DeserializeToModel<T>(string encodedJson, T model) where T : class, new()
      {
          DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
          settings.UseSimpleDictionaryFormat = true; //This is needed to read in the dictionary in HospitalAffiliations class

          T deserializedModel = new T();
          MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(encodedJson));
          DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedModel.GetType());
          deserializedModel = ser.ReadObject(ms) as T;
          ms.Close();
          return deserializedModel;
      }
  }

Open in new window

 
 The problem is calling the generic method on line 49 in this unit test: 'SuperHero' is a type, which is not valid in the given context      
'SuperHero' is a type, which is not valid in the given context
Here's the test class:
    [TestClass]
    public class DeserializedJsonToModelTest
    {
        private SuperHero hero;
        private DeserializedJsonToModel deserializer;

        [TestInitialize]
        public void Setup()
        {
            hero = new SuperHero()
            {
                FirstName = "Barry",
                LastName = "Allen",
                HeroName =

Open in new window

0
I have the following method below and I'm having a hard time understanding what does the following notation mean... The following code is reading from a table and converting it to a variable just not sure why the 9?

requiredFields[9] == 'T',  why a 9?

public static GeneralSetupProgramJobParameter GetProgramJobParameters(
            GeneralSetupProgramJobParameter item,
            string reqdfields,
            string prodparam,
            string chngparam,
            string estutilfld,
            bool defaultStatus0For2ndPrgm
            )
        {
                var requiredFields = reqdfields.ToCharArray();
                var productionDefaults = prodparam.ToCharArray();
                var changeParams = chngparam.ToCharArray();
                var estUtilFields = estutilfld.ToCharArray();

                item.DefaultToStatus0For2ndProgram = defaultStatus0For2ndPrgm;

                item.ProgramJobRequiredFields = new ProgramJobRequiredFields
                {
                    IsRequiredDateSold = requiredFields[9] == 'T',
                    IsRequiredSalesPerson = requiredFields[11] == 'T',
                    IsRequiredSource = requiredFields[10] == 'T',
                    IsRequiredSize = requiredFields[16] == 'T',
                    IsRequiredRoute = requiredFields[14] == 'T',
                    IsRequiredCancelDate = requiredFields[12] == 'T',
                    IsRequiredCancelReason = requiredFields[13] == 'T',
                    

Open in new window

0
I need to get the selected value of a listview that has 2 columns. I think this should be simple, but I am not getting the value I need. I have a winforms application, in C#. I populate the list view like this:
foreach (var item in documents)
{
	lstMyList.Items.Add(item.Name + "\t\t" + item.Value + "\t\t");
}

Open in new window

It displays the list with the values side by side. When I select a value from the list, I want to capture just the item.Name value. How can I do that?
0
Hello Experts,
I have a Onclick event attached to button which should open a window (on Javascript), which is working just fine.  But, when I click on another URL same window opens up, which is not related to the URL at all.  Any idea what could be going on?  Please try to help.  Thank you in advance.

Note:  Due to company's restrictions I will not be able to post the code here.

Thank you!
0
Hi there, I need a regex expression to extract a uk phone number from a string.
This is with a view to detecting phone numbers in paragraphs of text.
There are plenty of examples out there to verify UK phone numbers as being a regex match but I cannot find anything which will do so returning the match from within a string.
Uk phone numbers are 10 or 11  numbers long with a 0 at the beginning.  

This regex is an example of a regex which matches a phone number, but cannot handle leading or trailing text.  Can somebody help perhaps in modifying it so it can still pick out the numbers in a string whilst ignoring leading/trailing text.  

^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$

Open in new window


Thanks,
0
Hello Experts,
In a web page, when I click on a link, it fails.  Upon doing further research I found that I pass Line 1, but it changes to Line 2 automatically at the Run Time.  Any idea what is going on?  Please try to help.  Thank you very much in advance.

Line 1: http://abc.com/DataSources/APP DB/IDocument?AutoLogoutOnClose=True&AppName=TKT_DET&TktId=333333
Line 2: http://abc.com/DataSources/APP%20DB/IDocument?AutoLogoutOnClose=True&amp;AppName=TKT_DET&TktId=333333

Thank you!
0
Hi,

I am processing about 50,000 user IDs using about 10 TPL multithreads. The first 20,000 IDs process fast and fine (About 10,000 to 12,000 IDs in the first hour) but than it slows down to about 2,500 IDs per hour which doesn't make sense to me. I use a persistant LDAP connection by connecting to the NativeObject from my main thread, so even though I am disposing of the DirectoryEntry after each ID the connection should persist, correct? I chose to dispose of the DirectoryEntry after each ID to control memory.

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://rootDSE", null, null, AuthenticationTypes.FastBind);
object rootObject = rootEntry.NativeObject;

Open in new window


Also i am adding info to a Database as a troubleshooting measure to see where the issue may begin, the slowness issue was occurring before using the database.

Can someone please look at my code and tell me what i may be missing?

Thanks

foreach (String ID in IDs)
        {
            DateTime start = DateTime.Now;

            lock (DBLock)
            {
                try
                {
                    OleDbCommand myCommandInsert = new OleDbCommand();
                    myCommandInsert.Connection = myConn;
                    myCommandInsert.CommandText = "INSERT INTO Main VALUES (" + "'" + ID + "'" + "," +
                                                                                "'" + DateTime.Now.ToString() + "'" + "," +
                                            

Open in new window

0
If a user launches my application from a shortcut how do I get the path of the shortcut that was used to execute the application? It's easy enough to get the directory of the application itself. All of the following provide useful information:
Directory.GetCurrentDirectory();
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

Open in new window

However, let's say that my executable is on a share, let's say the path is \\MyServer\D\SharedFolders\MyApplication\MyExe.exe. Now, let's say the user creates a shortcut in C:\Users\[username]\Documents\My Shortcuts\MyExe - Shortcut. If the user double clicks the shortcut all of the above will return the UNC path. Is there a way I can get the path of the actual shortcut that was used to launch the executable?
0
I've created a visual studio 2017 with two webform projects in C#.  I've zipped it up and its over 40mb.  How do I make it smaller?  My actual code is only about 200 lines, but there are so many packages and scripts etc.  I'm working with C#, but am not sure if the same would apply to vb projects.
0
Amazon Web Services
LVL 12
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

From the following extract from a source input stream, i need to use c# regex to extract a match collection of each matching block of code between the ##if WORD ## and the matching ##endif WORD ##

##if textbox ##
		<tr>
			<td>Textbox description here, could be anything:</td>
			<td>##textbox##</td>
		</tr>
##endif textbox ##
		<tr>
			<td>multilinetextbox</td>
			<td>##multilinetextbox##</td>
		</tr>
##if staticdropdown ##
		<tr>
			<td>staticdropdown description here, could be anything or nothing or something else alltogether:</td>
			<td>##staticdropdown##</td>
		</tr>
##endif staticdropdown ##

Open in new window


The returned match should include the ##if and end ##endif blocks as below...

Match 1:
##if textbox ##
		<tr>
			<td>Textbox description here, could be anything:</td>
			<td>##textbox##</td>
		</tr>
##endif textbox ##

Open in new window


Match 2:
##if staticdropdown ##
		<tr>
			<td>staticdropdown description here, could be anything or nothing or something else alltogether:</td>
			<td>##staticdropdown##</td>
		</tr>
##endif staticdropdown ##

Open in new window


I have been testing various online regex testing sites to see I I can get what I need but always end up with the match being from the very first ## if WORD ## to the very last ##endif OTHERWORD ## construct

Any help gladly accepted :D
0
I have a C# WPF list box, lstMaintTechs that I have been trying to sort alphabetically.  I'm new to C# and WPF and just can't seem to make it happen.  Here is my code:

public List<tblMaintTech> Tech { get; set; }

        private void bindlistbox()  //called when window is initiallized
            
        {
            ProdTrackEntities pte = new ProdTrackEntities();
            Tech = pte.tblMaintTechs.ToList();
            DataContext = Tech;
        }

Open in new window


And here is the XAML for the listbox:
<ListBox x:Name="lstMaintTech" ItemsSource ="{Binding}" SelectedValuePath="MaintTechName" DisplayMemberPath="MaintTechName" HorizontalAlignment="Left" Margin="42,17,0,0" VerticalAlignment="Top" Width="203" FontSize="20" Height="465" IsSynchronizedWithCurrentItem="False" SelectionChanged="lstMaintTech_SelectionChanged" />

Open in new window


Any help would be great.  Thanks in advance!
0
I have created a GeneralSetupCompanyView Model inside my GetViewModel but I'm getting the following error when I assign my property CountryOption to the value CountryOptions = GetViewModelCountryOptions(vm.SelectedCountry).  
This GeneralSetupCompanyView is in a different namespace than the namespace ServiceAssistant.Areas.Parameters.Controllers.

My question is do I need to move my Service.Assistant.Model.Service.Picker.Item to the namespace where my GeneralSetupCompanyreside  or how should I correct this line of code:
CountryOptions = GetViewModelCountryOptions(vm.SelectedCountry),

Cannot implicitly convert type "System.Collection.Generic.List<Service.Assistant.Model.Service.Picker.Item>'to 'System.Collections.Generic.List<Systems.Models.SelectPicker.Item>'

namespace ServiceAssistant.Areas.Parameters.Controllers
{
    public class CompanyGeneralSetupController : BaseController
    {
        // GET: Parameters/CompanyGeneralSetup
        public ActionResult Index()
        {
            var employee = LoggedInUser;
            canView = null;
            if (!canView)
            {
                return RedirectToAction("Index", "Parameters", new { area = "Parameters" });
            }

            var viewModel = GetViewModel(employee);
            return View(viewModel);
        }

        private GeneralSetupCompanyViewModel GetViewModel(Employee employee)
        {
          
            var parameters = 

Open in new window

0
I have a SweetAlert with a Cancel option.  My javascript has the isConfirm function and works correctly if isConfirm is true.  It just bypasses the code for the else statement. Any thoughts?

 swal({
                title: "Add New Action/Task",
                text: "This will add a new Action/Task to the stored Action List for future use.  If you do not wish to save this Action for later, click Cancel and choose Other.",
                type: "warning",
                showCancelButton: true,
                cancelButtonText: "Cancel",
                buttons: true,
                dangerMode: true,
                closeOnConfirm: true,
                closeOnCancel: true,
                confirmButtonText: "Yes"
            },
                function (isConfirm) {

                    if (isConfirm) {
                        CM.disabled = false;
                        CM.style.backgroundColor = "white";
                        actionOther.style.backgroundColor = "white";
                        actionOther.placeholder = "Enter New Action/Task";
                    }

                    else {
                        CM.disabled = false;
                        actionDropdown.value = "Other";
                        actionDropdown.text = "Other (Enter Other Action/Task)";
                        actionOther.placeholder = "Enter Other Action/Task";
                    }

                }.bind(this));

Open in new window

1
I have an asp.net web application, with master pages , aspx pages and also user control (ascx ) pages. sample code below

I have a function in menu.ascx , user control page, which needs to fire a function in default.aspx page.
is there a way to do this ?

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="masterpage.Site1" %>  
<%@Register Src=~/menu.ascx” TagName=”menu” TagPrefix=”uc1” %>
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <asp:ContentPlaceHolder ID="head" runat="server">  
    </asp:ContentPlaceHolder>  
</head>  

<body>  
    <div id="navigaion">
         <uc1:menu ID=”menuControl” runat=”server” />
    </div>
    <div id="maincontent">  
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">   </asp:ContentPlaceHolder>  
    </div>  
</body>  
</html>
0
I have a .Net Framework (4.6.1) class library project (call it A).
Then I have a UWP app (call it B), and I want to use the code in A by referencing to A from B. But that is not possible. UWP apps are .Net Core and not compatible with .Net Framework.

So I created a .Netstandard 2.0.3 class library project (call it C), to be a proxy between A and B. I now reference from A (the UWP app) to C (the .Netstandard class library), and then from C to B (the .Net framework class library).

Everything compiles now, but when I run/debug the UWP app in Visual Studio I get the following error originating from the code in A:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.'

System.Web.ApplicationServices is a .Net Framework reference in A, and is not compatible with B. I was hoping to get around this by using .Net standard and C as a proxy between A and B.

Any suggestions on how to fix this?

Code examples won't help here, the code works fine, but not the integration between the various technologies.
0
In the below example code using ASP .NET Core 2.1, I am dynamically adding a table row when the add button is clicked. The row contains 3 input boxes and one button (a minus symbol which removes the row when clicked). I'm struggling to find the best way to handle the deletion since I want to preserve model-binding when the form is posted. The rows in this table should populate List<People> when the form is submitted.

Is there a more elegant way to handle this besides re-indexing each row every time a delete happens? Any examples I can review will be much appreciated.


Initial view from HttpGet controller
<div>
	<table class="table table-condensed" id="people-list">
		<thead>
		<tr>
			<th>First Name</th>
			<th>Last Name</th>
			<th>Email Address</th>
		</tr>
		</thead>
		<tbody>
		@for (var i = 0; i < Model.PeopleList.Count; i++)
		{
			<tr>
				<td>
					@Html.HiddenFor(m => Model.PeopleList[i].FirstName)
					@Html.TextBoxFor(m => Model.PeopleList[i].FirstName, new { @class = "row-index form-control"})
				</td>
				<td>
					@Html.HiddenFor(m => Model.PeopleList[i].LastName)
					@Html.TextBoxFor(m => Model.PeopleList[i].LastName, new { @class = "form-control" })
				</td>
				<td>
					@Html.HiddenFor(m => Model.PeopleList[i].Email)
					@Html.TextBoxFor(m => Model.PeopleList[i].Email, new { @class = "form-control" })
				</td>
				<td>
					<button class="btn btn-default" id="remove-person-@i"><i class="glyphicon glyphicon-minus"></i></button>
				

Open in new window

0
I have a C# application that needs to connect to sqlserver and postgresql

I have been able to connect it to sqlserver and it works and the connection string is shown below

<add name="Tournaments" connectionString="Server=CHRISTINESPC;Database=Tournaments;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>

I have tried a number of options for postgresql without success

Can anybody kindly help to specify what  the postgresql  connection string equivalent is

Notes:

CHRISTINESPC is my servername as displayed in sqlserver  management studio thou I am open to using an IP address
Tournaments my Database name in both sqlserver and postgresql databases

Thanks

Oluwole
0
I would like to get some feedback on what is the best way to create a model from this screen representation that I have attached bellow. I created a class GeneralSetupCompanyParame and I'm not sure how I should declare each property that I have circled in yellow in my screenShot. The one for the English,Spanish, French Description...

I'm just looking for the best representation. I started creating my company class, I'm just missing how I will set my property for the English,Spanish and French Description.

 public class GeneralSetupCompanyParameters
    {

         public class SMTPSettings
        {
            public string CommonSMTPSettings { get; set; }
            public string SMTPServer { get; set; }
            public int SMTPPort { get; set; }
        }
        
        public string CountryName { get; set; }

        public string ServiceYear { get; set; }
        public string QuickNote { get; set; }
        public bool AllowFutureSaleDates { get; set; }
        public bool ForcePWComplexity { get; set; }
        public bool AppointmentNotification { get; set; }
        public bool LimitPastSaleDates { get; set; }
        public int LimitPastSaleDatesDay { get; set; }
        public bool ForcePeriodicPWChanges { get; set; }
        public bool LockCallLogEntries { get; set; }
        public string EveryDay { get; set; }
        public bool LimitPastCancelDates { get; set; }
        public string LimitPasCancelDatesDays { get; set; }
        public bool 

Open in new window

0
HTML5 and CSS3 Fundamentals
LVL 12
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

I'm trying to use iMacros with C# in Visual Studio 2013
my code:

using iMacros;

...

{
           iMacros.AppClass imApp = new iMacros.AppClass(); // Object aanmaken van de namespace iMacros class AppClass
            iMacros.Status imStatus;
}

Open in new window


got an error:

interop type iMacros.AppClass cannot be embedded.

What could I do to resolve this?
0
I need some examples of how to do advanced grouping and formatting using GemBox and C#.
We use MVC

Thank You!
0
I want to implement the Webhook APIs from zoom.us using ASP .NET Core 2.1 Web API, but I'm not sure how to configure this to test in Visual Studio 2017 IDE. Since it requires me to configure an application URL where it will send callbacks to my APIs, how can I set this up locally for debugging when IIS Express uses localhost as the site name? Will I need a public facing webserver/site to publish my code to?
0
Hi,

I am trying to open an NSF file using interop.domino.dll c# and able to load all messages but there is some character encoding issue due to other languages as shown in below image



there any way to fix this encoding issue?

Thanks in advance!!!

Kind Regards
Geeta Malik
0
I am writing code and implementing the code sample in the below url from Silicon Expert.

https://www.siliconexpert.com/apidocs/content/list-part-search

The sample code produced error:  "The request was aborted: Could not create SSL/TLS secure channel."

Searching I found that the below code should be implemented.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AllwaysGoodCertificate);

Open in new window

Below is the full example.  
String username = "MyUserName";
String password = "MyPassword";

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AllwaysGoodCertificate);

string url = "https://app.siliconexpert.com/SearchService/search/authenticateUser?login=" + username + "&apiKey=" + password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
CookieContainer cookieContainer = request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
String searchUrl = 

Open in new window

0
I have a C# WPF datagrid displaying Work Orders from a SQL database view upon on which you select a row and click a select button (btnSelectWO)  The unique Work Order ID is then passed to a new window named EditWO as WONbr.  The datasource for the new window is a different than was used in the datagrid, CollectionViewSource tblMaintNotesViewSource.  My question is how can I filter or query the new window to show the record of the unique ID (WONbr) that has been passed to it so the user can modify the record?

I have set up this class but don't really understand what to do with it:
class WorkOrder
        {
            string Extruder { get; set; }
            string Shift { get; set; }
            string MaintNotes { get; set; }
            DateTime Date { get; set; }
            string Name { get; set; }
            int ID { get; set; }
            DateTime MaintDate { get; set; }
            string MainPerformed { get; set; }
            string MaintTech { get; set; }
            bool CloseOrder { get; set; }
            string AssignedTo { get; set; }
            string Instructions { get; set; }
        }

Open in new window


I'm new to C#, I've only been working with it for a few weeks.  I'm hoping this has to be pretty easy and straightforward, all I need is a kick in the right direction.

Thanks in advance for your help!
Jeff
0

C#

93K

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