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 want to use the Chartjs Library to create charts and am starting out with a simple Pie Chart. https://www.chartjs.org/docs/latest/charts/doughnut.html

First of all, I have the Chart.css and Chart.js files copied over to my Scripts folder.
My Controller has the following:

public ActionResult Dashboard()
        {
            int thirtyDays = DB.vw_Expires30Days.Count();
            int sixtyDays = DB.vw_Expires60Days.Count();
            int ninetyDays = DB.vw_Expires90Days.Count();

            double totalCount = Convert.ToDouble(thirtyDays) + Convert.ToDouble(sixtyDays) + Convert.ToDouble(ninetyDays);

            double thirtyDayPercentage = Math.Round((thirtyDays / totalCount) * 100, 2);
            double sixtyDayPercentage = Math.Round((sixtyDays / totalCount) * 100, 2);
            double ninetyDayPercentage = Math.Round((ninetyDays / totalCount) * 100, 2);

            List<PieSeriesData> pieData = new List<PieSeriesData>();

            pieData.Add(new PieSeriesData { Name = "30 Days", Y = thirtyDayPercentage });
            pieData.Add(new PieSeriesData { Name = "60 Days", Y = sixtyDayPercentage });
            pieData.Add(new PieSeriesData { Name = "90 Days", Y = ninetyDayPercentage, Sliced = true, Selected = true });

            ViewData["pieData"] = pieData;

            return View();
        }

Open in new window


My Dashboard View has the following:

@Scripts.Render("~/Scripts/Chartjs/Chart.js")

<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['30 Days', '31-60 Days', '61-90 Days'],
        datasets: [{
            label: 'Warranty Expiration',
            data: @ViewData["pieData"] as List<PieSeriesData>,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {

    }
});
</script>

<div class="container">
    <div class="col-xs-12">
    <div class="row">
        <div class="col-xs-10 col-xs-offset-1">

            <canvas id="myChart" width="400" height="400"></canvas>

        </div>

    </div>
   </div>
</div>

Open in new window

The chart does not render.  I'm trying to figure out what's missing.
0
Regex is so nuanced sometimes. I need a bit of help creating a regular expression that will capture the contents of a function so the outer function can be replaced while preserving the entire contents of the function.

Perhaps a brief explanation of exactly what I'm trying to accomplish will help any prospective experts understand my needs a little better. I need to do this because I have to do a mass replace on a lot of files containing queries that were originally written for Oracle. I need to make them compatible with Microsoft SQL Server. The specific example here is the Oracle TRIM(...) function. Microsoft SQL Server doesn't have this function but would instead use LTRIM(RTRIM(...)). This actually also works fine in Oracle so it's a bit of a no brainer to replace TRIM(MyColumnName) with LTRIM(RTRIM(MyColumnName)). Unfortunately, sometimes the contents of the TRIM(...) function may contain other functions. For (bad) example, TRIM(Coalesce(Sum(InvoiceTotal), 0)). The simplest Regex Replace would be to look for "TRIM(" and then find the nearest ")" but that won't work in this case because I'll end up with LTRIM(RTRIM(Coalesce(Sum(InvoiceTotal)), 0)) which is wrong. What I need instead is LTRIM(RTRIM(Coalesce(Sum(InvoiceTotal), 0))). As you might be able to see, I need a balancing group to accomplish this and make sure I have the parentheses matched properly.

I've read up on balancing groups here: …
0
Hello,
Any ideas please if i want to fill combobox in Async way.I am using WinForm C# ComboBox

Combobox has more then 500-1000 items dynamically filled.

I need a way if i can fill DataSource which is basically Model Type CustomerList before
and then just bind it at the time of Combobox initlization to improve loading time.

Currently it takes lot of time for form load as Combobox items are added.

If any option or ideas please share.

Thanks.
Abhilashs
0
Hi


How do I write the FromXml to read an xml file into the given opbject?

Once read in I need to test if a given OldPath exists


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

class MainClass
{
    class Program
    {


        // create two logs to hold each list
        
        public static List<HistoryLog> historyLogs = new List<HistoryLog>();
        static List<DownloadLog> downloadLogs = new List<DownloadLog>();

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

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

