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

Hello,
Is  connection string we use in .net  have some option to connect via proxy.
For example if i need to connect Database on a remote or cloud environment, what should i use or if there is proxy set up required ,is there anyway we can do it in connection strings?

Please suggest.

Thanks.
0
Hello,
Just need an idea if it is possible to fill all the values or data for dropdown in background and then when dropdown control loads just show it.

This is for window form .net Application with C# coding enviornment.

Thanks.
Abhilash
0
Hello Experts,
I have an existing API which returns daily data on demand.  We need to get the data once a day at 9:00am.  I am planning to run a daily job, which will call the API to receive the data.
 Please let me know what is the best way to call it.  I mean to say should I use web service, window service or any better way?

FYI: I am going to use .net and C# code.

Thank you in advance.
0
Hello everyone !

I am new on this forum.
In fact, I have a big project which consists of developping a spectrum analyzer on a plateform called Adalm Pluto (Developed by Analog Devices).   In order to detect the Pluto device and communicate with it, we use a library called Libiio and we build it with visual studio (I have no problem on this side).

Now the problem is that I need to implement a FFT to the signal recieved by the Pluto device, and then plot the results within an interface.
I have tried to use the ILNumerics library which is a very performant library to do these stuff (I have already all the code done), but when I try to execute it, it dosen't work because apparently, the trial version of ILNumerics is not sufficient.
Can anyone please help me out on this ? Does anyone have an idea about this ILNumerics library and how to possibly get it for free ?
Or can anyone share an example code that does something similar to what I am trying to do ?

Thank you so much in advance.

