C#

91K

Solutions

24K

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 Experts!

Need your help updating LINQ query.

The LINQ query should return a distinct record of locationId and phonenumber.
Then which need to extract locationId and phonenumber and store it in local variables.

SQL Query:

SELECT DISTINCT  
       personlocation.LocationID,
       phone.PhoneNumber
FROM dbo.personProducts pp
     INNER JOIN dbo.personPhonesLocations phoneLocation ON pp.personLocationRecID = phoneLocation.personLocationRecID
     INNER JOIN dbo.personLocations personlocation ON pp.personLocationRecID = personlocation.personLocationRecID
     INNER JOIN dbo.Phones phone ON phoneLocation.PhoneID = phone.PhoneID
     INNER JOIN dbo.PhoneTypes PhoneTypes ON pl.PhoneTypeID = PhoneTypes.PhoneTypeID
WHERE pp.PersonNumber = 'ABC123'
      AND PhoneTypes.PhoneTypeName = 'Contact Number'

Open in new window


C# method:
var personPhone = (from pp in dataContext.personProducts
from phoneLocation in dataContext.personPhonesLocations
from personLocation in dataContext.personLocations
from phone in dataContext.Phones
from phoneType in dataContext.PhoneTypes
where pp.PersonNumber == "ABC123" && phoneType.PhoneTypeName == "Contact Number"
select new
{
LocationId = personLocation.LocationID,
phonenumber = phone.PhoneNumber
}).Distinct();


if (personPhone != null)
{
    string locationId = ???; <-- need help
    string phonenumber = ??  <-- need help

}

Open in new window


TIA!
0
[Live Webinar] The Cloud Skills Gap
LVL 4
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

First and foremost, I appreciate everyone who has taken the time to help me out.

Task:
1.
This final code challenge will require you to use almost everything we've covered in this course. You’ll write a program to celebrate completing this course by printing “Yay!” to the screen a given number of times.
Write a program that:
Prompts the user to enter the number of times to enter “Yay!”. I've done this for you. Leave this as it is.
Prints “Yay!” to the screen that number of times (Hint: You’ll need a loop for this. You’ll also need to keep track of how many times the loop has run).
You can print them all on the same line or on separate lines.

2. Add input validation to your program by printing “You must enter a whole number.” if the user enters a decimal or something that isn’t a number. Hint: Catch the FormatException.

