[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

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

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
Build an E-Commerce Site with Angular 5
LVL 12
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Although this adds multiple sheets, it corrupts the excel file.

 using (SpreadsheetDocument document = SpreadsheetDocument.Create(@"C:\Users\Public\Documents\sheets10.xlsx", SpreadsheetDocumentType.Workbook))
            {
                //// Add a WorkbookPart to the document.
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();
                //// Add a WorksheetPart to the WorkbookPart.
                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet(new SheetData());

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                for (uint i = 0; i < 6; i++)
                {
                    Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = i, Name = i.ToString() };
                    sheets.Append(sheet);
                }

                workbookPart.Workbook.Save();
            }

Open in new window


Can someone advise why this does not work.
0
I used sendgrid azure to send email out using their SMTP service below. It returns no error message but the email does not send when I develop the code at Starbucks. Do you know why and what goes wrong?


public static string SendEmailByAPI()
        {
            var apiKey = System.Environment.GetEnvironmentVariable("SG.PUdwvPvERBWBYtjuplC5bg.zUkpRwBfbasdfasdfdashX3frMDWxjbcv4LFUacVtD-lrORlUFkbqA");
            var client = new SendGridClient(apiKey);
            var msg = new SendGridMessage()
            {
                From = new EmailAddress("ryu@suresadfasdfco.com", "DX Team"),
                Subject = "Hello World from the SendGrid CSharp SDK!",
                PlainTextContent = "Hello, Email!",
                HtmlContent = "<strong>Hello, Email!</strong>"
            };
            msg.AddTo(new EmailAddress("ryu@suasdfasdfreco.com", "Test User"));
            var x = client.SendEmailAsync(msg);
            return "Success " + x;
        }

Open in new window

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 want the code to look beautiful but have Bugphobia .
Let me explain my fear:I am afraid to add wired spaces to break my code I want a convention to help me make it look nice without breaking it.
this is  post request of the real code where I changed the secret fields to pseudo fields .
look how beautiful the JavaScript looks like but it's deceiving as i am going to transform all VALUES into variables later (json does not like variables).
Here is the javascript (which looks good ):

