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 Experts

Looking for advice, views, experience for a project our company are working on.

What it is our project consists of is 2 C# executables both being multi-threaded, one being setup as a TCP listener and the other being setup as TCP Client, these 2 do not talk directly to one another, but what they will do is communicate to 20 machines and both the exe’s will be hosted in the application server.

Exe 1 (TCP Listener) - communicates with 10 machine clients this way we are controlling the business process.
Exe 2 (TCP Client) - communicates with the other 10 machines which are listeners(code setup by vendor), this way they are doing the controlling of the business process.

Exe 1 we have completed that's fine.

Exe 2, how this works is we load up from a SQL DB table the 10 IP's of the each of the 10 machines and put each IP into its own thread and we connect directly to them, and the 2 way comms begin sending/receiving based on signal protocols information.

Our company have always setup to be controlling the complete process were we are the listener only and every machine is a client, but due to inexperience people in the project have some doubt using it the other way around.

My question is has anyone set up in this fashion before were 1 TCP client executable connects straight into multiple listeners and how they found it?

I appreciate all advice, views and experiences.

Thanks!
0
Do you know how to test my web app using HTTPS using local IIS?

Is there a test tool with IIS which supports this? And without needing to buy a certificate?

Thanks
0
Trying to understand the exposure caused by window.location

used in an .ajax call thusly:

                            window.location = buildTokenUrl('~/editor/', {
                                id: data.contentbankresourceid,
                                assettype: assetType,
                                poolid: self.cachedData().pool,
                                returnUrl: window.location.toString(),
                                defaultStyleId: defaultStyleId,
                                testId: self.testId,
                                formId: $("#formid").val()
                            });

Open in new window


I need some ideas how to block XSS attacks on this kind of code.

One was is for me to possibly expose a new server method that can be used to validate a url, before redirecting.

How might this look? What kind of input params could there be coming from the javascript? How might that server method return a valid URL for that particular case?

Might it choose from a white listed set of URL's?

Thanks
1
What grid control can you recommend so that the cells can be editable just like excel? Also upon leaving a selected row, it saves the changes.
0
Hey all I have the following image box' sizes on my WPF form:
 Box |Width |Height
 ----|------|------
 1   |357   |272
 ----|------|------
 2   |357   |272
 ----|------|------
 3   |365   |460
 ----|------|------
 4   |365   |265
 ----|------|------
 5   |715   |455
 ----|------|------
 6   |360   |465
 ----|------|------
 7   |360   |465
 ----|------|------
 8   |360   |465
 ----|------|------
 9   |540   |290
 ----|------|------
 10  |540   |290

Open in new window

So visually it would look something like this:
 --------------------------
 |       |        |       |
 |   1   |    2   |       |
 |----------------|   3   |
 |                |       |
 |                |-------|
 |       5        |       |
 |                |   4   |
 |------------------------|
 |        |       |       |
 |   6    |   7   |   8   |
 |        |       |       |
 |------------------------|
 |            |           |
 |     9      |     10    |
 --------------------------

Open in new window

So what my goal is is to get the current image I am wanting to place into a box and get its width and height and from that determine the best box to place it in so that it will show the image:

- Without black borders on either the left/right or top/bottom (or both).
- Not chop off the important areas of the image (mostly the middle section moving out).

I have decided to use Magick.NET in order to ease the pain of doing something like this from scratch. So when I determine what box I will be placing the image into then I can use the Magick.NET to crop it using:

Resize with something like this:
imgStream.Crop(width, height, Gravity.Center);

Open in new window

or
MagickGeometry size = new MagickGeometry(width, height);
size.IgnoreAspectRatio = maintainAspectRatio;
// Adjust geometry offset to center of image (same as `-gravity Center`)
size.Y = imgStream.Height / 2 - height / 2;
size.X = imgStream.Width / 2 - width / 2;
imgStream.Crop(size);

Open in new window

So to sum up the above - I am in need of finding the best box to place the image into before I go and use Magick.NET on it.
0
I have the codes below inside of the Controllers in MVC project. This is API project that I tried to learn.
My question is: how can I create end point for Get(int id)? Should I create a VIEW?