PS: Iam using Visual Studio 2017 on windows 10. (with C# language)

Regards,
Ayoub
1
Why am I getting access denied when entering this through PSExec in my C# program

 string ip = getIP();
            string scope = @"-accepteula -d -i \\" + ip + @" -u frutarom\" + textBox2.Text + " -p " + textBox3.Text + " cmd /c " + @" \\njfs01\public\testing\bat files\IP Release-Renew.bat";
            ProcessStartInfo info = new ProcessStartInfo("psexec.exe", scope);

            info.UseShellExecute = false;
            Process p = Process.Start(info);

Open in new window


I have the same code, minus the path being different... the Path IS valid, and have used it on other programs before.

Here is my .bat file

Start-Process powershell -Verb runAs
ipconfig /all

TIMEOUT /t 40

Open in new window


I am trying to make even a simple one work, and even this is giving me access is denied.
0
Hello i am trying to do an asynch server tcp in c# and i get this error and can not resolve it please

Request for the permission of type 'System.Net.DnsPermission, System, Version=4.0.0.0,

thanks for your help

my code :
 public static void StartListening()
        {
        Console.WriteLine("started point");
            // Establish the local endpoint for the socket.  
            // The DNS name of the computer  
            // running the listener is "host.contoso.com".  
			
	    string host = Dns.GetHostName();
	    IPHostEntry ipHostInfo = Dns.GetHostEntry(host);
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.  
            Socket listener = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.  
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.  
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.  
                    Console.WriteLine("Waiting for a connection...");
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
     

Open in new window

0
Is there a way to configure windows 2016 to not show this dialog box and silently crash so another app can restart it automatically?
crash
If not open to other suggestions
Its a legacy app we have code for if we need to edit we can.
1
I have a web application that is leveraging Telerik RadGrid to display database content. Framework is MVC with C#. I am trying to display a bootstrap alert with a message "Record Successfully Added". The issue is the Bootstrap Alert is never displayed. When I move the code to a page without the RadGrid, the Alert displays perfectly...So I believe this is a timing issue. I believe the placement of the Alert could also be the issue, but I can't seem to get this to work. See chtml code below. @Html.Action("ShowAlert") is the call for the Alert which I can run in debug and see the alert populated.

@{
    ViewData["Title"] = "Meals";
    ViewData["Icon"] = "fa-utensils";
    ViewData["Subtitle"] = "Stay tuned, wonderful content will arrive here soon.";
}

<div class="br-section-wrapper">
    @Html.Action("ShowAlert")

    @(Html.Kendo().Grid<synergix365.Models.Maintenance.Master.Meals>()
                .Name("grid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.Meal_ID).Title("Meal ID").Visible(false);
                    columns.Bound(p => p.Coop_ID).Title("Co-op ID").Visible(false);
                    columns.Bound(p => p.Meal_Name).Title("Meal Name");
                    columns.Bound(p => p.Meal_Type_ID).Title("Meal Type ID").Visible(false);
                    columns.Bound(p => p.Meal_Type_Name).Title("Meal Type");
                    columns.Bound(p => p.Charge).Title("Charge");
                    columns.Bound(p 

Open in new window

0
Hi,

I want to get "complete" page source from webpage but the "view source" option shows only HTML.  The code I want to access is only viewed using "Inspect Element" in Chrome/Firefox. Is there anyway, in C# or VB.NET to get the contents of Inspect element of the page ?
0
I've got an app that I serve using ASP.NET MVC. It calls APIs in the same application.  The API controllers have the [Authorize] attribute assigned. The app uses Azure AD and has an OwinStartup class which authenticates. See below. This all works fine.

We now have a request to make the APIs visible to other applications. Is it possible to somehow make the APIs allow authorization if we send a bearer token which we get from Azure?

 public class Startup
    {
       string clientId = System.Configuration.ConfigurationManager.AppSettings["Azure.ClientId"];

        string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["Azure.redirectUrl"];

       static string tenant = System.Configuration.ConfigurationManager.AppSettings["Azure.Tenant"];

        string authority = String.Format(System.Configuration.ConfigurationManager.AppSettings["Azure.Authority"], tenant);

        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Passive,
                    // Sets 

Open in new window

0
i am trying to generate a csv file from query. The file gets generated at the folder path but it does not  bring up the download

 error.JPG
private void SQLToCSV(string query, string Filename)
        {
            try
            {


                string path = HttpContext.Current.Server.MapPath("~/Export" + "/" + Filename);
                paths = HttpContext.Current.Server.MapPath("~/Export" + "/");
                filenames = Filename;
                SqlConnection conn = new SqlConnection(con);
                conn.Open();
                SqlCommand cmd = new SqlCommand(query, conn);
                SqlDataReader dr = cmd.ExecuteReader();

                using (System.IO.StreamWriter fs = new System.IO.StreamWriter(path))
                {
                    // Loop through the fields and add headers
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        string name = dr.GetName(i);
                        if (name.Contains(","))
                            name = "\"" + name + "\"";

                        fs.Write(name + ",");
                    }
                    fs.WriteLine();

                    // Loop through the rows and output the data
                    while (dr.Read())
                    {
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            string value = dr[i].ToString();
                            if 

Open in new window

0
Hi, How to generate random string with below pattern in C#

MAX LENGTH - 15
NUMERIC- 1
LOWER CASE - 1
UPPER CASE - 1
NON-APLHA NUMERIC - 1
0
I'm working with the localization file. I get the following result when the value are displayed in my view page :  A approuv&#233; instead of A Approuvé. The issue is with the é.  I have included a screen shoot.  Any clue  why will this happen.
 
And I have the following value for my french translation: lan.fr-CA.resx:
<data name="Approved" xml:space="preserve">
<value>A approuvé</value>

Open in new window



My chtml file is :
{ dataField: "FormattedApprovedDate", calculateSortValue: "ApprovedDate", dataType: "date", caption: '@(Language.Translate(Language.Keys.Approved, ViewBag))'},

Open in new window

file1.PNG
0
i have a filter option in a table

Capture.JPG
so the filter works

filter.JPG
but when i click the edit icon on the right then it hits the master page and does a postback and reloads the dropdownlist vales again that resets it back to selected index = 0, how can i avoid this postback to retain the filter values?

so this is how i initally populate the dropdown list on page_load

 if (amiadmin == "YES" || amiadmin == "NO")
                    {
                        if (!IsPostBack)
                        {
                            headervaluess.Items.Clear();
                            for (int i = 0; i < GridView1s.Columns.Count; i++)
                            {
                                if (GridView1s.Columns[i].HeaderText != "MultipleApproval" && GridView1s.Columns[i].HeaderText != "" && GridView1s.Columns[i].HeaderText != "Date" && GridView1s.Columns[i].HeaderText != "TimeStamp" && GridView1s.Columns[i].HeaderText != "Explanation_Details")
                                {
                                    if (GridView1s.Columns[i].HeaderText == "Item Code")
                                    {
                                        headervaluess.Items.Add(GridView1s.Columns[i].HeaderText.Replace("Item Code", "Item_Code"));
                                    }
                                    else if (GridView1s.Columns[i].HeaderText == "Item Description")
                                    {
             

Open in new window

0
Hello EE,

I have in vb.net a dictionary of (Date, String) that looks like this :

"01/01/1980" ; "a,b,r,e,t,b,g,x,y,z"
"02/01/1980" ; "k,w,q,z,c,u,i,o,p"
"03/01/1980" ; "n,w,q,y,h,v,r"
.....
"04/28/2019" ; "b,c,r,y,z"


actually, the "string" part has always 20 letters. i did not write them all, but you understand.
My problem is, If I tell my software to look for all combination of 5 letters or let's say 6 letters... and to tell me :

for "a,b,c,d,e,f" when is the last time it was in ?
then for "a,b,c,d,e,g" when is the last time it was in ?
then for .....
then for "u,v,w,y,z,x" when is the last time it was in ?

by doing 2 FOR LOOP is long.

My main question is, is there any Functions, or special classes, or LINQ methods that are more efficient in terms of speed?

my code today is doing this :

        For x As Integer = 0 To combinaisonList.Count - 1
            Dim arrString As String() = combinaisonList(x).Split(New String() {","}, StringSplitOptions.RemoveEmptyEntries)

            For Each kvp As KeyValuePair(Of Date, String) In MyItems.Reverse
                If arrString.All(Function(v) kvp.Value.Contains(v)) Then
                    finalLoop.Add(combinaisonList(x), Math.Abs(DateDiff(DateInterval.Day, Now, kvp.Key)))
                    Exit For
                End If
            Next
        Next

Open in new window



so combinaisonList is the (List Of String) of all combinaison that I deceided lets say (6 letters)
and "MyItems" is the dictionary(of date, string) that I was talking about

My code works, but its not fast enough.
1
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
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
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

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