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

I need to sort a foreach statement in an MVC website. I've included the code below. I would like to order the results by item.InteractionDate. I believe it is sorting by the Id rather than the InteractionDate. If you need a snippet from the model, I can add that as well.

<table class="table">
        <tr>
            <th>
                Meeting Date
            </th>
            <th>
                Customer
            </th>
            <th>
                Employee
            </th>
            <th>
                Notes
            </th>
            <th>
                Update Meeting
            </th>
        </tr>

        @foreach (var item in Model.Meetings)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.InteractionDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Customer1.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Employee1.FullName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Notes)
                </td>
                <td>
                    @Html.ActionLink("Edit Meeting", "Edit", "Meetings", new { id = Model.Id}, null)
                </td>
            </tr>
        }
    </table>

Open in new window

0
Introducing Cloud Class® training courses
LVL 12
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

Hi.
I created an folder in project directory (see the attached pic) .
Into this folder I will save some files while user use the program. When program close those file will be removed.
I'm programming in C# WPF.
The problem is that I cannot add files to this folder and get message:
'Could not find a part of the path 'E:\GAB-SW\Program\Source Code\Program_WPF\Program_WPF\bin\Debug\temp\Profile174.png'.'
If I open the project folder my "temp" folder was exist there.
Which path I have to use to save my files in this folder?
Capture1.PNG
Capture.PNG
0
I am writing an app that will get a list of directories and files.  I am populating a List<string> to store this information.

I created an ENUM to determine what directories and file extensions should be excluded.  I was trying to figure out how to write linq to "removeall" from the list against the values in the ENUM.  

Want to see if there is a way without looping through each value in List<string>.
public static class Enumerators
{
	public enum ExcludedDirectories
	{
		ABC
	}

	public enum ExcludedFiles
	{
		docx,
		Thumbs
	}
}

Open in new window

My solution is below.
    public static class EnumValidation
    {
        public static List<string> DeleteValues<T>(List<string> value)
        {
            var deletionvalues = Enum.GetValues(typeof(T));

            foreach (var del in deletionvalues)
            {
                value.RemoveAll(x => x.Contains(del.ToString()));
            }

            return value;
        }
    }

Open in new window

Is there a more efficient way?
0
I am working on an application that talks to 3rd party API, the API access gets locked out for every n requests but the API is not responding with an appropriate error message saying the account is locked out, and also now they are not ready make any changes to the API to send an user friendly message. We are getting some common weird message whenever account is locked out based on which we are understanding that the account is locked

are there any best practices to handle these kind of lock out mechanisms in C# Windows Service for the API calls?, I wanted to log message that the account is locked out and the password has to be reset and also to send an email
0
How can i unit test datagridview mouse click event.

The actual code is reading the cell value at the place where the mouse is clicked and if user really clicked on the cell it is capturing the value and copying that value to a textbox

Here it is using x and y co-ordinates to capture the value in the datagridview cell.

Can we unit test this functionality, if yes please help in providing related links/resources
0
I'm getting below error when i compile the c# project in vs2017

Formboca.resx due to its being in the Internet or Restricted zone or having the mark of the web on the file. Remove the mark of the web if you want to process these files
0
in asp.net c# I created treeview
 <div>

        <asp:TreeView id="LinksTreeView" Font-Names= "Arial" ImageSet="Events"  SelectedNodeStyle-ForeColor="Red" ForeColor="Black" EnableClientScript="true" PopulateNodesFromClient="true"  
        onselectednodechanged="TreeView1_SelectedNodeChanged" OnTreeNodeCheckChanged="LinksTreeView_CheckChanged" ShowLines="True"  OnTreeNodePopulate="PopulateNode" runat="server">
          <Nodes>
             <asp:TreeNode Text="Policy" SelectAction="Expand" PopulateOnDemand="true"/>
            </Nodes>
        </asp:TreeView>