My goal is to create end point, and I will have another website project to call the end point so the website can consume the API service.


  public class LeadController : Controller
    {
        [HttpGet]
        public IEnumerable<CrmModels.Lead> Get(int id)
        {
            CrmModels.Lead l = new CrmModels.Lead();
            List<CrmModels.Lead> li = new List<CrmModels.Lead>();
            if (id == 1)
            {
                l.firstName = "John";
                li.Add(l);
            }
            else
            {
                l.firstName = string.Empty;
                li.Add(l);
            }
            return li;
        }
        //Get api/lead details
        [HttpGet]
        public IEnumerable<string> Get()
        {
            //call crm controllers 
            return new string[] { "", "" };
        }
        //create
        [HttpPost]
        public void Post(CrmModels.Lead l)
        {
            //call crm controllers 
        }
        //update
        [HttpPut]
        public void Put(int id)
        {
            //call crm controllers 
        }
        //delete
        [HttpDelete]
        public void Delete(CrmModels.Lead l)
        {
            //call crm controllers 
        }
    }

Open in new window

0
I want to parse this string in C# and get the values for User, BusinessNameId, ToBusinessNameId, PatientId and ToProviderId

User: hw@gmail.com BusinessNameId: 1973 ToBusinessNameId: 1973 PatientId: 1506 ToProviderId: 1608


I think I need to use IndexOf

string test = "User: xyz@gmail.com BusinessNameId: 1973 ToBusinessNameId: 1973 PatientId: 1506 ToProviderId: 1608"

s.IndexOf('User:") but then how do I get xyz@gmail.com that comes right after it?

Or

s.IndexOf("BusinessNameId") but how do I get 1973 ?

There will always be a space between the strings (I can use * or any other character if it's better. It doesn't have to be a space)
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Configuration;
using System.Text.RegularExpressions;

namespace enumeration
{

    class Area
    {
        public enum Shape
        {
            Circle,
            Square
        }
        public void AreaShape(int x, Shape shape)
        {
            double area;
            switch (shape)
            {
                case Shape.Circle:
                    area = Math.PI * x * x;
                    Console.WriteLine("Circle Area= " + area);
                    break;
                case Shape.Square:
                    area = x * x;
                    Console.WriteLine("Square Area= " + area);
                    break;
                default:
                    Console.WriteLine("Invalid Input"); break;
            }
        }
    }
    class EnumTest:
    {
        public static void Main(string[] args)
        {
            Area area= new Area();
            area.AreaShape(15,Area.Shape.Circle);
            area.AreaShape(15,Area.Shape.Square);
            area.AreaShape(15,(Area.Shape)1);
            area.AreaShape(15,(Area.Shape)10);
        }
    }

}
0
How can I remove an xml node from an XmlDocument object in c#?  For example, I want to remove <LastName> tag.....


Input:
<DataSet>
	<Person>
		<FirstName>Bob</FirstName>
		<LastName>Smith</LastName>
	</Person>
	<Person>
		<FirstName>Gina</FirstName>
		<LastName>Davis</LastName>
	</Person>
</DataSet>

Open in new window


Desired Result:

<DataSet>
	<Person>
		<FirstName>Bob</FirstName>
	</Person>
	<Person>
		<FirstName>Gina</FirstName>
	</Person>
</DataSet>

Open in new window



I'm using .NET Framework 3.5
0
We need to remove an area from our project using MVC.  We also use Code First.   What steps needs to be taken to make sure we don't break anything?
0
Using the Uri object to return a list of domain found in the  string

I need to find if Uri (or related .NET object) can return 2 of 3 domains when it parses this string:

https://sso.mydomain.org/openam/?goto=http://evildomain.com/?hacked=mydomain.org:80/ntshome/Home/Index?ClientId=MP";

I would be okay if it returned:

sso.mydomain.org
evildomain.com
mydomain.org:

OR

evildomain.com
mydomain.org

How can I do this with Uri or some other .NET object?

Thanks
0
Hello.
1. I has created a datagridview with some textbox cells dinamicly
2. I'm trying to add autocomplete text to cell (it doen't work when datagridview created dinamicly)

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            (e.Control as DataGridViewTextBoxEditingControl).TextChanged -= cell_TextChanged;
            (e.Control as DataGridViewTextBoxEditingControl).TextChanged += cell_TextChanged;
        }

        void cell_TextChanged(object sender, EventArgs e)
        {
            AutoCompleteStringCollection acCollection = new AutoCompleteStringCollection();
            acCollection.Add("1122");
            acCollection.Add("1133");
            acCollection.Add("1144");
            acCollection.Add("1222");
            acCollection.Add("1333");
            acCollection.Add("1444");

            TextBox tb = sender as TextBox;
            tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
            tb.AutoCompleteCustomSource = acCollection;
            tb.AutoCompleteMode = AutoCompleteMode.Suggest;   
        }

