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

Hi Experts,

I have the following code. Before @Html.ValidationSummary() I want to put a check, if 'InvaliFileFormat' div is visible then make it invisible.
[code]
 @using (Html.BeginFormAntiForgeryPost("/Contact", FormMethod.Post, new { @enctype = "multipart/form-data" }))
    {      
        @Html.ValidationSummary()
        if (Model.UploadIssueMessages != null)
        {
            <div class="validation-summary-errors" style="display:normal;margin-bottom: 0px;" id="InvaliFileFormat">
                <ul>
                    <li>@Model.UploadIssueMessages</li>
                </ul>
            </div>
        }}
[code]

Thanks in advance!
0
Rowby Goren Makes an Impact on Screen and Online
LVL 12
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

I am using DropZone but would like to send another form field to my controller.  I don't think I can add the form field inside the Form - other than as a hidden field.
I have my View as:

    @{
        ViewBag.menu = false;
        ViewBag.Title = "Upload New ARC Request";
        ViewBag.maxFiles = 1;
    }

<div class="col-xs-10">

        <div class="row">
            <div class="col-xs-6">
                @Html.Label("Title:")
                @Html.TextBox("NewTitle", null, new
           {
               @class = "form-control",
               @placeholder = "Enter Title",
               @id = "NewTitle"
           })
            </div>
          </div>

            <div class="row">
                @using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new
                {
                    @class = "dropzone dz-clickable",
                    @enctype = "multipart/form-data",
                    @id = "documentDropzone"
                }))
                {
                   @Html.Hidden("title", t)
                        <div class="dz-message">
                            Drop files here or click to upload.
                        </div>
                }
            </div>
            <script type="text/javascript">
                Dropzone.options["documentDropzone"] = {
                    maxFilesize: 10000,
                    acceptedFiles: "application/pdf"
                };
            </script>
        </div>

</div>

<script 

Open in new window

0
I'm getting an exception in my following line of code in my function.  My goal is to return the value of my resultsContainer if my switch statement is invoked.

            results = resultsContainer;  > Cannot implicit convert type System.Collections.Generic.List<XXX.Models.CustomReports.CreditHoldDetailsResults>
