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 dropped a datadridview on to my WinFrom. I then populate it using this code. What would it take to add controls at the bottom of the grid that would allow the user to go to the first record, go to the last record, go to the previous record and go the next record? Is this just a property of the dgv or do I need to add code to handle this?

        private void DisplayPersonnelMaster()
        {
            try
            {
                PersonnelDataSet = new System.Data.DataSet(); /* Define the data set for the list of personnel */
                PersonnelDataSet.CaseSensitive = false;

                PersonnelDataCommand = new System.Data.SqlClient.SqlCommand();
                PersonnelDataCommand.Connection = PersonnelDataConnection;

                PersonnelDataCommand.CommandText = "SELECT [FULLNAME],[LASTNAME],[FIRSTNAME],[MIDLNAME],[PINNUMBER] FROM [PERSMSTR] ORDER BY[FULLNAME]";

                PersonnelDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
                PersonnelDataAdapter.SelectCommand = PersonnelDataCommand;
                _commandBuilder = new System.Data.SqlClient.SqlCommandBuilder(PersonnelDataAdapter);

                PersonnelDataAdapter.Fill(PersonnelDataSet);

                if (PersonnelDataSet == null || (PersonnelDataSet.Tables.Count == 0) || (PersonnelDataSet.Tables[0].Rows.Count == 0))
                {
                    MessageBox.Show("No records found in personnel database. Please start …
0
For part of a program I am creating I need to find the distance in miles between two ZIP codes.  This does not have to be exact, "as the crow flies" is fine.  I have found some solutions online but can not get them to work.  My background is in SQL but I have an understanding of programming logic, but I still can't get these to work in Microsoft Visual Studio.

The first one I found looked like it would do exactly what I wanted to do but the urls are not update and I am not sure where they may have moved to or what they used to be:
http://blog.codebrain.co.uk/post/2009/05/08/C-Distance-Between-Two-Postcodes.aspx

"http://maps.google.com/maps/geo?q={0}&output=xml" is no longer a valid link.

Another solution that I tried is:
https://www.techrepublic.com/blog/software-engineer/how-do-i-determine-the-distance-between-zip-codes-using-c/

For this one, the basic idea makes sense to me but I am not sure how to put it all in to action.  The link to download the examples is no longer valid and I am not sure where all of the code goes.  For instance, where do I need to reference "LoadData" from and what needs to be passed to it as the "path."  Also is the xml document stored in project somewhere?

Any insight into either of these solutions or even another that would work better are appreciated.  Thanks
0
I have an MVC C# Web Application and am using jQuery Bootgrid. The bootgrid is populating fine, the issue is I can't seem to get the icons in front of the top right drop downs. See screen shots attached. I am using bootstrap 4. I believe the jquery bootgrid is having a conflict with the fontawesome, but I can't seem to resolve. I have attached screenshots of what I need and what I have.

chtml snippet -----------------------------------------------------------
    <script>
    var grid = $("#grid-data").bootgrid({
        ajax: false,
        caseSensitive: false,
        columnSelection: true,
        formatters: {
            "commands": function (column, row) {
                return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.audience_id + "," + row.client_id + "," + row.audience_name + "," + row.active + "\"><span class=\"fas fa-pencil-alt\"></span></button> " +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.audience_id + "\"><span class=\"fas fa-trash-alt\"></span></button>";
            },
        }
    }).on("loaded.rs.jquery.bootgrid", function () {
        /* Executes after data is loaded and rendered */
        grid.find(".command-edit").on("click", function (e) {
            $("#EditAudience").modal("show");
            var array = $(this).data("row-id").split(',');
            $("#edit_Audience_ID").val(array[0])
            …
1
I have the following simple code with a skip and take which i'd hoped would add the following to my query e.g. "OFFSET 3000 ROWS FETCH  FIRST 10 ROWS ONLY" which runs very quick on the millions of rows with provider ibm.data.db2.entityframework.

 
public static IQueryable<T> GetPage<T>(this IQueryable<T> entities, int pageRows, int pageSize,int totalRows)
        {
            var skip = (totalRows < pageSize ? 0 : pageRows);
            return  entities
                .Skip( skip)
                .Take( pageSize);
        }

Open in new window


but instead it creates the following adding a "WHERE Project1.row_number > 0" for the skip which is not that fast:

SELECT 
Project1.CASE_ID AS CASE_ID, 
Project1.CREATED_TSTAMP AS CREATED_TSTAMP, 
Project1.CASE_TYPE_DESC AS CASE_TYPE_DESC, 
Project1.CASE_STATUS_DESC AS CASE_STATUS_DESC

FROM ( SELECT           Project1.CASE_ID AS CASE_ID, 
                        Project1.CREATED_TSTAMP AS CREATED_TSTAMP, 
                        Project1.CASE_TYPE_DESC AS CASE_TYPE_DESC, 
                        Project1.CASE_STATUS_DESC AS CASE_STATUS_DESC, 
                        row_number() OVER (ORDER BY Project1.CASE_ID ASC) AS row_number
      FROM ( SELECT 
            Extent1.CASE_ID AS CASE_ID, 
            Extent1.CREATED_TSTAMP AS CREATED_TSTAMP, 
            Extent1.CASE_TYPE_DESC AS CASE_TYPE_DESC, 
            Extent1.CASE_STATUS_DESC AS CASE_STATUS_DESC
            FROM CRSOWN.CRV_CASE_SUMMARY AS Extent1
      )  AS Project1
)  AS Project1
WHERE Project1.row_number > 3000
ORDER BY Project1.CASE_ID ASC FETCH FIRST 10 ROWS ONLY ;

Open in new window


how do I get it to add "OFFSET 3000 ROWS FETCH  FIRST 10 ROWS ONLY"
0
Hello,
I want to make a windows form application that will only show the number of friend we have in a specific Facebook account, so no posting, viewing or whatever. Just a big counter number on a screen.

I tried the following code:
using Facebook;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FacebookCounter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var fb = new Facebook.FacebookClient();

            dynamic tokenInfo =
              fb.Get(
                String.Format(
                  "/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials",
                  "XXXXXXXXXXXXX",
                  "XXXXXXXXXXXXX"));

            var appAccessToken = (string)tokenInfo.access_token;

            //   FacebookClient client = new FacebookClient(accToken());
            fb.AccessToken = appAccessToken;
            dynamic friendListData = fb.Get("/me/friends");
            var result = (from i in (IEnumerable<dynamic>)friendListData.data
                          select new
                          {
                              i.name,
                              i.id
                          

Open in new window

0
Want to print continuous crystal report using from range, below attaching image of what i want to achieve:

How can i print continuous crystal report?
Also i'm using this code to print single report
public void GetInvoiceRpt(string strReportName, string strVno)
        {
            try
            {
                int compcode = Convert.ToInt32(Application.Current.Properties["CompId"]);

                ReportDocument cryRpt = new ReportDocument();
                TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
                TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
                ConnectionInfo crConnectionInfo = new ConnectionInfo();
                Tables CrTables;


                cryRpt.Load(strReportName);

                crConnectionInfo.ServerName = clsconnection.SQLServerName();
                crConnectionInfo.DatabaseName = "MyApplication" + clsconnection.getCompanyCode(compcode);
                crConnectionInfo.UserID = clsconnection.SQLLoginID();
                crConnectionInfo.Password = clsconnection.SQLPW();
                CrTables = cryRpt.Database.Tables;
                foreach (Table CrTable in CrTables)
                {
                    crtableLogoninfo = CrTable.LogOnInfo;
                    crtableLogoninfo.ConnectionInfo = crConnectionInfo;
                    CrTable.ApplyLogOnInfo(crtableLogoninfo);
                }
                cryRpt.Refresh();

                cryRpt.SetParameterValue("@voucherno", strVno);

    

Open in new window

0
Using Visual Studio C# what would the proper way to design an application that would allow the users to move people from one group to another. What I have are three tables that are filled with peoples names and skill sets. As they complete various classes and pass exams they graduate to a higher class. I need to write an application that will allow a user to mark one or more people in one group and elevate them to another group. In the past, I have always displayed multiple rows using a datagridview. Would that still work in this case? How would I execute the move? Add a column to the grid and when I save the grid execute SQL statements that move the marked records into the designated group. Is there a better way not using a datagridview? I am still learning my way around C# so any guidance that can be provided would be appreciated.
0
Can anyone give me the code to display a multiple page tiff image using MVC and ASP.Net C#?
0
I am getting wrong barcode scan value -


BarcodeFormat = "000000000000"; //12 digit

I have generated a list of barcode (ex. 1 to 10000) with format 000000000001 to 000000010000
when I scanning using my mobile camera, some barcodes are getting wrong values as below

Barcode            Scan Value
000000000001      000000000001
000000000002      000000000001
000000000003      000000000001
000000000004      000000000001
000000000005      000000000001

000000000006      000000000006
000000000007      000000000006
000000000008      000000000006
000000000009      000000000006
000000000010      000000000006

000000000011      000000000011
000000000012      000000000011
000000000013      000000000011
000000000014      000000000011
000000000015      000000000011

000000000016      000000000016
000000000017      000000000016
000000000018      000000000016
000000000019      000000000016
000000000020      000000000016

What is going wrong ?

I am using following library:

Source Code url : https://github.com/barnhill/barcodelib

/*
 * ***************************************************
 *                 Barcode Library                   *
 *                                                   *
 *             Written by: Brad Barnhill             *
 *                   Date: 09-21-2007                *
 *          Last Modified: 11-02-2013                *
 *                                                   *
 *  This library was designed to give developers an  *
 *  easy class to use when they need to generate     *
 *  barcode images from a …
0
HI,

I am building a windows form program to replace excel sheets as they are always crashing and losing work and as the sole IT guy they need to go. The program is working but not very optimised due to the amount of data in the tables. One of the SQL queries selects a table and returns all company names where that line hold values and populates a drop down filter box. SQL is not really my thing but need some pointers in making this more responsive.

 public void getCompanyList(string database)
        {
            var select = @"SELECT DISTINCT dbo.[Forecast_" + database + @"].Company
FROM            dbo.[Forecast_" + database + @"] INNER JOIN
                         production.dbo.products ON dbo.[Forecast_" + database + @"].Product_Code COLLATE Latin1_General_BIN = production.dbo.products.ProductCode
GROUP BY dbo.[Forecast_" + database + @"].Nr, dbo.[Forecast_" + database + @"].Product_Code, dbo.[Forecast_" + database + @"].Description, 
                         dbo.[Forecast_" + database + @"].Category, production.dbo.products.SCE, dbo.[Forecast_" + database + @"].Company
HAVING        (SUM(ISNULL(dbo.[Forecast_" + database + @"].Week1, 0)) + SUM(ISNULL(dbo.[Forecast_" + database + @"].Week2, 0)) 
                         + SUM(ISNULL(dbo.[Forecast_" + database + @"].Week3, 0)) + SUM(ISNULL(dbo.[Forecast_" + database + @"].Week4, 0)) 
                         + SUM(ISNULL(dbo.[Forecast_" + database + @"].Week5, 0)) + SUM(ISNULL(dbo.[Forecast_" + database + 

Open in new window

0
Advise on building a windows application.

I want to be able to generate a butterfly diagram based on height, width, length input from the user. (see diagram)

 Diagram 1
I can generate a bitmap to do this.

The part I cant seem to figure out is how I can draw/drop blocks onto the butterfly map and then draw lines to show route/path.

I was thinking of having the blocks (in diagram Below) on the windows form and simply drag/drop onto the picture of the box??
Then somehow draw the lines or make the lines an auto populate?

diagram 2
Any thoughts?
Thanks in advance for any suggestions/help you can provide.

Jed-
0
I have a button in my UWP application that is set to change a variable that controls whether a StackPanel shows up or not. For some reason, this is not working. There is a similar function that changes it to FALSE that works just fine. If I start with it being TRUE (starts with the stackpanel open) and close it and then hit the same button an error appears that doesn't appear otherwise. " Exception thrown: 'System.InvalidCastException' "

xaml
<AppBarButton Click="{x:Bind OpenRecords.OpenNewTicketAsync}" Icon="Add" Label="New Ticket" ToolTipService.ToolTip="New Ticket"/>

Open in new window

<StackPanel x:Name="OpenCustomerPanel" Orientation="Horizontal" x:Load="{x:Bind OpenRecords.NewOpenTicket, Mode=OneWay}" RelativePanel.Below="OpenCommandBar">

Open in new window


C#
public event PropertyChangedEventHandler PropertyChanged;
private bool _NewOpenTicket = false;

		public void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
			 
		public void OpenNewTicketAsync()
        {
            NewOpenTicket = true;
        }
		
		public bool NewOpenTicket
        {
            get => _NewOpenTicket;
            set
            {
                if (_NewOpenTicket != value)
                {
                    _NewOpenTicket = value;
                    OnPropertyChanged();
                }
            }
        }

Open in new window

0
In InfoPath Designer 2013 I am trying to upload a form templet to Share Point location and I am getting error :”There is some issue in assemble metadata service. Please try again.”
This form was uploading properly before,  one other person was adjusting just some form formating minor issue as form is (moving some check box from and extending some text box size .)
After that intervention it looks like form start to behave strange and gives this error.
 Not sure why is this error popping up as upload procedure was working fine before. I have several other very similar forms that could be uploaded to the same location without problem??
Is it something that I should check in this form template properties or …?
0
Try to run a ASP Core 2.0 with C# and the CSS can only apply if I set the APP URL to 53400 port. It doesn't work for other port. Why it appear so strange ?

Thx
Work.png
NoWork.png
0
Hello,

I have a plain windows Form with a button (buttonClickMe) in the middle. I want to animate it a little. I just want the size of the button to double when the button is hovered over, but double in size over a timeframe of a second. I want to do this with C# with a windows form. Any ideas?

Thank you,
 Shannon Callahan
0
There is a requirement that there will be the grid of employee having name,id,gender etc..And there will be the dropdownlist of employee names outside of grid. the requirement is that the values in the grid of employee name need to be populated at the top of dropdownlist. where we can do this whether in client side or server side. if cilent side means how we can achieve that scenario
0
i have a gridview with a header template and trying to use masked edit extender so its easy for users to enter data as they tab through the gridview. but what happens is:

highlighted.PNG
even after i click out of focus and enter data this happens:

maskededit.PNG
how do i go by removing focus of the textbox and how can i have the mask to stay and be replace by the time entered by the user??

 <asp:TemplateField HeaderText="Start Time" SortExpression="Start Time">
                <EditItemTemplate>
                    <asp:MaskedEditExtender runat="server"
                                            AutoComplete="false"
                                            TargetControlID="TextBox13"
                                            Mask="99:99"
                                            MessageValidatorTip="true"
                                            OnFocusCssClass="MaskedEditFocus"
                                            OnInvalidCssClass="MaskedEditError"
                                            MaskType="Time"
                                            InputDirection="LeftToRight" AcceptAMPM="true"
                                            ErrorTooltipEnabled="True"  ID="MENEWStartTImeEdit" ClearMaskOnLostFocus="false" />
                    <asp:TextBox ID="TextBox13" runat="server" Text='<%# Bind("Start_Time","{0:HH}:{0:mm}") %>'></asp:TextBox>
                </EditItemTemplate>
                <HeaderTemplate>
        

Open in new window

0
Razor# MVC

I have a javascript function that is called when a drop down is changed. this function calls a code behind function in the controller. the problem is the js function does not wait for the function to run, it never calls success or error. Once the java script function exists then the function called in the code behind runs.

Can anyone advise on how to make the javascript function wait while the code behind function is called and returns?

Javascript
function toggleDIvDisplay(e) {
        debugger;
        var result;
        $.ajax({
            type: "POST",
            url: '@Url.Action("FleetSelect", "Reports")',
            data: "{'value':'" + e + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                result = data;
                if (data == "OK") {

                }
            },
             error: function () {
                alert("Failed to load Item");
            }
        });

        if (result == "123") {
            $('#divtwo').show();
        }
        else {
            @* $('#divtwo').hide(); *@
        }
    }

Open in new window



Code behind controller
 public JsonResult FleetSelect(string value)
        {
            List<ReportType> rList = GetReportList();
            foreach (ReportType rt in rList)
            {
                if (rt.id == Convert.ToInt32(value))
                {
                    if (rt.vehicle)
                    {
                        return new JsonResult { Data = "V" }; 
                    }
                    else
                    {
                        return new JsonResult { Data = "F" };
                    }
                }
            }
            return new JsonResult { Data = "V" };
        }

Open in new window

0
Anyone aware of a community or website that i can list work packages for our ERP upgrade.

I would appreciate any help.

Best,

Ross
0
What is the proper way to format and write to a pdf file using VS C#? I need to generate reports off a grid and output to a pdf file that is very nicely formatted with titles and date stamps and then the data.
1
I am dumping the content of a multidim array into excel via openxml.
It works but when I open the excel file, the numbers are stored as text which displays the little green triangle in the upper left of the cell.

Here is how I add the rows/cells and assign the array value.

  int arrayCounterID = 2;
                for (uint j = 2; j < rplUpdatedData.GetLength(0); j++)
                { 
                    row = new Row() { RowIndex = 7 + j };
                    uint rowNumber = 7+j;
                    
                    for (int i = 0; i < 15; i++)
                    {

                        Cell cell = new Cell()  
                        {
                            CellReference = data[i] + rowNumber.ToString(),                 
                            DataType = CellValues.String,
                            CellValue = new CellValue(rplUpdatedData[j, arrayCellID[i]].ToString()),
                            StyleIndex = 4
                        };

                        row.Append(cell);
                        arrayCounterID++;
                    }             
                sheetData.AppendChild(row);

Open in new window



I add an if statement to test the array value and set the datatype and value.

int arrayCounterID = 2;
for (uint j = 0; j < rplUpdatedData.GetLength(0); j++)
{ 
    row = new Row() { RowIndex = 7 + j };
    uint rowNumber = 7+j;

    for (int i = 0; i < 15; i++)
    {

	Cell cell = new Cell()  
	{ CellReference = data[i] + rowNumber.ToString(), StyleIndex = 4 };

	double isNum = 0;

	if (Double.TryParse(rplUpdatedData[j, arrayCellID[i]].ToString(), out isNum))
	{
	    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
	    cell.CellValue = new CellValue(rplUpdatedData[j, arrayCellID[i]].ToString());
	}
	else
	{
	    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
	    cell.CellValue = new CellValue(rplUpdatedData[j, arrayCellID[i]].ToString());
	}                    
	
	row.Append(cell);
	arrayCounterID++;
    }

sheetData.AppendChild(row);
}

Open in new window



This creates the excel file and the XML source looks ok but the Excel file appears corrupt and will not open.
Any thought on my approach?
0
I have a library with an on modified workflow and an event receiver which listens for ItemCheckedIn.

In the event received,  I check out the item, turn off EventFiring, update a column and then turn it back on and check the item back in.

The workflow and the receiver a colliding.  The workflow needs the item to be checked in to run and the event receiver checks it out,  and changes the item which in turn calls the Workflow.

I am not sure what to do to handle this.

  • Make the workflow start manually
  • Find a way to let the workflow run even if the item is checked
  • Other?

Any ideas on this would be greatly appreciated.

I thought that perhaps I will change the workflow to manual not on update and kick off the workflow at the end of the event receiver, but the following code doesn't find the workflow (it is using the SharePoint 2013 Workflow Template).

 public void StartWorkflow(SPListItem listItem, SPSite spSite, string wfName)
        {
            SPList parentList = listItem.ParentList;
            SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
            foreach (SPWorkflowAssociation association in associationCollection)
            {
                if (association.Name == wfName)
                {
                    association.AutoStartChange = true;
                    association.AutoStartCreate = false;
                    association.AssociationData 

Open in new window

0
OK so we have an in house marketing database that used to connect to a remote MySQL database on a Linux server. I decided to migrate to a MySQL server on our in house computer that also serves as the domain controller. everything is working fine except when I try to export a CVS. This was all operational when it was connecting to the Linux server prior. Please give me a hand guys!

The error that I am getting is below:
MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered during command execution. ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered attempting to read the resultset. ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Reading from the stream has failed. ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at …
0
Trouble with workflows that don't want to terminate.  I have workflows using the 2013 template that show completed, but still are in the running list.  I've looked at PowerShell and a C# console application to terminate them.

I haven't found a C# snippet that works nor a PowerShell snippet.

I also need this functionality for 2010 template workflows.

Any advice on all this would be appreciated.
0
I am trying to connect to a MongoDB database with asp.net core in C# with a userid and password.  Can anyone assist me in that respect?
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).