I tried all of those solutions but can't seem to get the loop to function. Here is my revised version.

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
       
            a = 0;
            Console.Write("Enter the number of times to print \"Yay!\": ");
           
            try{
                var x = int.Parse(Console.ReadLine());
                Console.WriteLine(x);
               
            while(a < x)          
                    {
                    Console.WriteLine("Yay!");
                    a++;
                    }
               
0
Using Winforms C# SQL Server

Can a dataGridView be used unbound to enter int values for calculation purposes and then insert those values into a database table after?
I need to enter package data such as Pieces, Length, Height, Width, DimFactor on either one row or multiple rows. e.g. Length * Width * Height / Dim Factor.

All the example I found refer to bound data.

Is a dataGridView the best option for this?
0
I have a function in an application that supplies  a string which is actually 3 strings with null separators.
This is rather frustrating as I could not even see the last 2 strings in the debugger.

I now need to do a string replace but this fails as the string I need to replace resides in the 2nd of the internal strings after the first null (\0).

Is there an easy way to split the string based on the null character or even better a string replace function that will work with a string constructed this way?
0
I had this question after viewing Looking for a new laptop.

I'm looking at Lenovo X1 that "Experienced Member" (I love the username :)) suggested (here is the link http://www3.lenovo.com/ca/en/laptops/thinkpad/thinkpad-x/X1-Carbon-5th-Generation/p/22TP2TXX15G)

I wonder if Amazon has it. I looked and one came up.

Should I choose "Windows Home 10" Or "Pro"? this is the screenshot
laptop
0
I'm looking to buy a new laptop. I want it to be light and to use for .Net development. It needs to be light.

On my current laptop, I have:  VS 2013 and VS2015 (community), SQL 2014 and SQL 2016 (developer editions)

1. No Toshiba. I already have one and don't like it. It's not for development.  I got it maybe 4 yrs ago.

2. I have a gaming laptop. It's MSI but it's so heavy and running out of disk space when I installed SQL 2016.

3. At work, we have Dell laptops. Seems like a good laptop but screen is too small. At my previous job, my coworker had Surface but again, the screen was too small. I think 15 inch screen would be good.

4. I know I need SSD and i7 processor
Is this a good one? Any recommendations?
Dell Latitude E7470 Business Ultrabook 14 Inch i7-6600U 16GB DDR4 Windows 10 Pro (256G)
1
I get this error at this part// string iDetailID = detail.EventDetail_ID.ToString(); // how do I solve it??
 protected void btnAdd_Click(object sender, EventArgs e)
    {
        string iDetailID = detail.EventDetail_ID.ToString();
        ShoppingCart.Instance.AddItem(iDetailID, detail);

        int ddlAmount, participants, itemNr;
        if (ValidateInput(out ddlAmount, out participants, out itemNr))
        {
            l1.Text = "";
            SetCookie();
            UpdateEventParticipantes(ddlAmount, itemNr);
            Response.Redirect(string.Format("Detail.aspx?id={0}", itemNr));
        }
    }

Open in new window

0
This must have already been solved by now as it's such a common problem.

A program saves its window positions. User was running on a dual monitor computer. User then moves to a single monitor computer, runs program, window positions are restored, and windows are no longer visible, being positioned way off on the second monitor which now doesn't exist.

How can my program determine if a restored window is not positioned on a real screen (it's positioned off the screen), and how can the program determine a nice place to position the window if it needs repositioning to the user's existing screen?

[As a side note: I noticed if I turn off my 2nd monitor the operating system repositions all the windows that were on my 2nd monitor back to my 1st monitor.]

(I'm programming in C#. I'm hoping to avoid resolving a problem someone else has already solved.)
0
I have an older website that build the home page by using an .aspx page as a frame, that includes other .aspx pages to make up the entire page. For example it is made up of about 4 different .aspx pages (i.e.: topMenu.aspx, leftPanel.aspx, righPanel.aspx, footer.aspx). These pieces are added by use of an include statement, into the HomePage.aspx.

  <!--leftPan -->
        <!--#include file ="../includes/leftPanel.aspx"-->
  <!--leftPan close -->

This is working but I need to make some changes to one of the included pages and I also need to add some C# code into the page. I've attempted to do this, based on my limited knowledge of this,  but am getting the following error:

Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30205: End of statement expected.

Source Error:


Line 1:  <Script Runat="Server">
Line 2:  		private void ibSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
Line 3:  		{
Line 4:  			// Get search terms


Source File: E:\Sites\Intranet\includes\leftPanel2.aspx    Line: 2


Show Detailed Compiler Output:

Show Complete Compilation Source:


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1087.0 

Open in new window


my code is below:

<Script Runat="Server">
		private void 

Open in new window

0
I am running some queries in Powershell.

I have created a function that returns an object I can use foreach (hence the return ,$table)
I first obtain a sql reader and load a data table with the returned recordset.

$rdr = $command.ExecuteReader()
          
 $table = new-object “System.Data.DataTable”
 $table.Load($rdr )
    
  return ,$table

Open in new window


The issue is that when iterating through the results I cannot perform an additional calls $command.ExecuteReader() even if I create a new command object and set the query text for that new command object.

I get the following error when I try: "There is already an open DataReader associated with this Command which must be closed first."

So I tried to close the reader after loading the data table

$rdr = $command.ExecuteReader()
          
 $table = new-object “System.Data.DataTable”
 $table.Load($rdr)
 $rdr.Close()

  return ,$table

Open in new window


With the data table filled and returned by the function, why can't I close the reader and then make a subsquent call to $command.ExecuteReader() ????
0
Free Tool: SSL Checker
LVL 9
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Still pretty green to MVC and need some guidance on how to accomplish what was so simple in web forms. I have a dropdown filled with names from a database. Each of the records that contains those names, also contains an ID. On the same view, I have a label. What I want to do, is change the value of the label when the dropdown selection changes. A simple, static example of how to do this would be great. At the very least, I'd like to just be pointed in the right direction.
0
1 error saying
Feature 'interpolated strings' is not available in C# 5.  Please use language version 6 or greater.
here is the code!!
 protected void SetCookie()
    {
        if (Request.Cookies["aa"] != null)
        {
            Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|";
        }

        Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + $"{lblTitle.Text},{lblPrice.Text},{lblDate.Text},{lblLocation.Text},{lblStartTime.Text},{lblEndTime.Text},{lblParticipants.Text},{lblDescription.Text},{lblItemNr.Text},{imgEvent.ToString()}";
        Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
    }

Open in new window

0
I get the below error when trying to reference the AspNetUserClaim table in my MVC C# solution. From other articles I have read you get this when you have multiple classes with the same name. I check in my Object Browser and all of that and simply cannot find any other class in my project with this same name. If I remove the only class with this name away, it cannot find that class. Any suggestions on how to debug this?

Schema specified is not valid. Errors: \r\nMultiple types with the name 'AspNetUserClaim' exist in the EdmItemCollection in different namespaces.  Convention based mapping requires unique names without regard to namespace in the EdmItemCollection.
0
If user selects 5 on ddl and only 4 event participants are displayed, there will be a label asking user to select qty that is lower!! Now, when I click the button nothing changes and there is also a line underlining eventParticipants.
- The end of the cookies line are red too, and I think there is a problem with the image.url part?
code behind for the button
  protected void btnAdd_Click(object sender, EventArgs e)
    {
        var id = Convert.ToInt32(lblItemNr.Text);
        SqlConnection con = new SqlConnection(_connStr);
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        SqlCommand cmd1 = con.CreateCommand();
        cmd1.CommandType = CommandType.Text;
        cmd1.CommandText = "update EventDetail set eventParticipants=eventParticipants-" + ddlAmount.Text + " where EventDetail_ID=" + id;
        cmd1.ExecuteNonQuery();
        Response.Redirect("Detail.aspx?id=" + id.ToString());
        //below are the codes with problems (eventParticipants)...
        if(Convert.ToInt32(ddlAmount.Text) > Convert.ToInt32(eventParticipants))
        {
            l1.Text = "please enter lower quantity";
        }
        else
        {
            l1.Text = "";

            if (Request.Cookies["aa"] == null)
            {
                Response.Cookies["aa"].Value = lblTitle.Text.ToString() + "," + lblPrice.Text.ToString() + "," + lblDate.Text.ToString() + "," + lblLocation.Text.ToString() + "," + 

Open in new window

0
If there is 0 participants available, I want a label saying 'no available participants for this event' so the user cannot select qty from dropdownlist!! But there is this error

   int qty;
    int id;
    protected void Page_Load(object sender, EventArgs e)
    {
        FillPage();
        qty = get_qty(id);
        if (qty == 0)
        {
            lblParticipants.Visible = false;
            ddlAmount.Visible = false;
            btnAdd.Visible = false;
            l2.Text = "no available participants for this event";          
        }
    }
   public int get_qty(int id)
    {
         id = Convert.ToInt32(lblItemNr.Text);
        SqlConnection con = new SqlConnection(_connStr);
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from EventDetail where id=" + id + "";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            qty = Convert.ToInt32(dr["eventParticipants"].ToString());
        }
        return qty;
    }  

Open in new window

0
Hi All,

I have developed an application using C# (Visual Studio) which runs without issue on my Windows 10 development PC. However, when I copy the application to its intended target PC and run it (Server 2012 R2), I get an exception informing me that a file or assembly could not be loaded:

************** Exception Text **************
System.IO.FileLoadException: Could not load file or assembly 'Microsoft.SqlServer.ConnectionInfo, Version=13.100.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))
File name: 'Microsoft.SqlServer.ConnectionInfo, Version=13.100.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' ---> System.ArgumentNullException: String reference not set to an instance of a String.
   at System.Reflection.RuntimeAssembly.GetResource(RuntimeAssembly assembly, String resourceName, UInt64& length, StackCrawlMarkHandle stackMark, Boolean skipSecurityCheck)
   at System.Reflection.RuntimeAssembly.GetManifestResourceStream(String name, StackCrawlMark& stackMark, Boolean skipSecurityCheck)
   at System.Reflection.RuntimeAssembly.GetManifestResourceStream(String name)
   at NewClientInstall.fmMain.<.ctor>b__3_0(Object sender, ResolveEventArgs args)
   at System.AppDomain.OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
   at NewClientInstall.fmMain.rolesAndPermissions(Boolean training)
   at …
0
I have the following string:

AB=3000 PART DESCRIPTION

I need to replace the 3000 with another number, but in order to find the 3000 I have to look for AB=

Then if 3000 needs to change to 3050, how would I do that?  It should read when done:
AB=3050 PART DESCRIPTION
0
Hi Team,

I am having a text file having pipe separated string values. The issue is getting string within the string as shown below. I am looking for a regular expression or some solution to remove that quotes as shown in the desired text below.

Existing: "This string is ok."|"This is an example with a "C" double quoted grade in middle."|"Next line"
Desired: "This string is ok."|"This is an example with a C double quoted grade in middle."|"Next line"

Looking forward to hearing from you.
0
I have the following if statement but need to add else when the case 12,15,18,22 is not I only need to show the OutTracking and InTracking currently now it shows nothing if I have other than case 12,15,18,22.  I need to show without a hyperlink and plain text

[Rule("r100")]
        public void r100Implementation(string OutTracking, string OutTrackingAlias, string InTracking, string InTrackingAlias)
        {
            if (OutTracking != null)
                switch (OutTracking.Length)
                {
                    case 12:
                    case 15:
                    case 22:
                        // fedex
                        UpdateFieldValue("OutTrackingAlias", "<a href=\"https://www.fedex.com/fedextrack/?cntry_code=us&tab=1&tracknums="
                        + OutTracking
                        + "&clienttype=dotcom\" target='_blank'>"
                        + OutTracking
                        + "</a>");
                        break;
                    case 18:
                        // UPS
                        UpdateFieldValue("OutTrackingAlias", "<a href=\"http://wwwapps.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1="
                        + OutTracking
                        + "&clienttype=dotcom\" target='_blank'>"
                        + OutTracking
                        + "</a>");
                        break;
                }
               

Open in new window

0
Get HTML5 Certified
LVL 9
Get HTML5 Certified

Want to be a web developer? You'll need to know HTML. Prepare for HTML5 certification by enrolling in July's Course of the Month! It's free for Premium Members, Team Accounts, and Qualified Experts.

1. When I click edit, I have to click it twice in order for the edit to work
2. Then shows the update, but all the items are not shown and when I click update -> it says 'result = det.EventDetailUpdate(int.Parse(id), int.Parse(tid), tname, tdate, decimal.Parse(tprice), tdesc, tlocation, tstart, tend, timage, int.Parse(tparticipants)); 'input string is not in correct format
what I did to update!!
   protected void abind()
    {
        List<EventDetail> detList = new List<EventDetail>();
        detList = aDet.getAllEventDetail();
        gvDetail.DataSource = detList;
        gvDetail.DataBind();
        //   ViewState["grdDetailsDataSource"] = (List<EventDetail>)gvDetail.DataSource;
    }  protected void gvDetail_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetail.EditIndex = e.NewEditIndex;
     //   abind();
    }
    protected void gvDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetail.EditIndex = -1;
      //  abind();
    }
    protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int result = 0;
        EventDetail det = new EventDetail();
        GridViewRow row = (GridViewRow)gvDetail.Rows[e.RowIndex];
        string id = gvDetail.DataKeys[e.RowIndex].Value.ToString();
        string tid = ((TextBox)row.Cells[2].Controls[0]).Text;
        string tname = ((TextBox)row.Cells[3].Controls[0]).Text;
        string tdate = ((TextBox)row.Cells[4].Controls[0]).Text;
 

Open in new window

0
I have an application which uses the following code to import a powershell snapin (left out exception handling for brevity!!):

public static RunspaceConfiguration MyRunspaceConfiguration
public static Runspace MyRunspace = RunspaceFactory.CreateRunspace(MyRunspaceConfiguration)
MyRunspace.Open();
MyRunspace.AddPSSnapin("WMware.VimAutomation.Core", out CustomPsException)

Open in new window


This works fine, however with a recent update to VMware software the use of snapins has been deprecated and the now modules are used instead. The advice from VMware is to use the following (in powershell):

Get-Module –ListAvailable VM* | Import-Module

The problem I have is I don't know how to achieve this line within my C# application runspace - any ideas?
0
I would like in my Visual Studio vb.net or c# project a way to link to code methods that it impacts. Is this possible in Sandcastle?
0
Dear Sir/Madam

What are the possible condition for 9 checkbox, please let me know

thanks in advance
0
eg. I have 20 participants. When I select 2qty and click the button, it is supposed to have 18 participants!! However now when I click the button, the qy changes to 0 , and all the other participants no. for other events will change too..
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var id = Convert.ToInt32(lblItemNr.Text);
    SqlConnection con = new SqlConnection(_connStr);
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        SqlCommand cmd1 = con.CreateCommand();
        cmd1.CommandType = CommandType.Text;
        cmd1.CommandText = "update EventDetail set eventParticipants=eventParticipants-" + lblParticipants.Text;
        cmd1.ExecuteNonQuery();
        Response.Redirect("Detail.aspx?id=" + id.ToString());   
    }

Open in new window

0
<asp:GridView ID="gvType" runat="server" AutoGenerateColumns="False" OnRowDeleting="gvType_RowDeleting" DataKeyNames="EventType_ID" >
            <Columns> 
    <asp:TemplateField HeaderText="Select">
   <HeaderTemplate> <asp:CheckBox ID="chkAll" runat="server" onclick="javascript:SelectAllCheckboxes(this);" />  </HeaderTemplate>
   <ItemTemplate> <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Type_Selected" /> </ItemTemplate>
   </asp:TemplateField>
                 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>
                <asp:BoundField DataField="EventType_ID" HeaderText="EventType_ID" ReadOnly="True" SortExpression="EventType_ID" />
                <asp:BoundField DataField="EventTypeName" HeaderText="EventTypeName" SortExpression="EventTypeName" />
                </Columns>
        </asp:GridView>

Open in new window

Code behind Codes
 EventType aType = new EventType();
    protected void Page_Load(object sender, EventArgs e)
    {
       /* if (!this.IsPostBack)
        { this.BindGrid(); } */

        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void bind ()
    {
        List<EventType> eveList = new List<EventType>();
        eveList = aType.getAllEventType();
        gvType.DataSource = eveList;
        gvType.DataBind();
    }
  protected void gvType_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int result = 0;
        EventType type = new EventType();
        string categoryID = gvType.DataKeys[e.RowIndex].Value.ToString();
        result = type.EventTypeDelete(categoryID);
    }

Open in new window

class code
 public int EventTypeDelete(string ID)
    {
        string queryStr = "DELETE FROM EventType WHERE EventType_ID=@ID";
        SqlConnection conn = new SqlConnection(_connStr);
        SqlCommand cmd = new SqlCommand(queryStr, conn);
        cmd.Parameters.AddWithValue("@ID", ID);
        conn.Open();
        int nofRow = 0;
        nofRow = cmd.ExecuteNonQuery();
        conn.Close();
        return nofRow;

    }//end Delete 

Open in new window

0

C#

91K

Solutions

24K

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