Open in new window


Why autocomplete list does not showing?
I'm sorry for my bad english....
0
I have a file dialog method in my code to which I pass a value using a parameter called ImportPath. I want to assign this value in the app.config file which you can see below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <setting name="ImportPath" serializeAs="String">
    <value>C:\GPShares\Import</value>
  </setting>
</configuration>

Here is the code:

            openFileDialog1.Title = "Select Arrests csv file to scrub";
            openFileDialog1.InitialDirectory = ImportPath;
            openFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            openFileDialog1.FileName = "";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

The problem is the value for ImportPath is always blank. What is the proper technique to retrieve the value for ImportPath?
0
Dear Experts,
 I'm using ODBC in C# to select data (SQL statement) from a database then to insert these data into CSV file.

How do I improve my code when the SQL result is huge data?

        public Void executeQuery(string query)
        {

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }

            OdbcCommand dc = new OdbcCommand(query, conn);
            OdbcDataReader reader = dc.ExecuteReader();

            schematab = reader.GetSchemaTable();

            DataTable dt = new DataTable();
            dt.Load(reader);

            reader.Close();

            Insert dt to CSV file

        }

Open in new window



Thanks
0
What happens if a thread acquires a lock (SemaphoreSlim), and then that thread gets terminated before it releases the lock?

e.g.
private SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
public async Task DoStuff()
{
    using (semaphoreSlim.WaitAsync(1000))
    {
    	...//Do something
    }
}

Open in new window

What happens if the thread gets terminated while it's in "Do Something"?
0
Hello,
I am trying to display a pdf image to a winform. I am using axacropdf to try to accomplish this. It is working perfectly the first time I pass a .pdf file to it to display. After the first time it doesn't display the image but shows a comment and fill/sign section. How can I reset this control each time so it only displays the image I want to see.

            //Display the card pdf image
            string sAGIN = Convert.ToString(dtMOcard.Rows[0][37]);
            string sAGIN3 = sAGIN.Substring(0, 3);
            pdfCard.setShowToolbar(false);
            pdfCard.src = "";
            pdfCard.LoadFile(@"\\usoscs320\e_drive\Gracol PDF Done NEW\" + sAGIN3 + @"\" + sAGIN + @"\F" + sAGIN + @".pdf");
            //pdfCard.src = @"\\usoscs320\e_drive\Gracol PDF Done NEW\" + sAGIN3 + @"\" + sAGIN + @"\F" + sAGIN + @".pdf";

Open in new window


First Scan
Second Scan
0
I have two tabs in the form and a dropdownlist.
Even when I'm on Tab2 when I select a value, the page defaults back to tab 1 after postback. What can I do to maintain default on Tab2 upon postback
0
Hi, I'm using Visual Studio 2017.  I created a C# Web API with MVC checked project.  It comes  with a basic structure already.  It has the HomeController and the ValuesController cdoe in the project explorer.  Build and ran the problem and it lands and shows the Home's Index view page no problem.  However, I get error when I accessed the ValuesController Get API.  Please see the attached image.  With this message and my break point, it does reach and execute the Get() API no problem by me adding /api/Values
But then the browser would ask if I want to save or open, if I select open then I got the error.  It's having problem opening and displaying the values.json file.  

The ValuesController.Get() api doesn't return a ActionResult so I assume it doesn't need a View created and the context menu doesn't show adding view is an option to it.  Is this correct?

  I looked up the error online and it seems it'a registry corruption issue.  I'm running Visual Studio 2017 Enterprise installer again in Repair mode.  I'm hoping that would fix it or I would have to mess with the registry values.

I'm also attaching the screen cap pop up text at the bottom of the screen when I call the Get or Get id api.

Thank you
json-error.jpg
Get-err.jpg
Get-id-err.jpg
0
Question about a RegEx:

 @"[&|?](" + "myDomain.com" + ")=(.*?[^&]+)?";

what do these require or prevent before the domain?

[&|?]

and what does this require or prevent after the domain?

(.*?[^&]+)?

Thanks.
0
Im new to C# and think this is a pretty basic question but looking for a better way. Is there no better way to check for null values from a datareader then write a if..then statement for each input field?

so building on a previous example:

   using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = sqlCon;
                    sqlCon.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            someList.Add(new someModel
                            {
                                Desc_a = sdr["DescA"].ToString(),
                                Desc_b = sdr["Descb"].ToString(),
                                id_a = Convert.ToInt32(sdr["Id"]),
                                State = sdr["state"].ToString()
                            });
                        }
                        sqlCon.Close();