with dynamically created nodes in code behid
   public void PopulateNode(Object sender, TreeNodeEventArgs e)
        {
            if (!IsPostBack)
            {
                // Call the appropriate method to populate a node at a particular level.
                switch (e.Node.Depth)
                {
                    case 0:
                        // Populate the first-level nodes.
                        PopulatePolicy(e.Node);
                        break;
                    case 1:
                        // Populate the second-level nodes.
                        PopulateYear(e.Node);
                        break;
                    case 2:
                        // Populate the third-level nodes.
                        PopulateBill(e.Node);
                        break;
                    default:
                        // Do nothing.
                        break;
0
Hello Experts,

I'm compiling a c sharp program in Visual Studio code (when I say I'm compiling, I mean copying from a site - I'm not a coder)

The code is as follows:

namespace mycsharpmodule4
{
    using System.Collections.Generic;     // for KeyValuePair<>
    using Microsoft.Azure.Devices.Shared; // for TwinCollection
    using Newtonsoft.Json;                // for JsonConvert
    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Runtime.Loader;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Client.Transport.Mqtt;
   

    
class MessageBody
{
    public Machine machine {get;set;}
    public Ambient ambient {get; set;}
    public string timeCreated {get; set;}
}
class Machine
{
   public double temperature {get; set;}
           
}
class Ambient
{
   public double temperature {get; set;}
   public int humidity {get; set;}         
}

    }

Open in new window



When I run the code I get the following error:

CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [C:\app\mycsharpmodule4.csproj]
The command 'cmd /S /C dotnet publish -c Release -o out' returned a non-zero code: 1

Open in new window


The full output is as follows:

The push refers to repository [carlscontainer.azurecr.io/mycsharpmodule4]
An image 

Open in new window

1
i am trying to export my gridview to excel in my application based on filtered results.
exportgridview.PNG
when user enters an item code and clicks on filter button i pass that value into the sqldatasource's filter expression and now have the results narrowed down in the gridview.

i now want to export these filtered records into excel.

This is my code:
private void ExportGridToExcel()
        {
            //Get the data from database into datatable

            string strQuery = "select [Plant],[Item Code],[Description],[ftid] ,[fid] From [Format] WHERE SUBSTRING([Item Code],0,5) =" + filter.Text;

            SqlCommand cmd = new SqlCommand(strQuery);

            DataTable dt = GetData(cmd);

            //Create a dummy GridView

            GridView GridView1 = new GridView();

            GridView1.AllowPaging = false;

           Gridview1.DataSource = dt;

            //Gridview1.DataBind();

            Response.Clear();

            Response.Buffer = true;

            Response.AddHeader("content-disposition",

             "attachment;filename=DataTable.xls");

            Response.Charset = "";

            Response.ContentType = "application/vnd.ms-excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter hw = new HtmlTextWriter(sw);

            Gridview1.RenderControl(hw); ---------------- i get this message RegisterForEventValidation can only be called during Render();   

            //style to format numbers 

Open in new window

0
I need to get the folder name from a file path using substring in c#. The file path looks like this: O:\folder1\subfolder\text.docx. From this I want to pull out folder1 only. How can I do that using substring?
0
Cloud Class® Course: CompTIA Cloud+
LVL 12
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hello,

I am trying to come up with a solution in WPF to solve a UI issue I am having.

If you look at the attached wire-frame for the UI you will see that I'm trying to make a grid of sorts. The top portion of each row contains 'static' data (will always show # animals, species, gender, etc), but the bottom portion (additional details section) is more dynamic. If you look at the wire-frame you will notice that groups 1 and 2 have 5 attributes and group 3 has 8. This 'footer' section should support (n) attributes.

I'm not sure how to go about solving this issue. WPF datagrids re pretty limited so I don't know how to make this concept work with that. It doesn't necessarily have to be a datagrid, as long as I can solve the problem (even if there is a 3rd party control that could handle this, that works too).

Anybody have any ideas on where to get started?

0
I am working on a MVC project with AngularJs  and trying to download SSRS report as an excel. Am new to AngularJs.
I have tried the following codes and output is download excel with binary code!

Please correct my code, so that will download excel in exact same format as in SSRS report.

report-list.ctrl.js
(function () {
    'use strict';
    var module = angular.module('app')

        //.directive('ngConfirmClick', [
        //    function () {
        //        return {
        //            link: function (scope, element, attr) {
        //                var msg = attr.ngConfirmClick || "Are you sure?";
        //                var clickAction = attr.confirmedClick;
        //                element.bind('click', function (event) {
        //                    if (window.confirm(msg)) {
        //                        scope.$eval(clickAction)
        //                    }
        //                });
        //            }
        //        };
        //    }])

        .controller('ReportListController', ['$scope', '$http', '$q', '$interval', '$location', '$window', '$modal', '$modalStack', 'toastr', 'dataService',
            function ($scope, $http, $q, $interval, $location, $window, $modal, $modalStack, toastr, dataService) {

                $scope.showreportlist = true;
                $scope.reports = [];
                $scope.clientsessionreportData = [];


                $scope.downloadReport = function (res) {

                    

Open in new window

1
Hello,
I have an application that is connecting to a board via a COM port.

I wrote the following function to open/close the port:
static public bool ConnectEMR4(string portID, string strCommand)
        {
            SerialPort mySerialPort = new SerialPort( portID, 9600,Parity.None,8,StopBits.One);
            
            try
            {

                // Create random data to write to the stream.
                byte[] dataArray = new byte[25];
                new Random().NextBytes(dataArray);

                mySerialPort.Open();

                mySerialPort.Write(dataArray, 0, dataArray.Count());

                mySerialPort.Close();
                MessageBox.Show("Connection successful");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return true;
        }

Open in new window

The problem I have is that I am trying to convert from a VB6 app to C# version.
My exposure to the COM Devices is minimal. The OBC command needs to combined a checksum added.

A VB6 version that I need to convert to C# would be these module:

'******************************************************************************
Attribute VB_Name = "modCRC"
Option Explicit

'******************************************************************************
'Procedure Name             :  CalcCRC()
'Procedure definition       :  Calculates the 2 Byte CCITT CRC-16 Checksum
'Description of Arguments   :  String
'Values 

Open in new window

0
I am new to Razor pages and am trying to develop a web application (ASP.NET Core 2.1 using EF Core 2.1).  I have a form where I want to bring in a list of lot numbers for a part code.  So I just want to tap into the database context and populate a dropdown.  I am seeing  a lot of examples for MVC - but I am not using controllers.

I do not understand why this is so complicated.  In a lot of examples, people are using the ViewBag, but I do not have access to that.

I have been working through articles on the internet for an entire week and am at my wit's end.  Is this just extremely complicated?  

I am not looking for an entire solution here.  How do I just create a dropdown that shows a list of items from a table in the database?  I have the context setup and working.  I just cannot figure out how to get a dropdown populated from any table in the database.

If you have experience with this, should I scrap my project and start over with MVC Razor pages?  I am new to asp.net so I just went with the latest technology...

Thanks for any help,
Bonnie
0
What are the big benefits of .NET CORE?

And how do they differentiate from .NET Framework?
0
Design Pattern for object oriented design question...

What is that 5 letter word that has 5 OOP Design Patterns in that one word?

Once I hear the word, I will recall the 5 patterns.

"S," is Single Responsibility..

Thanks.
0
Hello,

I want to create desktop application using C# .NET that create RAR file. application select date wise files and create one RAR file of that.

Is there any utility or third party tool available ?


Thanks,
Naitik Gamit
0
Hello Experts,

Can someone please let me know how to automatically run my Windows app as administrator.

At the moment, in order to run any app e.g. even command prompt, I have select to run as administrator.

Is there a way to enable all apps to run as administrator?

I'm running Windows 10

Cheers
0
Codes always show that it is unsuccessful. I suspect its my cascading delete problem?

cs code, with button @ html ->     <button type="button" style="margin-right:189px" class="btn btn-danger" runat="server" ID="btnDeleteInd" onserverclick="btnDeleteInd_ServerClick">Remove</button>
        protected void btnDeleteInd_ServerClick(object sender, EventArgs e)
        {
            foreach (GridViewRow gr in gvPerson.Rows)
            {
                int check = mem.DeleteIARecord(int.Parse(gr.Cells[0].Text));
                if (check == 1)
                {
                    ScriptManager.RegisterStartupScript(Page, GetType(), "AlertDisplay", "displaySuccess('Successfully Deleted Member:');", true);
                }
                else if(check == 0)
                {
                    ScriptManager.RegisterStartupScript(Page, GetType(), "AlertFailureDisplay", "displayFailure();", true);
                }
            }
        }

Open in new window


sql:
    public int DeleteIARecord(int personid)
        {
            int result = 0;
            List<SqlCommand> transcommand = new List<SqlCommand>();
            SqlCommand mycmd = new SqlCommand();
            string commandtext = "delete from membership.TBL_PERSON_PA where PERSON_ID=1;" + 
                                 "delete from membership.TBL_PERSONAL_ASSISTANT where PA_ID=(Select PA_ID from membership.TBL_PERSON_PA where PERSON_ID=1); " +
                                 "delete from membership.TBL_MEMBERSHIP where PERSON_ID=(Select PERSON_ID from membership.TBL_PERSON where PERSON_ID=1); " +
                                 "delete from event.TBL_EVENT_GUEST_INVITE where PERSON_ID=(Select PERSON_ID from membership.TBL_PERSON where PERSON_ID=1); " +
                                 "delete from TBL_PERSON where PERSON_ID=1; ";
            mycmd = dbhelp.CreateCommand(commandtext, CommandType.Text, "@1", personid);
            transcommand.Add(mycmd);
            result = dbhelp.ExecTrans(transcommand);

            return result;
        }

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

What is the correct way to write a repository pattern.  I wrote the below classes but when I went to use the insert statement I had to pass in T to SQL which I didn't want to do.

I also need to add an additional method "CallSproc" that would pass in the stored procedure name with optional parameters and allow it to be run without returning anything.
public interface ISQL<T>
{
	void InsertStatement(string sqlString);
	void UpdateStatement(string sqlString);
	void DeleteStatement(string sqlString);
	List<T> SelectStatement(string sqlString);
	List<T> SelectSPROC(string sprocName, List<Parameters> parameters);
}

Open in new window

public class SQLData<T> : ISQL<T> where T : new()
{
	string filename = string.Empty;

	SqlConnection SQLConn;
	SqlCommand SQLCmd;
	SqlDataReader SQLRdr;
	string strConnection = string.Empty;

	public void InsertStatement(string sqlString)
	{
		throw new NotImplementedException();
	}

	public void UpdateStatement(string sqlString)
	{
		try
		{
			using (SQLConn = new SqlConnection(ConnectionStrings.GetConnectionString()))
			using (SQLCmd = new SqlCommand())
			{
				SQLCmd.CommandText = sqlString;
				SQLCmd.CommandType = CommandType.Text;
				SQLCmd.Connection = SQLConn;
				SQLCmd.CommandTimeout = 0;
				SQLConn.Open();
				SQLCmd.ExecuteNonQuery();
			}
		}
		catch (Exception ex)
		{
			string x = ex.Message;
		}
		finally
		{
			SQLConn.Close();
		}
	}

	public void DeleteStatement(string sqlString)
	{
		throw new NotImplementedException();
	

Open in new window

0
Please high level what microservices can do?

And from a C# perspective, what is the best way to create them?

.NET CORE?

etc...
0
After i click the delete button, a modal is supposed to show. But now, it receives this error over here : HiddenField hdn = (HiddenField)gvPerson.Rows[gvPerson.SelectedIndex].FindControl("hdnId");

cs code
  public void btngvPersonDelete_onclick(object sender, EventArgs e)
        {          
             HiddenField hdn = (HiddenField)gvPerson.Rows[gvPerson.SelectedIndex].FindControl("hdnId");
            if (hdn != null)
            {
                // bindPAtable(int.Parse(hdn.Value));
                BindEventRepeater(int.Parse(hdn.Value));
                int rowIndex = gvPerson.SelectedRow.RowIndex;
                ScriptManager.RegisterStartupScript(Page, GetType(), "AlertUnauthorised", "showmodalIND(" + rowIndex + ");", true);
            }
        }

Open in new window

HTML side
    <div runat="server" id="person" style="display:none;">
       <asp:GridView CssClass="table table-hover BlueTable personTable" ID="gvPerson" class="table table-striped" DataKeyNames="PERSON_ID" EmptyDataText="No Records Found" ShowHeaderWhenEmpty="true" OnRowEditing="gvPerson_RowEditing" OnRowDeleting="gvPerson_RowDeleting" runat="server" AutoGenerateColumns="false" GridLines="None" UseAccessibleHeader="true" BorderStyle="None" >
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                       <input type="hidden" runat="server" id="hdnId" value='<%# Eval("PERSON_ID") %>' />
                    </ItemTemplate>
         

Open in new window

0
In ASP.NET C# I create a possibility to open pdf file


in cs file:
protected void bttnpdf_Click(object sender, EventArgs e)
        {

            WebClient User = new WebClient();

            Byte[] FileBuffer = User.DownloadData("\\\\lsmfs1\\726984\\2016\\726984.pdf");

            if (FileBuffer != null)
            {

                Response.ContentType = "application/pdf";

                Response.AddHeader("content-length", FileBuffer.Length.ToString());

                Response.BinaryWrite(FileBuffer);

            }

        }

in aspx:
<asp:Button ID="bttnpdf" runat="server" Text="Click for open PDF" Font-Bold="True" OnClick="bttnpdf_Click" />

PDF document takes whole page to open, I do not find an option to go back, only close browser,
can I open this document in some container in the page or create some "BACK" functionality?
0
Is there a good way to allow a MVC app to have a limited number of concurrent logins.  I know how to limit it to one concurrent login, but is is possible to limit it to 3 for instance.
0
I used Leaflet.js at my previous job last year. I think in C# code, we created a FeatureCollection (something like that). We also had Geometry column in the database.

1. Now, I have an address and have its longitude and latitude. I get this, for example, from Google API.  I'll save this in the database

2. In Leaflet.JS, I can use GeoJson --> https://leafletjs.com/examples/geojson/

My questions... can I just use the Longitude and Latitude of the address with Leaflet.js?  how does GeoJson come into play ... I don't know why that project had a Geometry column in the database? Why do I need GeoJson? How can I create GeoJson for an address?
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).