            if(File.Exists("DownloadLog.xml") ){
              Console.WriteLine("Hello DownloadLog.xml");
              downloadLogs.FromXml("history", "DownloadLog.xml");

            foreach (var downloadLog in downloadLogs)
            {
                Console.WriteLine("download Name: {0} download OldPath: {1}  ", downloadLog.Name, downloadLog.OldPath );


            }


            }
            else {


            // make a loop just   to test
            // this is to simulate where the infomation will be
            // derived from  with some condition deturmining if 
       

Open in new window

0
I have the following class in a file called classfleet.cs

public class Fleet
{
        
        public string Make { get; set; }
        public string Model { get; set; }
}

Open in new window


on the aspx webpage, I want to get like below.

<asp:textbox text="Make" />
<asp:textbox text="Model" />

All I want is to get the class child name. not the value.
Is it possible with c#? Please show me how if it is possible.
0
FindControl is throwing a null reference exception.  I have to reference a list column which contains
the control id's to match in page but my query does not work using FindControl with the column/field name which contains the
name of the control.  I tried creating a struct but still throws exception. I what I am trying to do posible and how. Can someone help?

Thanks in advance,
Isaac

<div class="form-group" visible="false" id="FirstName" runat="server">
                  <div class="col-xs-12 col-md-8 col-sm-10 nill">
					<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" Text="First name *" CssClass="control-label" />
                      <br />
					<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control" MaxLength="50" aria-label="First name" required="required" AutoPostBack="true"></asp:TextBox>
					<span class="required"></span>
                  </div>
                </div>
                     <br />
                </td>
            <td>
//////////////////////////////////////
struct providerList {
                    public int fieldId;
                   public string fieldRequired;
                   public string aspName;
                   public string aspType;
                           }
private void loadform(List<ProviderInRequest> providerList)
        {

            for (int i = 0; i < providerList.Count; i++)
            
        
            {

                 
                Control ctrl = 

Open in new window

0
I am working on an asp.net c# web application that creates a report and saves the report as a pdf. The report could reach up to 140 pages and is already over 22 MB at page 35. Is there any way to reduce the size of these files as they will then be retrieved and emailed. The application is asp.net webforms using ms reportviewer.

this is the code I used to save the report. I created a LocalReport in the code behind instead of using the reportviewer control beause we don't need to display the report.

            private void SavePdf()
            {
                  var path = GetReportPath();

                  var bytes = _localReport.Render(
                        "PDF", null, out string mimeType, out var encoding, out var filenameExtension,
                        out var streamIds, out var warnings);

                  using (var fs = new FileStream(path, FileMode.Create))
                  {
                        fs.Write(bytes, 0, bytes.Length);
                  }
            }

this is the code to create the report before saving it as a pdf.

            private void RenderReportForSaving()
            {
                  var reportDataSource = new ReportDataSource("DataSet1", base.GetDiscipleshipReportView());

                  try
                  {
                        var path = Server.MapPath($"~/Administration/Reporting/Reports/{_reportType}.rdlc");
                        var report = new LocalReport();

                        _localReport.EnableExternalImages = true;
                        _localReport.ReportPath = path;
                        _localReport.DataSources.Clear();
                        _localReport.DataSources.Add(reportDataSource);

                        AddSubQueriesToLocalReport();

                        _localReport.Refresh();
                  }
                  catch (Exception ex)
                  {
                        …
0
I have a c# application.
I am trying to Loop through records in a Grid with the  purpose of writing same into a table.
The full script is shown below.
The first 3 parameters are coming from a master record and this seam ok.

When i got to the line below

 foreach (DataGridViewRow dgvRow in dgvDetailsTable.Rows)

 dgvDetailsTable.Rows was flagged  as an error  even though
that is my gridname.


using (var command = new NpgsqlCommand("public.spjobhistory_insert", conn))
                {
                    conn.Open();
                    command.Parameters.Add(new NpgsqlParameter("staffnox", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = model.Staff_no });
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticcompany });
                    command.Parameters.Add(new NpgsqlParameter("EmpIdx", NpgsqlTypes.NpgsqlDbType.Integer) { Direction = ParameterDirection.Input, Value = model.EmpId });
                   
                    foreach (DataGridViewRow dgvRow in dgvDetailsTable.Rows)
                    {
                        if (dgvRow.IsNewRow) break;
                        else
                        {
                            command.CommandType = CommandType.StoredProcedure;
                            //dgvtxtCompName
                            //dgvStartDate
            …
0
i have classic mvc web app that have login/password stored in the database. so i have login/password entry webpage and validate again database table.
my question is:

1. what is the best practice to store the userid / password so the secure member can access our admin area? we have admin area for user who can modify some information.
2. can you show me some example codes for single sign on using mvc? I hope to create gmail or facebook single sign on feature.

Thanks
0
I am trying to implement the use of the DatePicker  within a Grid
in my c# application.

There are 2 fields in the grid with date values and the script for selection into
the date fields is shown below. The script works but i get some extra system
message as part of the selected date

 switch(dgvDetailsTable.Columns[e.ColumnIndex].Name)
            {
                case "dgvStartDate":
                    _Rectangle = dgvDetailsTable.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                    dtp.Size = new Size(_Rectangle.Width, _Rectangle.Height);
                    dtp.Location = new Point(_Rectangle.X, _Rectangle.Y);
                    dtp.Visible = true;
                    break;
                case "dgvEndDate":
                    _Rectangle = dgvDetailsTable.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                    dtp.Size = new Size(_Rectangle.Width, _Rectangle.Height);
                    dtp.Location = new Point(_Rectangle.X, _Rectangle.Y);
                    dtp.Visible = true;
                    break;

            }



See  attached screen for some system messages coming before the date

DatePicker  with a prefix in the actual date
DatePicker  with a prefix in the actual date debugged
I just want the date and not the systems messages prefixing it how can i remove the
unwanted messages

Thanks

Olukay
0
How would I refactor this code to make the cocktail class static and remove the variables from it?  This was a test question that I got wrong, so just trying to learn not cheat.

class Program
    {
        static void Main()
        {
            var bartender = new Bartender();
            var martini = new Cocktail(
                    new Component { Name = "Rum", Type = ComponentType.Wet },
                    new Component { Name = "Vermouth", Type = ComponentType.Wet },
                    new Component { Name = "Olives", Type = ComponentType.Garnish }
                );
            martini .Mix();
            bartender.Pour(martini );
        }
    }

    class Cocktail
    {
        private readonly Component[] components;
        private Mixture mixture;
        public bool Mixed { get; private set; }

        public Cocktail(params Component[] components)
        {
            this.components = components;
        }

        public void Mix()
        {
            this.mixture = new Mixture(components.Where(i => i.Type != ComponentType.Garnish).ToArray());
            this.Mixed = true;
        }
    }

    public class Component
    {
        public string Name { get; set; }
        public ComponentType Type { get; set; }
    }

    public enum ComponentType
    {
        Garnish,
        Dry,
        Wet
    }

    public class Mixture
    {
        private readonly Component[] components;

        public Mixture(Component[] components)
        {
        

Open in new window

0
I have part of a program that is much easier to write in C++, and other parts of a program that are easier to write in C#.

Is there a way to mix C# and C++ together in one Visual Studio solution?

Can I add a C++ project to a Visual Studio solution that was created for C# code? (Perhaps create a C++ *.dll file? Oh but then I'm calling unmanaged code...)
0
On my form I have a CopyBTN  this Copies the contents of a RichTextBox to the clipboard any suggestions why it sometimes fails yet if in debug you can just continue for it to work
How do I capture this exception?
FYI there is lines of text in ResultsRTB.Text

        private void CopyBTN_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(ResultsRTB.Text);
        }

Open in new window


Error

System.Runtime.InteropServices.ExternalException was unhandled
  ErrorCode=-2147221040
  HResult=-2147221040
  Message=Requested Clipboard operation did not succeed.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
       at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
       at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
       at System.Windows.Forms.Clipboard.SetText(String text)
       at Trevor.Form1.CopyBTN_Click(Object sender, EventArgs e) in D:\Vb\Trevor\Trevor\Form1.cs:line 265
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at 

Open in new window

0
Hi Team,

I want to select the value 'AMK'  from the drop-down which is nothing but built up of <Div> tags as mentioned in the attached screenshot. What should be the relative Xpath for this from id 'GroupID' ?

appreciate your early response.
DOMStructure.PNG
0
Hi

How do I build an SQL query passing parameters

In the code bellow I need to pass 2 variables into an SQL Update command  

The SQL is wrong because it's not interpreting the variables properly

How do I build stored procedures passing parramiters


        SQLiteConnection dbConnection;
        public Form()
        {
            InitializeComponent();
            dbConnection = new SQLiteConnection("Data Source=D:\\PathTo\\database\\MyDatabase.db3;Version=3;");
            dbConnection.Open();
       }

................

// Code that bulds Old And New name

                                newName = illegalInFileName.Replace(newName, "");
                                    string path = FI.Directory + "\\" + newName;
                                    if (fName != newName)
                                    {
                                        FI.MoveTo(path);
                                    if (UpDateDBChkBox.Checked == true)
                                    {
                                        string OldName = FI.Directory + "\\" + fName;
                                        string sql = "update episode set path = " + @newName + " where path = '" + OldName ;
                                        SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
                                        command.ExecuteNonQuery();
                                    }

Open in new window

0
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
I have two queries and try to make them together. All i try to do is to add totalreceiptamount from 2nd sub query to the 1st main query.
I am using ms sql server 2012. Not sure how to join them together.


Main Query
SELECT        
Invoice_Header.Member_Number AS membernumber, Invoice_Header.Invoice_Amount AS invoiceamount, 

(new column = totalreceiptamount)

Member_Association.Member_Type_Code, Member.Full_Name, Invoice_Header.Office_Number
FROM            Invoice_Detail INNER JOIN
                         Invoice_Header ON Invoice_Detail.Invoice_Number = Invoice_Header.Invoice_Number INNER JOIN
                         Receipt_Detail ON Invoice_Detail.Invoice_Number = Receipt_Detail.Invoice_Number INNER JOIN
                         Receipt_Header ON Receipt_Detail.Receipt_Number = Receipt_Header.Receipt_Number INNER JOIN
                         Member_Association ON Invoice_Header.Member_Number = Member_Association.Member_Number INNER JOIN
                         Member ON Invoice_Header.Member_Number = Member.Member_Number
WHERE        (Invoice_Detail.Charge_Code IN ('1910D', '1910T', 'NEW19')) AND (Invoice_Header.Invoice_Date BETWEEN 
'20181201' AND '20190131') AND (Receipt_Header.Deposit_Date BETWEEN '20181201' AND '20190131') AND 
(Member_Association.Association_ID = 'ABC') AND (Member_Association.Status = 'A')
ORDER BY Invoice_Header.Invoice_Amount

Open in new window


Second Query - Sub
(new column = totalreceiptamount):QUERY
SELECT        SUM(Receipt_Detail.Amount_Applied) AS totalreceiptamount
FROM            Receipt_Detail INNER JOIN
                         Receipt_Header ON Receipt_Detail.Receipt_Number = Receipt_Header.Receipt_Number INNER JOIN
                         Invoice_Detail ON Receipt_Detail.Invoice_Number = Invoice_Detail.Invoice_Number
WHERE        (Receipt_Detail.Member_Number = membernumber) AND (Receipt_Header.Deposit_Date BETWEEN '20181201' AND '20190131') 
AND (Invoice_Detail.Charge_Code IN ('1910D', '1910T', 'NEW19'))

Open in new window

0
Is it possible to use VS C# to create and to populate an Excel spreadsheet? I need to read csv files and then convert them to Excel files. The data will get read and then manipulated before being written back out. Any helpful links and tips would be greatly appreciated,.
0
I am getting an error on a page that uses entity and Telerik for a webforms application that uses .net 4.0 because I am not able to update to later version of .net.  Had a different error when trying to use entity framework 6.0 and went down to 5.0 and that error is gone and site loads but now the page I am trying to add has this issue.  See errors below when page is brought up.  Not sure how to see LoaderExceptions when on a server.  No problems running on development computer with Visual Studio 2017.

 Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Open in new window


Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
   

Open in new window

0
i have a html text box which allow user to select mulitple states. e.g. the textbox value will be CA,TX,FL

and I want to take the value and turn into like below.

select * from state where statecode in ('CA','TX','FL')

I use c# asp.net web form. please show me how to do that...thanks
0
I want to send link on twilio ... how can I do that?
0
do u see anything wrong with this? it returns null for some reasons

public string urlShorter(string url)
        {
            string finalURL = "";
            string post = "{\"longUrl\": \"" + url + "\"}";
            string shortUrl = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
                request.ServicePoint.Expect100Continue = false;
                request.Method = "POST";
                request.ContentLength = post.Length;
                request.ContentType = "application/json";
                request.Headers.Add("Cache-Control", "no-cache");
                using (Stream requestStream = request.GetRequestStream())
                {
                    byte[] postBuffer = Encoding.ASCII.GetBytes(post);
                    requestStream.Write(postBuffer, 0, postBuffer.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            finalURL = Regex.Match(json, @"""id"": ?""(?.+)""").Groups["id"].Value;
                        }
                    }
                }
        

Open in new window

0
How do I add an image from resource to WPF form?

In Visual Studio I create a new project. I select: Visual C# | Windows Desktop | WPF App (.NET Framework)
Name of new project is "WpfApp1"

In Solution Explorer I right-click on "WpfApp1", select Properties

On left side I select Resources

I drag image file from File Explorer to the "Resources page". This adds the image to my resources. (Let's say the image file is "MyImage.bmp" and it shows up as "MyImage")

I set Access Modifier: change from "Internal" to "Public"

Now I would like to add this image to my MainWindow.xaml form:
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Image Source="{something goes here}" />
    </Grid>
</Window>

Open in new window

What do I specify as Source for Image I'm my MainWindow.xaml file?
0
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

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