Do I need to write something like
if (sdr.getString(0) != DBNull || sdr.getString(0) != NULL){
Desc_a = sdr["DescA"].ToString(),
} else {
Desc_a = " no value"
}

for each input such as
                            someList.Add(new someModel
                            {
                                if (sdr.getString(0) != DBNull || sdr.getString(0) != NULL){
                                     Desc_a = sdr["DescA"].ToString(),
                                } …
0
there is a checkbox based on selection i need to fetch data from back end. there is a creditunits field is there in sql table that having values 0 to 5.
so when i check checkbox creditunits value is greter than 0 to display, when not checked no filter.
0
The method below is what I use to encrypt passwords. The method GetEntropy() simply returns random text.

The issue I am having, is that if I call the Crypt method with a string that contains a "%", for example  Crypt("te%xt"), and I then decrypt the encoding, it returns "tet". For some reason the %x is being read as something else. I tried to escape the %, for example Crypt("te/%xt"), but that just returns "te/t".

 static string Crypt(string text)
        {
            byte[] entropy = Encoding.ASCII.GetBytes(GetEntropy());

            return Convert.ToBase64String(
                ProtectedData.Protect(
                    Encoding.Unicode.GetBytes(text), entropy, DataProtectionScope.CurrentUser));
        }

Open in new window


Any guidance is much appreciated.
0
How to install Resharper on Visual Studio 2017?

I have the license ID handy, but forgot how.

Thanks.
0
I am very new to C# and just learning, I assume this is a pretty basic question but i need a bit of help.

I have a SQL join that I am putting in an object and passing to a viewModel but I seem to be having trouble when I change from select * to naming all the headers and assigning it to the object.

  Select a.Desc,a.ID, b.Desc, b.state  from a
  join a ON b.Id = a.Id

 
   using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = sqlCon;
                    sqlCon.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            someList.Add(new someModel
                            {
                                Desc_a = sdr["a.Desc"].ToString(),
                                Desc_b = sdr["b.Desc"].ToString(),
                                id_a = Convert.ToInt32(sdr["a.Id"]),
                                State = sdr["b.state"].ToString()


                            });

                        }
                        sqlCon.Close();


I seem to be getting "System.IndexOutOfRangeException: a.Desc" error. I assume Im not assigning the value from the sql into the object correctly but im not seeing why?

Thank you for your help
0
Report Viewer works on ASP.NET Website but not Mac. Shows Blank pages.  Some posts indicate it has to do with overflow:auto defauting to hidden on Mac and visible on Windows.
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).