var data = JSON.stringify({
  "fields": {
    "horse_colour": "brown",
    "birth_date": "2011",
    "sire_name": "sire name",
    "dam_name": "dam name"
  }
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://breeding-portal.mystagingwebsite.com/wp-json/acf/v3/listings/726");
xhr.setRequestHeader("authorization", "Basic bG93ZXNhbGV4QGdtYWlsLmNvbTpNYXJ0eW1jZmx5MTIz");
xhr.setRequestHeader("content-type", "application/json");

xhr.send(data);

Open in new window


This is a working C# code using RESTSHARP (which I am looking for a pretty way to organise it READY FOR VARIABLES.(the values).

var client = new RestClient("https://breeding-portal.mystagingwebsite.com/wp-json/acf/v3/listings/726");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic bG93ZXNhbGV4QGdtYWlsLmNvbTpNYXJ0eW1jZmx5MTIz");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "\t{\n  \"fields\": {\n\t\t\"horse_colour\":\"brown\",\n\t\t\"birth_date\":\"2011\",\n\t\t\"sire_name\":\"sire name\",\n\t\t\"dam_name\":\"dam name\"\n  }\n}\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request); 

Open in new window

0
Is it possible to use Visual Studio and step through debug of a REST service using the WCFTestTool? If so, how is that done?  I have a set of SOAP WCF services but I need to do a REST as well. I know one can do a WebInvoke after the OperationContract like:

[WebInvoke(Method = "POST", UriTemplate = "/GetTest",  RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

The code is C# and Visual Studio 2017.

I do *not* have localadmin access.

Any information on that would be greatly appreciated.

Thanks!
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
Hi This is following on from here

As a learning exercise I'm retrieving and updating an XML file of TV show  information  

It occurred to me that it's possible to have multiple seasons to the same TV show so I adjusted the XML accordingly
TV.XML
<?xml version="1.0"?>
<TV>
  <Show>
      <Name>MacGyver 2016</Name>
      <FolderName>MacGyver 2016</FolderName>
      <TMDBid>67133</TMDBid>
      <Season>
        <SeasonNumber>3</SeasonNumber>
        <Episode>
          <EpisodeNumber>1</EpisodeNumber>
          <EpisodeName>Improvise</EpisodeName>
          <BackDrop>https://image.tmdb.org/t/p/w350_and_h196_bestv2/eQMVJkBltvID73sh9vvTistssS6.jpg</BackDrop>
          <FullPath>J:\Media\TV\MacGyver (2016)\S03\Macgyver.2016.S03E01.Improvise.mp4</FullPath>
        </Episode>
      </Season>
      
  </Show>
</TV>

Open in new window


Of course this broke the LINQ query from the previous so answer

How do adjust the select query bellow to retrieve Episode data which is now nested in Season?

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

namespace XmlReader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the XML Document using Linq to XML
            var xdoc = 

Open in new window

0
Need some good technology news sources for .NET Full Stack development and the Microsoft Stack

What are good news sources for me to read and learn about what technologies are coming next and which new technologies are being adopted more that expected or less than expected?

Thanks
0
I saw this example but this is using JavaScript

ASP TextBox JavaScript OnKeyup Event
https://forums.asp.net/t/1656156.aspx?onkeyup+in+asp+textbox

I want to use C# or VB

On a ASP.NET Web Forms page.

I have a TextBox that looks like this:

<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>


When I click in the textbox with my mouse how do I save the text "you clicked in the textbox" to a ASP Hidden Field using C# or VB?
1
C++ 11 Fundamentals
LVL 12
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

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

I have a simple SQL query in a c# project that I have to convert to LINQ but am struggling with it due to my very limited experience and understanding of LINQ queries.  What's stumping me is how to handle the summing and grouping.  This is a pretty time sensitive project for me and once I see how it's done I'll be able to understand and build on it.
Here is the query:
SELECT Dept, Shift, ShiftDate, FLOOR(SUM(RunningGoal)) AS Target, SUM(UnitsProd) AS Produced 
FROM Vw_PRODCOUNTER_HourlyProduction 
WHERE Dept = '3500A' AND Shift = '1' AND ShiftDate = '12/13/2018' GROUP BY Dept, Shift, ShiftDate

Open in new window

Thanks for your time and help in advance.  Have a good day!
JeffH
0
I am trying to use child rows datatables found at:  https://www.datatables.net/examples/api/row_details.html

I have a Controller that returns my SQL View as a List:

 public ActionResult List()
        {
            MyDB DB = new MyDB();

            List<vw_Report> data = (from x in DB.vw_Report
                                                    select x).ToList();

            data = (from x in vw_Report.GetRows()
                    select x).ToList();

            return View(data.ToList());
        }

My View follows the example provided:

    @model List<master.path.Models.vw_Report>
        @{
            ViewBag.menu = false;
        }

        <!DOCTYPE html>
        <html>
        <head>
            <meta name="viewport" content="width=device-width" />
        </head>

        <body>

            <h1 style="text-align:center">Report</h1>

            <div style="padding: 25px;">
                <table class="DTStyle" id="List">
                    <thead>
                        <tr>
                            <th>

                            </th>
                            <th>
                                Text Field 1
                            </th>
                            <th>
                                Text Field 2
                            </th>
                            <th>
                                Text Field 3
                            </th>
                            <th>
 …
0
This works but I wonder if there's another way of writing foreach. If not, I'll keep what I have

var nn = q.Select(x => x.Schedule); //scheudles that don't have authusers attached to them
var p = CurrentContext.Schedules.Select(x => x.AuthUsers.Where(u=> u.ID == user.ID)).ToList(); //list all schedules and their authusers

	foreach (var row in p)
	  {
		foreach (var s in row)
		  {
		    if (s.ID == 72)
			{
				//var f = s.Schedules;
				//var t = f.Select(x => x.AuthUsers);authuser for the schedule

				foreach (var ss in nn)
				{
						
				  var schedId = s.ID;
				  ss.AuthUsers.Add(new AuthUser()
					{
						ID = s.ID
					});
	}
	   }

Open in new window

0
Hi;
here is my story
--Total Record -- 5000 records  
---Bringing Data from Database using lambda expression....
var dtTable = objHRContext.BscTbls.Select(X => X ).ToList ();  

Open in new window

 
--it takes 0 second bringing data from database.....
--binding  Data to gridview  with DataTable it takes 10 seconds... Here is my problem
 
 gvData.DataSource = dtTable;
  gvData.DataBind();

Open in new window

--Here is  my GridView Design view

 <asp:GridView ID="gv_EmpList"   runat="server" AutoGenerateColumns="False"
                    class="table table-striped" Width="100%">
                    <Columns>
                      
                        <asp:BoundField DataField="BscName" ItemStyle-Wrap ="true" HeaderStyle-Wrap ="true"  HeaderText="الاسم" />
                        <asp:BoundField DataField="RankDescription" HeaderStyle-Wrap ="true" HeaderText="grade" />
                        <asp:BoundField DataField="BscRank_Type_Desc" HeaderStyle-Wrap ="true" HeaderText="grade type" />
                         <asp:BoundField DataField="Unit_Name" ItemStyle-CssClass ="styleDisPlay" HeaderStyle-CssClass ="styleDisPlay" HeaderStyle-Wrap ="true" HeaderText=" grade type " />
                        <asp:BoundField DataField="BscNo" HeaderStyle-Wrap ="true"  HeaderText="emp number" />
                        <asp:BoundField DataField="LastPromDate" HeaderStyle-Wrap ="true" HeaderText="promotion date" />
                        <asp:BoundField DataField="Billet_Name" 

Open in new window

0
I have a c# application writing into a postgresql database through a stored procedure.

I have 2 input parameters  and 2 output parameters

I need to be able  to get the 4 (2 input and 2 output)  into some screen variables

The  scrip that runs the stored procedure is shown below;

        public void SelectUserProfile(UserProfileModel model)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(pgrstring))
            {

                using (var command = new NpgsqlCommand("public.spuserprofile_select", conn))
                {
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new NpgsqlParameter("usercodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = model.usercode });
                    command.Parameters.Add(new NpgsqlParameter("passwordx", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = model.userpwd });
                    command.Parameters.Add(new NpgsqlParameter("groupcodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Output, Value = model.groupcode });
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Output, Value = model.companycode });

                    string var01 = model.companycode;
                    string var02 = …
0
What does it takes to convert vb.net to c#? Is it worth the effort  . What benefits or worse situation expected?
0
Hi

Using the XML file bellow as a log I'm gathering information about TV shows using TMDB api (Not part of question just background)

How do I access each show name and its childs episodes details?

Ultimately I want to be able to access a  Episode path and if doesn't exist in the xml create a new entry or parent show

XmlReader
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace XmlReader
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(@"J:\Media\TV\TV.xml");
            XmlNodeList Nodes = xmlDoc.SelectNodes("TV/Show");
            for(int I =0; I <= Nodes.Count; I++)
            {
                Console.WriteLine(Nodes[I].Name); // This throws an error 
            }

            Console.ReadKey();
        }
    }
}

Open in new window


TV.xml

<?xml version="1.0"?>
<TV>
  <Show>
      <Name>MacGyver 2016</Name>
      <FolderName>MacGyver 2016</FolderName>
      <TMDBid>67133</TMDBid>
      <Season>3</Season>
      <Episode>
          <EpisodeNumber>1</EpisodeNumber>
          <EpisodeName>Improvise</EpisodeName>
          <BackDrop>https://image.tmdb.org/t/p/w350_and_h196_bestv2/eQMVJkBltvID73sh9vvTistssS6.jpg</BackDrop>
      <FullPath>J:\Media\TV\MacGyver (2016)\S03\Macgyver.2016.S03E01.Improvise.mp4</FullPath>
      </Episode>
  </Show>
</TV>

Open in new window



I'm assuming I would create a new episode by appending to it's parent show (something like bellow) but how do I find the correct show / season
Similarly How do create  a new show?

XmlNode EP = xmlDoc.CreateElement("Episode");
            XmlNode EpNum = xmlDoc.CreateElement("EpisodeNumber");
            EpNum.Value = "2";
            EpNum.AppendChild(EP);
            // repeate for each element

Open in new window

0
OWASP Proactive Controls
LVL 12
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

How to update a api Async?

Hi guys. I have a list of products and walts to update each product async
 foreach (var product in productlist)
{
    UpdateProduct(product);
   console.log(${product.productnumber} DONE);
}
How is this asynchronous ?
0
I hope someone can help me with this. Been at this all afternoon. I'l go step by step.

1. I have a table Schedule and AuthUsersSchedule.  For each Schedule row, we can have one or more users in AuthUsersSchedule. There's a FK relationship. Looks like this.
s1.png
s2.png
2. There's an EDMX. I see the Scheudle table in it but the AuthUsersSchedule is a navgiation property. In the code, I can't do dbcontext.AuthUsersSchedule. Looks like this

s3
3. I have a stored proc and I get the Schedules

var param = new SqlParameter() { ParameterName = "searchtext", Value = string.Concat('%',searchText,'%') };
var result = CurrentContext.Database.SqlQuery<SearchAssetModel>("[dbo].[usp_SearchAssets] @searchtext", param).ToList(); 

Open in new window


4. I populate the Scheudle like this

 Schedule = new Schedule()
			  {
				 ID = c.ScheduleId,
				 Sched = c.Sched,
				 MasterLeaseID = c.MasterLeaseID,
                                ......

Open in new window


But how do I populate AuthUsers? How do say.... give all the users in AuthUserSchedule with AuthUserSchedule.ScheduleId = Scheudle.Id.  I did this and getting errors

 Schedule = new Schedule()
			  {
				 ID = c.ScheduleId,
				 Sched = c.Sched,
				 MasterLeaseID = c.MasterLeaseID,
                                ......,
                                 AuthUsers = new AuthUser()
				  {

				 }

Open in new window


s4.png
If it helps, this is the entire code section that I populate Schedule




Open in new window

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 writing an application that sends JSON data to an Azure Event Hub.
My method for sending the data looks like this
 
 
        public async Task SendDataAsync(string data)
        {
            EventData eventData = CreateEventData(data);
            await _eventHubClient.SendAsync(eventData);
        }

Open in new window


The EventHubClient is created like this
 
       public DataSender(string eventHubConnectionString)
        {
            _eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString);
        }

Open in new window


and it is called in the application like this
           
 
            try
            {
                DataSender ds = new DataSender(_eventHubConnectionString);
                try
                {
                    Task tsk = ds.SendDataAsync(input);
                    response.Add("SendDataAsync", input);
                }
                catch (Exception taskException)
                {
                    response.Add("SendDataAsync", taskException.HResult + " : " + taskException.Message);
                }
                
            }
            catch (Exception ex)
            {
                response.Add("DataSenderError", ex.HResult + " : " + ex.Message);
            }

Open in new window


I am trying to build in as much error trapping as I can.
One of the scenarios that I foresee is that the connection string used to create the EventHubClient will be incorrect.
The try/catch around the creation of my datasender will catch a badly formed connection string but if the connection string is well formed but incorrect I can't find a way to trap that.
What I find is that the SendDataAsync method runs and returns a task, but data doesn't arrive at the event hub (because the connection string is incorrect) but I can't seem to identify how to trap that.
Any advice much appreciated
0
I need to copy a drop-down section on a form to another form element.

So I have a drop-down List:

<div class="row">
                        <div class="col-xs-6">
                            @Html.Label("Select one or more Item(s):")
                            @Html.DropDownListFor(x => x.List, sl.getItem(s)(), new
                       {
                           @type = "drop",
                           @multiple = true,
                           @style = "width: 100%",
                           @id = "List",
                           data_placeholder = "Select Item(s)",
                       })
                        </div>

                        <div class="col-xs-2 col-xs-offset-1">
                            <button type="button" class="btn btn-info" style="vertical-align:bottom;" onclick="NewRequest.copyList();">
                                Copy to Summary
                            </button>
                        </div>
                    </div>

The View also has:

<script type="text/javascript">
    var NewRequest = new NewRequestClass();
    NewRequest.init();
</script>

My JavaScript file has:

function NewRequestClass() {
    this.List;
    this.notes;
}

copyList: function (sender) {
        alert(this.List);
        this.notes = this.List;
    },

    //Maps variables to the correct field
    init: function () {
        this.List = document.getElementById("List");
        this.notes = …
1
I'm trying to add JavaScript validation to checkboxes and a text box in MVC.  Just can't figure out what I'm missing.  It's MVC and I'm new to this way of doing things.

My View has  form with checkboxes:

 <div class="row">
                        <div class="col-xs-1">
                            @Html.CheckBoxFor(x => x.test1, new
                                { @class = "form-control",
                                  @id = "test1"
                                })           
                        </div>

                        <div class="col-xs-4" style="margin-left:-20px;">
                            <div style="font-weight:600;">
                                Test 1
                                </div>
                            </div>

                        <div class="col-xs-1">
                            @Html.CheckBoxFor(x => x.Test2, new
                       {
                           @class = "form-control",
                           @id = "Test2"
                       })                      
                        </div>
                        
                        <div class="col-xs-4" style="margin-left:-20px;">
                            <div style="font-weight:600;">Test 2</div>
                        </div>
                    </div>

Open in new window


I also have this at the top of my view:

<script type="text/javascript">
    var NewRequest = new NewRequestClass();
    NewRequest.init();
</script>

Open in new window


On my submit button I have this onclick:  onclick="NewRequest.validateForm(this.form)";

The javascript file lools like:

function NewRequestClass() {
    this.Test1;
    this.Test2;
   
}

NewRequestClass.prototype = {

//Maps variables to the correct field
    init: function () {
        this.test1 = document.getElementById("Test1");
        this.test2 = document.getElementById("Test2");

    },

validateForm: function (sender) {

        if ((this.test1.checked == false) && (this.test2.checked == false)
        
        ) {
            swal({
                title: "Required Fields",
                text: "You must check at least one Request",
                type: "warning",
                showCancelButton: true,
                closeOnCancel: true
            });
        }

    },

}

Open in new window


I'm getting an error that test1 is undefined.  What am I missing?
1

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