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 am using ASP.NET MVC 5 with entity framework. I have an existing SQL database that houses a table with a path and name for an attachment (Attachment) that links to another table (Meeting). I want the details view of the Meeting to show the name of the attachment and a link to download the attachment. The attachments are stored on a server on the same network. The attachments are not housed in SQL. I will also want to update the create view to create an attachment but I want to tackle one thing at a time.

Sidenote: This project was created using Entity Framework scaffolding so most of the code is default created from the scaffolding.

Meeting Details View

@model CRM.Models.Meeting

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div id="MeetingDetails">
    <h4>Meeting</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.InteractionDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.InteractionDate)
        </dd>
        <br />
        <dt>
            @Html.DisplayNameFor(model => model.Notes)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Notes)
        </dd>
        <p />

        <dt>
            @Html.DisplayNameFor(model => model.CustomerCallDecisionedBy)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CustomerCallDecisionedBy)
        </dd>
        <br />
        <dt>
            @Html.DisplayNameFor(model => 

Open in new window

0
Thanks to some expert advice obtained from this web site I can now successfully print a text file complete with a print dialog box. As was to be expected the users are now requesting the output to also be available in pdf format plus they want some values to be bold and others in a different font. Using C# how do I go about creating a pdf file and then formatting values on a record? Any tips and/or links would be greatly appreciated.
0
I have 2 entities bounded together with a join table. Creating the article works fine. Updating the article entity throws this exception:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_ArticleGroups_Articles_ArticleID". The conflict occurred in database "myDB", table "dbo.ArticleGroups", column 'ArticleID'. The statement has been terminated.

Below is my classes and setup

User.cs

public int UserId { get; set; }
public string FullName { get; set; }
public virtual ICollection<GroupUser> GroupUsers { get; set; } = new List<GroupUser>();

Open in new window


Article.cs

public class Article
{
    public int ArticleId { get; set; }
    public string Title { get; set; }
    public virtual ICollection<ArticleGroup> ArticleGroups { get; set; } = new List<ArticleGroup>();
}

Open in new window


Group.cs

public class Group
{
   public int GroupId { get; set; }
   public string GroupName { get; set; }
   public virtual ICollection<ArticleGroup> ArticleGroups { get; set; } = new List<ArticleGroup>();
   public virtual ICollection<GroupUser> GroupUsers { get; set; } = new List<GroupUser>();
}

Open in new window


Join Tables

GroupUser.cs

public class GroupUser
{
        public int UserId { get; set; }

        public User User { get; set; }

        public int GroupId { get; set; }

        public Group Group { get; set; }
}

Open in new window



ArticleGroup.cs

public class ArticleGroup
{
   public int ArticleId { get; set; }
   public Article Article { get; set; }
   public int GroupId { get; set; }
   public Group Group { get; set; }
}

Open in new window


AppDbContext.cs


Open in new window

0
Hi Team,

We have below google map which is being generated dynamically by google API’s. we are supposed to write test cases for example

1.      Need to click on the vehicle which is in operation now and perform some test.
2.     How can I search for the particular vehicle whose div contains some special text like "currently in operation"  or "vehicle is off" etc ?

Issue: In the above requirement you can not find any id associated with a vehicle, when one will inspect in the browser rather they will file HTML like “//*[@id="Test"]/div[1]/div”, which eventually will change if DB changes.GoogleMap_VehicleLocation
appreciate any suggestion from experts. I am currently using selenium with c# to handle such thing.
1
Hi,
Thanks foe helping me.
Am using VS 2013 professional , C#. Am having issue in running the application. I am new to this project and every body in this team is also new and no knowledge of .net applications. I took the code from the system. The code was already deployed in server and running actively. I couldn't attached the screen shots ( solution explorer,  Dev url which is running actively,etc ) because my system is restricting to upload doc and pictures.

DEV URL: https://devip/DuLogin.aspx

This DuLogin.aspx is resided under Login project  (class library).



Also i see how to add additional docs or information you request going forward from my other personal laptop.

Kind regards,
Pooja
0
I have a multithreaded (threadpool) console app which imports large amounts of records (each record is approx 2kb) from a microsoft message queue

This console app sits on a server and its sole job is to take the records from the queue, process the data, and save to a DB

We are trying to get to around 500 messages a sec, however we cannot seem to get above 100
We have done various things, the current investigation showed on 70 threads were running (in task manager)
We added the following lines of code to the app in a hope that would solve the issue
 ThreadPool.SetMinThreads(100, 100);
 ThreadPool.SetMaxThreads(10000, 10000);

Open in new window


We saw the threads rise from 70 to 140, however, it still took around 10 mins to process 50,000 records, so we are thinking if we can increase the amount of threads then it should crunch through the data quickly

The machine sits on around 7% cpu when this is running, with plenty of other resources and head room

I know without all the code etc its hard to comment, but could someone please help in pointing me in the right direction on things to try
My first issue is why it cannot spawn more threads

We have used threads (not threadpools) previously, this resulted in high cpu, but we saw threads go up to the 1000's

This is obviously a complicated subject, but hoping  someone could shed some light on areas to focus on first
0
Have a Json file that was able to convert and load into a class where I added to a form to view the results. What I really want to do is upload to a database. So the first part was done in a project called Cm.UI. The uploading to a database I want to do in a separate project called Cm.Data. Problem is i can't figure out how to pass the results to the other project to process. first set of code is the JsonConvert portion:
private void Form1_Load(object sender, EventArgs e)
        {
            string filePath = System.IO.Path.Combine(_desktop, "Upload.txt");

            Upload data = JsonConvert.DeserializeObject<Upload>(System.IO.File.ReadAllText(filePath));
            UploadData(data);
            UploadToDb.ProcessData(data);
        }

Open in new window


The Last line is the issue. This is what was recommended to fix the error in the data project:
 public static void ProcessData(Cm.UI.frmProcessJsonFile.Upload data)
        {
           
        }

Open in new window



But that doesn't work. get UI can't be found. What am I doing wrong? New to C #. Using VS 2017
0
I have a task that requires me to receive a RARP request with  MAC address and then to send out a RARP Response mapping that MAC to an IP. I understand the concepts behind RARP but am simply having an issue finding examples for building RARP packets in C#. I was wondering if anybody can point me in the right direction for building the actual packet.
0
I have the following if statement that I'm returning a model if it match my current model. I'm trying to re write the example bellow without an if else statement. Any suggestions would be great...

        public ActionResult ReportWriter(ReportRequestViewModel viewModel)
        {
            bool hasAccess = true;
            if(!hasAccess)
            {
                return RedirectToAction("Index", "Reports", new { area = "Reports" });
            }
            ViewBag.IsAngularJS = false;
            var model = GetViewModel(viewModel.ReportType.ToString(), viewModel.ConfigurationId);
            var type = model.Data.GetType().Name;
            ReportViewModel vm = null;
            #region ViewModel Casting
            if (type.Equals("SalesReportViewModel"))
            {
                vm = model.Data as SalesReportViewModel;
            }
            else if (type.Equals("CustomerReportViewModel"))
            {
                vm = model.Data as CustomerReportViewModel;
            }

Open in new window

0
I have a chart control in asp.net that I am trying to display annotation in the chart area - topcenter of 'ChartArea1'.  It does not display on the chart.

Why?

Below is my asp.net code

<Annotations>
                                        
                                            <asp:TextAnnotation Alignment="TopCenter" Font="Arial, 10pt" ForeColor="#00FFCC"
                                                Name="Chart1Annotation" Text="Nominal" TextStyle="Default" ClipToChartArea="ChartArea1">
                                            </asp:TextAnnotation>
                                        </Annotations>

Open in new window

0
Hi I am using Authorize.net for payment gateway in my Asp.net code, It suddenly stopped working few days back, I want to fix that immediately, Please help me,
I am getting error on below line
myWriter = new StreamWriter(objRequest.GetRequestStream()
Error is The exception message is 'The request was aborted: Could not create SSL/TLS secure channel.'. See server logs for more details.
Here is code, My windows machine is Windows server 2008 and I have installed Framework 4.5.

    I tried to setup that on Windows server 2012 R2 and it is working fine there, Problem is in current Production machine which is 32bit machine, Is Authorized.net not compatible with 32 bit machine? Please let me know.

 
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        String ApiLogin = System.Configuration.ConfigurationManager.AppSettings["ApiLoginL"];
        String TransactionKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKeyL"];

    
        String post_url = "https://secure2.authorize.net/gateway/transact.dll";

        Dictionary<string, string> post_values = new Dictionary<string, string>();

        post_values.Add("x_login", ApiLogin);
        post_values.Add("x_tran_key", TransactionKey);
        post_values.Add("x_delim_data", "TRUE");
        post_values.Add("x_delim_char", "|");
        post_values.Add("x_relay_response", "FALSE");

        post_values.Add("x_type", "AUTH_CAPTURE");
        post_values.Add("x_method", 

Open in new window

0
Hi I am using Authorize.net for payment gateway in my Asp.net code, It suddenly stopped working few days back, I want to fix that immediately, Please help me,
I am getting error on below line
myWriter = new StreamWriter(objRequest.GetRequestStream()
Error is The exception message is 'The request was aborted: Could not create SSL/TLS secure channel.'. See server logs for more details.
Here is code, My windows machine is Windows server 2008 and I have installed Framework 4.5.

 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        String ApiLogin = System.Configuration.ConfigurationManager.AppSettings["ApiLoginL"];
        String TransactionKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKeyL"];

   
        String post_url = "https://secure2.authorize.net/gateway/transact.dll";

        Dictionary<string, string> post_values = new Dictionary<string, string>();

        post_values.Add("x_login", ApiLogin);
        post_values.Add("x_tran_key", TransactionKey);
        post_values.Add("x_delim_data", "TRUE");
        post_values.Add("x_delim_char", "|");
        post_values.Add("x_relay_response", "FALSE");

        post_values.Add("x_type", "AUTH_CAPTURE");
        post_values.Add("x_method", "CC");
        post_values.Add("x_card_num", OrderD.CARDNUMBER);
   
        post_values.Add("x_card_code", OrderD.CVV);
       
        post_values.Add("x_exp_date", OrderD.MONTH + "" + OrderD.YEAR);…
0
I had this question after viewing How to use OpenRequest() of CHttpConnection?.

I need to send a POST to Google.Vision server, using MFC and c++. The code is the following:

        CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded");
      CString strFormData = "{'requests':[{'image':{'source':{'imageUri':'https://www.galileo2000.it/download/1.jpg'}},'features':[{'type':'FACE_DETECTION'}]}]}";

      CInternetSession session;
      CHttpConnection *pConnection = session.GetHttpConnection(_T("https://vision.googleapis.com/v1/images:annotate?key=MY_GOOGLE_API_KEY"));
      CHttpFile *pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,_T("https://vision.googleapis.com"));
      BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strFormData,strFormData.GetLength());


Actually I am not very fond on these topics, so I got the above code in Internet. But I successfully wrote a WebService in C#, which works. The strFormData is the same I use in the WebService, so it should be correct. The main doubt is the second parameter of the OpenRequest. Of course I get an error "Impossible to resolve the server or the address". (Unluckily the message is in Italian and I translated back to English, so the actual error message could be slightly different).
Thanks
0
This question is a two parter. First of all, using C#, is there a way to check the specific encoding information on a .WAV file? I know I am able to check things like the sampling rate, number of channels, etc. But I want to be able to detect if the .WAV file uses either µ-law (u-law), PCM, or any other formats I'm not aware of.

If the .WAV file turns out to be something other than µ-law, how do I convert the .WAV file into µ-law using C#?
0
I have a several JSON source files (about 500 MB total size, with 76,000 individual records) that I'm working on importing into a SQL database using C#.  I prefer importing into SQL using SQLBulkCopy, but to use that for multiple tables I would need to effectively create the entire database in C# before importing, or else read through every JSON file once for each table I'm importing.  

Neither option which seemed good to me, so I have written code to import each line of data individually using parameterized SQL queries, but that hits the database once for each record on each table.  There is also a potential problem in that our database has a record keys table for the primary key on each database table, and in order to not be writing to that table after every row insert (doubling the number of database writes), I'm keeping track of it in C# and updating it at the end.  The code to keep track of the value is more complicated than I would like, which means the risk of an issue is higher than updating it once after a SQLBulkCopy.

The most important question is which would be faster, parsing the JSON files once for every database table and using SQLBulkCopy for one insert per table, or parsing the JSON files once and writing each individual line?  Also, if the times are similar, it might be worth rewriting it to parse the files once for each table anyway, just to make the code simpler and reduce the likelihood of primary key errors.
0
I am trying to get a object out of IEnumerable collection which is in Dictionary.

I have a method which return IEnumerable of Employees. so In my code I am saying:

var emplist = employeelist.GetEmployeelist(ids);

Open in new window


I want a get a object depeding on the key i.e empid. So I am saying:

if(emplist.containKey(id)) { var emp = emplist.where(x => x.key == id);

Open in new window


so I am hoping that i would get the employee object in emp and can go though the emp object like emp.id, emp.name etc.

Could you please let me know how can i get the object from IEnumerable collection which is in Dictionary?
0
https://developers.google.com/calendar/quickstart/dotnet
I hope to get list of music concert event based on the zip codes
and I used above google api.

can you guide me how to filter just music event and zip?

I use c#
0
I need help using CKEDITOR with my form text area field.  http://docs.cksource.com/CKEditor_3.x/Users_Guide
I have a form field that is a text area. I need to update this field so that it works like a Rich Text Editor.  I have included the javascript file in my layout view as:
<script type="text/javascript" src="~/Scripts/ckeditor/ckeditor.js"></script>

My Database has a field for the Comments field that is a varchar(MAX) data type.
The Form View has a Text area field:

<div class="col-xs-6">
                @Html.TextArea("newComment", null, new
       {
           @class = "form-control",
           @type = "grow"
       })
</div>

I just display the notes as:  @note.Content
The onclick event of the Submit Button has:  onclick="editCR.addNote();

The JavaScript for addNote:
addNote: function () {
        this._post(SubmitNoteURL, {
            id: this.id,
            content: document.getElementById("newComment").value
        }, function (data) {
            var commentDiv = document.getElementById("commentArea");

            var para = document.createElement("p");

            var contentSpan = document.createElement("span");
            contentSpan.innerHTML = data.content;
            para.appendChild(contentSpan);

            document.getElementById("commentArea").appendChild(para);
        });

The controller to Add the Note:

public class NoteController : Controller
    {
        [HttpPost]
        public JsonResult Add(int…
0
This code in Java works perfectly:

    URL url = new URL(PREREQ_URL);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", authorization);
    System.out.println(authorization);

    InputStream is = (InputStream) con.getInputStream();
    BufferedReader in
            = new BufferedReader(new InputStreamReader(is));

    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();

Open in new window


I am trying to convert it into C# and I am getting
System.Net.WebException: 'The underlying connection was closed: An unexpected error occurred on a send.'

This is what I have:

    Uri prereqUri = new Uri(PREREQ_URL);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(prereqUri);
    //request.Headers["Authorization"] = authorization;
    request.Headers.Add("Authorization", authorization);
    //request.PreAuthenticate = true;
    request.Method = "POST";
    //var postData = "Authorization=" + authorization;
    //var data = Encoding.ASCII.GetBytes(postData);
    //request.ContentLength = data.Length;

    //using (var stream = request.GetRequestStream())
    //{
    //   stream.Write(data, 0, data.Length);
    //}

    var response = (HttpWebResponse)request.GetResponse();

Open in new window


I have also tried the commented out code with the same problem. Any ideas, please.
0
Hello,

I have always been a c#, .NET developer and our company is gradually transitioning to MVC and Angualr.  I am very new to MVC and Angular concepts, done a few courses about Angular and MVC on plural sight since last week and that is where I am at currently.

One the tasks I have on hand is to display a modal pop from from which needs to triggered to display from an MVC controller based on certain conditions and this modal pop up form which is a very basic form needs to be displayed using Angular.

This Modal pop up is as simple as it gets and will have a text box which needs to have an input of a 14 digit alpha numeric characters ( failure on providing it will show a validation error message on the modal pop up itself) a submit and a cancel button. On click of the submit button (after validation), the MVC controller needs to receive this value and continue its normal process.

Currently the MVC page where the modal pop up needs to be displayed has a few controls and a button. On click of this button the MVC controller calls the data access method and stores certain values in the DB. But if this 14 digit code is missing it currently throws an exception. Hence the need to for a modal popup for the user to enter the missing data.

I would very much appreciate if you can point me in the right direction by providing me some useful links or some code samples.

Thanks in advance AJ
0
dateshit.JPG

everything looks right why is it still throwing that stupid error, i hate strings and date they need to do something regarding this :(
0
I have an MVC 5 project where I have local processing RDLC reports using report viewer 14. For some reason I have a report that is called and after about 1 minute and 40 seconds and my site says that "No data was heard from..." in Chrome, and in IE it thinks there is a DNS problem after that 1 minute and 40 seconds. I have confirmed the SQL Query running in just a second. I am thinking that the biggest time factor is I am using a Matrix in my report.

I guess I would like to know how to extend my timeout. I have had other stored procedures that take a long time to run and I used the below reference and it fixed that. But I do not know how to fix this problem.

https://www.codeproject.com/Questions/238245/Dataset-xsd-Timeout-Problem
0
I need to build a aspx page that collects data.
On the page I have a dropdown for the number of people attending the event.
I want a dynamic  form that requests attendees information, but only for the number of attendees.
This has to live in the .net world
0
I've written a C# asp.net application that uses Microsoft.Office.Interop.Excel.  Application creates an Excel spreadsheet, saves it and then tries to close and quite Excel but the Excel process is still running in the Task Manager.  (same code works in a console app or Windows Forms application but not in my asp.net web app).

Here is the basis of the code:

using MyExcel = Microsoft.Office.Interop.Excel;
.
.
.
MyExcel.Application xlApp;
MyExcel.Workbook xlWorkBook;
MyExcel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
.
.
 xlApp = new MyExcel.Application();
 xlWorkBook = xlApp.Workbooks.Add(misValue);
 xlApp.DisplayAlerts = false;
 xlWorkSheet = (MyExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 xlWorkSheet.Name = "Daily Report";
.
.
xlWorkBook.SaveAs(myFile, MyExcel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, MyExcel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();

Open in new window

0
Hello, and thank you for your assistance!

I would like a graphical design interface to edit and dress up some web pages that I will create using Microsoft C# MVC Code First migrations, which create CSHTML files with Razor code within them.  Is there a tool that will let me drag & drop, etc., move things around visually and let the tool change the file as I design it?  And if there are several, which one or ones are the easiest to learn & use?  I am also in a time crunch with this project.  

Many thanks!

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