to xxx.Models.CustomsReport.CreditHoldResultsContainers.


    public static CreditHoldResultsContainer GetReportResultsObject(CreditHoldSearchCriteria searchCriteria
            , xxx.Models.Employee LoggedInUser
            , System.Globalization.CultureInfo systemCultureInfo
            )
        {
            var results = ServiceAssistantService.CustomReports.CreditHoldService.GetReportResults(searchCriteria, LoggedInUser.CultureInfo, LoggedInUser.ID.Trim().ToUpper());
            var resultsContainer = results.reportResults;
            var headerText = "";

            
         
            if (resultsContainer != null && resultsContainer.Any())
            {
                headerText = headerText + "  " + Sxxx.Tools.Language.Translate(Language.Keys.Sort_By, LoggedInUser.CultureInfo) + " : ";
                switch (searchCriteria.SortOrder)
                {
                    case 1:
                        resultsContainer = resultsContainer.OrderBy(x => x.CustomerNumber).ToList();
                        break;
                    case 2:
                        resultsContainer = resultsContainer.OrderByDescending(x => 

Open in new window

0
I want to disable a dropdown in my cshtml code

<dropdown dropdown-menu-items="results" option-label="Not Reviewed" class="jq-checker-inspection-dropdown" data-poi-index="@inspectionItem.PointOfInspection"></dropdown>

I tried disabled = "true" and that does not work.

I also have a boolean variable
isenable = false

and i tried something like this

<dropdown dropdown-menu-items="results" option-label="Not Reviewed" class="jq-checker-inspection-dropdown" data-poi-index="@inspectionItem.PointOfInspection" @(isEnabled ? "disabled" : "")></dropdown>

None of them work. can you please suggest on how i can diable the dropdown box.
0
I have a c# application that needs to write into a postgresql table using a stored procedure

I have tried the stored procedure manually to conform it allows the insert operation and its ok

I attached a step by step explanation of what i have done in the attached word file

The following is contained in the attachment

1.      Values in the Model Based on Debugger

2.           Stored Procedure scripts for the inserts

3.     .InvalidCastException: 'Can't write CLR type System.Int32 with handler type TextHandler'
        Error Screen during the execution of the script

4.      SCHEMA of the Table  into which I have already inserted a record to test the storedprocedure

What could i possibly doing wrong and how can i resolve the issue

Thanks

Oluwole
Error-Inserting-into-a-postgre-tabl.docx
0
I have a dropdown in my cshtml file and and need to disable and enable it based upon a variable value

var canEdit = false or var canEdit = true

so basically if value is false disable the dropdown or if true enable the dropdown

<dropdown dropdown-menu-items="results" option-label="Not Reviewed" class="jq-checker-inspection-dropdown" data-poi-index="@inspectionItem.PointOfInspection"></dropdown>

I want it to work that something like this

 <input @(isEnabled ? "" : "disabled") @(noId == savedId ? "checked" : "") class="form-check-input" type="radio" name="checker-verify-radio-@componentId" id="checker-verify-radio-no-@noId" value="no">

the above working code is for a check box.if its true i have the checkbox checked and if false then checkbox is unchecked.

similiarly i want to have my dropdowd disabled if canEdit = false  and dropdown enabled if canEdit = true
0
Hi,

I am trying to access some public properties I have in a form an C# does not let me see them.

What am I doing wrong?

Thanks,

Ward

// From the main from.

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 FormAccess
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            Form other_form = new OtherForm();

            // other_form.Test1 = "";  <-- Cannot see
            // other_form.Test2 = "";  <-- Cannot see

        }
    }
}

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 FormAccess
{
    public partial class OtherForm : Form
    {
        public string Test1 = "";
        public string Test2 { set; get; }

        public OtherForm()
        {
            InitializeComponent();
        }
    }
}

Open in new window

0
I have api mvc and just want to know what is the best practice for two items

1. I want to know how to ensure how many the api has been consumed and where.
0
I want to learn what is the best practice of using try catch inside of my class object. you can just assume I have simple database call and the class returns custom class like Person.

what I hope to get is when the error is occurred, a master log files will be written on it and I can have all of the log messages as I want.
0
Following on from @ gr8gonzo  comment here on serialize and deserialize XML

This will test if a show exist before adding it

            if(tv.Shows.Exists(show => show.TMBDBid == 77236))
            {
                Console.WriteLine("A Discovery Of Witches Exists");
            }
            else
            {
                tv.Shows.Add(new Show()
                {
                    Name = "A Discovery Of Witches",
                    FolderName = "A Discovery Of Witches",
                    TMBDBid = 77236



                });
            }

Open in new window


How do I test if an episode exists

Tried this but both produced errors so didn't  continue  with  Episode.EpisodeNumber etc
if (tv.Shows.Exists(show => show.TMBDBid == 67133 && show.Season.SeasonNumber))

// AND this
if (tv.Shows.Exists(show => show.TMBDBid == 67133 && show.Season => Season.SeasonNumber))

Open in new window


Again expanding on the example  How do I list the episodes?

         foreach (Show show in tv.Shows)
            {
                // Print out what TV shows are listed

                string ShowName = show.Name;
                string ShowID = show.TMBDBid.ToString();
                Console.WriteLine("ShowName: {0}, TMBDBid: {1} ", ShowName, ShowID);
                foreach (Season season in show.Season)
                {
                    String SeasonNumber = season.SeasonNumber.ToString();
                    Console.WriteLine("SeasonNumber: {0}", SeasonNumber);
                }
                foreach(Episode episode in show.season.)
                {
                    // How do I list the episodes?
                   //                Error	CS1061	'Show' does not contain a definition for 'season' and no extension method 'season' accepting a first argument of type 'Show' could be found
                }
            }

Open in new window


Also when adding a new show or episode can you add it in order of show name then SeasonNumber and finally EpisodeNumber
0
JavaScript Best Practices
LVL 12
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

0
Hi,

I am having .wsdl url. I am having these two information

1. SERVICEendPOINT: http://service.com/geocode2008?wsdl
2. WSDL location url: http://service.com/provider/geocode/2008/

How to use these in c# .net application. How c# client consumes this .wsdl? I have attached my .wsdl in the attachment.

If I enter Zipcode, How to call getGeocode? I am not sure what needs to be done.

Thanks
wsdl_xml.jpg
0
I have asmx and I hope to have html / jquery to consume it.
The asmx below using class library as parameter.

I do not know how to consume it on html/jquery. Can you show me how to do that?

Thanks,


[WebMethod]
        public string CreateDisciplinaryComplaintInPDF(Domain.DisciplinaryComplaint dd)
        {
            Controller.PDFservice ps = new Controller.PDFservice();
            Domain.DisciplinaryComplaint ddNew = new Domain.DisciplinaryComplaint();
            #region data mapping
            ddNew.fullName = dd.fullName;            
            #endregion
            string returnString =  ps.GetDisciplinaryComplaintDownloadData(dd);
            return returnString;
        }

Open in new window

0
I would like to skip expensive trip to the database and back in retrieving output and instead  save the results in memory.
What techniques in C# can do this.

I have a page with a series of questions and the only way I know is run a query to the database to get the output and I would like to know if there is another way to accomplish that.
0
I have an MVC Web application. On the cshtml page, I have a data table that I am trying to format a date like M/dd/yyyy. My issue is that when the date is null, it displays "1/01/0001". I would like for it to just display blank if it is null. My code is below.

                            <td>@jobinfo.MLR_Submission_Date.ToLocalTime().ToString("M/dd/yyyy")</td>

Open in new window

0
Hello Experts,
I have file in a network shared folder. I can access it from file explorer(\\10.0.1.22\Users\mm\Test.txt). But when I am trying to access it from the C# program it says file does not exists. Any suggestions?

FileInfo myFile = new FileInfo(@"\\10.0.1.22\Users\mm\Test.txt");
bool exists = myFile.Exists;

Thanks in advance.
0
I have an MVC C# Application. On the cshtml page, i have a date input field. Sometimes the user leaves it blank and sometimes fills it in. I need to evaluate whether the field is blank or not in the controller. If it is blank, I would like to insert a default value of '01/02/1901'. I'm using html 5.

input code is below:
<input type="date" name="Date Worked" id="add_Date_Worked" class="form-control" required />

Open in new window

0
I have a radiometric image (320px by 240px) with temperature data behind each pixel

I have extracted the temperature data and put into float[320, 240];
Then I can reference by X Y and get the temperature data


This all works fine, I over lay the temperature data over the image, and when the user hovers it shows the temperature data for that pixel

however I need to now increase the size of the image for display purposes and on hover show the temperatures, the image bit is easy, I just set in CSS

However, the original data (X Y pixels) also needs to be stretched so when the user hovers it shows the correct temperatures
The issue is the original data half the size, so would somehow need to duplicate diagonally

here is the code in question which gets the data into the float array.
I now need to return a float array of 640,480, with the correct pixel temperature data
Any idea how i would stretch the float array and maintain the correct pixel data considering the original is 320x240 and the output needs to be 640x480 ?

_tempData = new float[320, 240];

            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(tempContents)))
            {
                BinaryReader br = new BinaryReader(ms);
                for (int x = 0; x < 320; x++)
                {
                    for (int y = 0; y < 240; y++)
                    {

                        //write temp value for pixel
                        float pixelTemperature = 

Open in new window

0
I have an MVC C# application that requires a user to select a client from a drop down list "add_Client_ID". After the user makes a selection, I need to refresh the "add_Product_ID" drop down list with the filtered information. What is the best method for this? Can someone help.

Drop Down Code -----------------------------------------
                <div class="row mg-t-20">
                    <label class="col-sm-5 form-control-label">Client:</label>
                    <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                        <select name="Client_ID" id="add_Client_ID" class="form-control" required>
                            <option value="0">Select a Client</option>
                            @{
                                foreach (Client client in Model.Clients)
                                {
                                    <option value="@client.Client_ID">@client.Client_Name</option>
                                }
                            }
                        </select>
                    </div>
                    <label class="col-sm-1 form-control-label"><span class="tx-danger">*</span></label>
                </div>

                <div class="row mg-t-20">
                    <label class="col-sm-5 form-control-label">Product:</label>
                    <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                        <select name="Product_ID" id="add_Product_ID" class="form-control" disabled required>
                   

Open in new window

0
Exploring SQL Server 2016: Fundamentals
LVL 12
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

How can I draw or plot an oil well trajectory in 3D using C #. Please check the image attached.

Regards,

Dallag
open_wells_3d_1.png
0
I need a function that takes datetime variable and tests if it is a valid datetime. If it is, then format it into (yyyy-MM-dd) to go into a sql datetime field. If the datetime is not valid, return (1901-01-01). Language is c#.
0
I have an MVC C# Web Application where the user is not required to input a value in a date input field. If the user does not enter a date, MVC throws an error as it expecting a value. Below is my input code, model & controller information. What is the best way to handle if user does not supply a date and still insert data successfully into Sql using a stored procedure. The stored procedure is expecting a datetime as a parameter.

Controller Code -----------------------------------------------------------------------
        [HttpPost]
        [ActionName("AddTimeInfo")]
        public ActionResult AddTimeInfoPost(TimeInfo timeinfo)
        {
            if (ModelState.IsValid)
            {
                timeinfo.Created_By = Request.Cookies.Get("User_ID").Value;
                timeinfo.Updated_By = Request.Cookies.Get("User_ID").Value;
                try
                {
                    timeinfoDao.InsertTimeInfo(timeinfo);
                    TempData["Success"] = "true";
                }
                catch (Exception e)
                {
                    TempData["Success"] = "false";
                }
            }
            else
            {
                var errors2 = ModelState
                    .Where(x => x.Value.Errors.Count > 0)
                    .Select(x => new { x.Key, x.Value.Errors })
                    .ToArray();
                TempData["Success"] = "false";
            }
            return RedirectToAction("TimeInfo", 

Open in new window

0
I am getting trouble to read sheet name in the workbook.

Atleast if i get the index, then and there i could able to read the sheet based on worksheet name.

Let us say Example...

I am having multiple sheet like (A,B,C,D,E,F,G,H,etc,).

Suppose if i give "D", then it should return "3" (4th index)  (0 to 3)..

how to get this index in c#.net or linq C#
0
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

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