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

All I want to do is gather the top 10 largest files in each directory.

So, I want to gather all directories and sub-directories to page through in a later routine.

One simple way to do this would be with LINQ, well it should be simple.

The issue arises when you try to "point it" to the C: or D: or...drive.  You get the unauthorized exception even if you ran the application as the Admin.  (right click, run as administrator)

internal List<String> lstDirectoryListAll(string dir
                                                , string searchPattern
                                                , SearchOption searchOption)
        {
            var dirs = new List<string>();

            try
            {
                dirs = Directory.GetDirectories(dir, searchPattern, searchOption).ToList();
            }

            catch
            {

            }

            return dirs;
        }

Open in new window


Many folks have stated that you can just leave the catch blank in posts all over the internet.  We all know that you will not get what you are seeking in that scenario.

There are a ton of convoluted C++ files to import and do some insane work around.  Highly undesirable and will take an eternity to figure out what in the heck is going on (I'm not a C++ guy).

Isn't there a simple way to get every directory?  I would almost bet on it.

Thanks in advance.
0
Hi,
Any idea to convert this java code to C# format.

HttpClient httpClient = HttpClientBuilder.create()
					.setDefaultRequestConfig(RequestConfig.custom()
							.setCookieSpec(CookieSpecs.STANDARD).build())
					.build();

Open in new window


Kind regards,
Pooja
0
Have a C# method that will receive a List<string> of numbers, and i need to remove the leading zeros only.
public List<string> RemoveLeadingZeros(List<string> commish)
        {
            List<string> lineList = new List<string>();
            int count = 0;
            foreach(string line in commish)
            {
                commish.ToString().TrimStart('0');
                
                count++;
            }
            lineList.AddRange(commish);
            return lineList.ToList();
        }

Open in new window

Data set looks like this:
0000012.74
-000001.3
0
Hi,
New  to java. I am trying to convert java code to C#. I am going to start with this simple code. Can you please help me or provide me some tips to convert this small java class to C#. Advance thanks!

package token;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class MatchTokens
{
	private String response = null;;
	private String SSOUrl = null;;
	private static String grant_type = "password";
	private String SystemID = null;
	private String SystemPassword = null;
	private String ClientID = null;
	private String ClientSecret = null;
	private String AccessToken = null;
	private String RefreshToken = null;
	private static String access_token_key = "match-access";
	private static String refresh_token_key = "match-refresh ";
	
	public MatchTokens(String SSOUrl, String ClientID,
			String 

Open in new window

0
Hi

I'm trying to work out how to Entity Framework

I've created a movie database in MS SQL and on to creating a MovieModel using Entity Data Model Wizard,and EF Designer from database,
The results are pictured bellow

how do I join the tables?
For instance

movie.id = movielinkperson.movieId
 movielinkperson.personId = person.id

I thought I could drag a line between the two this doesn't  work

MovieModel.JPG
0
I have one form that calls a lookup form. On the parent form there is a field called txtVendor. Next to that field is an icon that calls frmLookupVendor. This is the code that calls that form.

        private void btnLookupVendor_Click(object sender, EventArgs e)
        {
            /* Prepare to open vendor lookup Form */
            if (LookupVendorForm == null)
            {
                LookupVendorForm = new frmLookupVendor();
            }
            else
            {
                if (LookupVendorForm.Created == false)
                {
                    LookupVendorForm = new frmLookupVendor();
                }
            }

            /* Always show and activate the winform */
            LookupVendorForm.Show();
            LookupVendorForm.StartPosition = FormStartPosition.CenterScreen;
            LookupVendorForm.Activate();
        }

Down in this form there is data grid view. I know I have the correct value but I cannot get it return the value. What am I missing?

        private void dgvVendors_DoubleClick(object sender, EventArgs e)
        {
            int currentRow;

            currentRow = dgvVendors.CurrentCell.RowIndex;
            dgvVendors.CurrentCell = dgvVendors[0, currentRow];
            pv = dgvVendors.CurrentCell.Value.ToString();

            DialogResult = DialogResult.OK;

            return;
        }
0
Hi

I'm trying to find all the directories that contain an *.avi file so I can move the directory
Doesn't matter if other files type exist in the same directory

In the code bellow I'm finding every directory even with no avi

           string[] Dirs = Directory.GetDirectories(Root, "*", SearchOption.TopDirectoryOnly);
            foreach (string Dir in Dirs)
            {
                string NewDir = "";
                string[] Files = Directory.GetFiles(Dir, "*.avi", SearchOption.TopDirectoryOnly);

                // If a no avi file in Dir Files should not be  null  ??

                if (Files != null ) //|| Files.Count() >= 1)
                {
                    NewDir = avi_files + Dir;
                    string OldDir = Root + "\\" + Dir;
                    if (!Directory.Exists(NewDir))
                    {

                        //   Directory.Move(OldDir, NewDir);
                        Console.WriteLine("OldDir: {0} NewDir: {1} ", OldDir, NewDir);
                    }
                }
 
           }

Open in new window


The first Dir dose not have an *.avi file but in the "Immediate window"
Files != null
true

Open in new window

That means Files has an avi file ??

as you can see in the code i've tried different methods
var files = Directory.EnumerateFiles(Root, "*.*", SearchOption.AllDirectories)
                    .Where(s => s.EndsWith("*.AVI") || s.EndsWith("*.avi"));

Open in new window

0
I have a line in my c# application where i pass a Date variable into my model and a defined static class variable (see below)

EmployeeDetails.staticbirthdate = model.birth_dt = Convert.ToDateTime(BirthDateValue.Text);

The Birthdate  on screen reads  28-07-2019 (see  screen below)

Screen Show showing the date field
When passing the date variable to both the model and static class variable which are both defined as date

the values now read 0001/01/01 and not the actual value on screen and i end up with an error

while still trying  to read the date field into those variables.

See Error scree below

Error screen while passing Screen date to 2 variables
The line being flagged above is part the definition below

{
            PersonnelModel model = new PersonnelModel();
            EmployeeDetails.staticstaffno = model.type_app = TypeAppValue.Text;
            EmployeeDetails.staticstaffno = model.staff_no = StaffNoValue.Text;
            EmployeeDetails.staticsurname = model.surname = SurnameValue.Text;
            EmployeeDetails.staticfirstname = model.firname = FirstNameValue.Text;
            EmployeeDetails.staticmidinit = model.midinit = MidInitValue.Text;
            EmployeeDetails.staticaddressline1 = model.home_add = AddressLine1Value.Text;
            EmployeeDetails.staticaddressline2 = model.home_add2 = AddressLine2Value.Text;
            EmployeeDetails.staticaddressline3 = model.home_twn = AddressLine3Value.Text;
            EmployeeDetails.staticphoneno = model.offic_phn = 

Open in new window

0
Can writing this

$server.bindData("GemSubscriptions", $scope, "gemSubscriptions")


instead of this

$server.bindData("GemSubscriptions", $scope, "gemSubscriptions", {
        callback: function (d) {
            console.log("Gem Reports:", d);
        }
    })


cause any issues?


Thanks.
0
I'm trying to check to see if a value entered into my app (part) exists in a list that is deserialized from a JSON file.  If the value entered for 'part' exists in the list column Olditem all is good, otherwise throw a warning.  Here are the classes that were derived from the JSON data:

 public class InvItem
    {
        [JsonProperty("Description")]
        public string Description { get; set; }

        [JsonProperty("Inventoryitem")]
        public string Inventoryitem { get; set; }

        [JsonProperty("Lbsperunit")]
        public double Lbsperunit { get; set; }

        [JsonProperty("Olditem")]
        public string Olditem { get; set; }

        [JsonProperty("Onhand")]
        public double Onhand { get; set; }

        [JsonProperty("Uom")]
        public string Uom { get; set; }
    }

    public class InvItemlist
    {
        [JsonProperty("GetInvListResult")]
        public List<InvItem> InventoryList { get; set; }
    }

Open in new window


Here is my code, but it always returns the entire list regardless of the input:
public void CheckIfPartExists(string part, string filename)
        {
            string filePath = Path.Combine(FileSystem.Current.LocalStorage.Path + filename);
            string jsonString = File.ReadAllText(filePath);
            var match = JsonConvert.DeserializeObject<InvItemlist>(jsonString);

            match.InventoryList.Where(i => i.Olditem == part).FirstOrDefault();
            
            if (match != null)
            {
                btnEnter.Focus();
            }

            else
            {
                DisplayAlert("ATTENTION!!!", "This part number does not exist in inventory.", "Ok");
                txtPartNbr.Text = "";
            }
            
        }

Open in new window


I'm pretty new at C#, any help will be greatly appreciated.
Jeff
0
we have been tasked with trying to salvage a document from an orphaned SharePoint content database, and have seen suggestions to this tool which seems promising:
https://archive.codeplex.com/?p=sharepointdatabaseexplorer

I have downloaded the zip file and extracted the content. As it is directly from codeplex there is no simple way to install/setup for the novice user. If you are familiar with downloading source code from such sites and making it into an executable program so we can actually run the tool, could you give a very basic beginners guide on how to do so (it will need to be complied/ran from a windows machine). There is a source code directory once you extract the zip file. I presume it is a c sharp application based on file extenions, although this is not my area of expertise, so even understanding the basics of what tools we would need to setup in the windows machine to compile/execute would help.
0
By referring to:

https://jwt.io/#debugger-io

Untitled.jpg
I wish to implement the RS256 algorithm and get the Encoded Token in .NET

I managed to generate the encoded text for Header and Payload, using the following codes:

var header = new Dictionary<string, object>()
            {
                { "alg", "RS256" },
                { "typ", "JWT" }
            };
            String strHeader = Base64UrlEncode(JsonConvert.SerializeObject(header));

            var claims = new Dictionary<string, object>()
            {
                { "sub", "1234567890"},
                {"name", "John Doe"},
                {"admin", true},
                {"iat", 1516239022}
            };
            String strClaims = Base64UrlEncode(JsonConvert.SerializeObject(claims));

            textBox1.Text = strHeader + "." + strClaims;

Open in new window


private String Base64UrlEncode(String input)
        {
            var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            // Special "url-safe" base64 encode.
            return Convert.ToBase64String(inputBytes)
              .Replace('+', '-')
              .Replace('/', '_')
              .Replace("=", "");
        }

Open in new window


But I got problem in generating the Signature part?

Appreciate the assistance here, thanks.
0
Hi,
How to prevent xml external entity (xxe)  through C#

StringReader a= new StringReader(b);
a= new XmlTextReader(a);
reader.XmlResolver = null
 <<<<<<Security tool is reporting here that possible of XXE mitigation>>>>>>>>>>>>>>>>
 
i applied
StringReader a= new StringReader(b);
a= new XmlTextReader(a);
a.XmlResolver = null;
a.DtdProcessing = DtdProcessing.Prohibit;
bool b = a.Read();

am not getting any value in a.
0
Hi

The object of my exercise is to learn Entity Framework most of the time I will have created a Database already

I'm using Visual Studio 2019 the tutorials I've found are based on 2017

I've given up trying to connect to an SQLite database as steps  outlined here suggest SQLite isn't compatible with VS 2019


So I  dumped the Database to an SQL file this has both table structure  and data but no database creation

Can someone tell me how to create a Microsoft Server Database and import this SQL file

I then would like to know how to create a DB connection class s  I can use it in different applications
0
Hi;

I have really  big trouble with AZURE CosmosDb during 1 week! İt makes me down. Everything is working in my local computer. But if I publish below code,
it returns me Below Error.


LOGS in Azure function in Azure:

2019-07-25T12:28:00.854 [Information] C# Timer trigger function executed at: 7/25/2019 12:28:00 PM
2019-07-25T12:28:00.888 [Error] Executed 'Function1' (Failed, Id=9e5758d7-7ffa-430a-85ee-178aeaa6758a)
Cannot deserialize a 'ObjectId' from BsonType 'Binary'.
Code:
    public static class Function1
    {
        [FunctionName("Function1")]
        [Obsolete]
        public static void Run([TimerTrigger("* * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var connectionString = @"mongodb://gggdfdfgfsdfdsfsd";
            //var connectionString = @"mongodb://localhost:27017/admin";
            MongoClient client = new MongoClient(connectionString);
            var database = client.GetDatabase("xxxxx-playground");
            //var database = client.GetDatabase("abc");
            var collection = database.GetCollection<Test>("test");

            var beforeDate = DateTime.UtcNow.AddDays(-7);
            var totalDeleted = 0;
            var ids = new List<ObjectId>();

            do
            {
                ids = collection.Find(k =>
                                      k.CreatedDate < beforeDate &&
                                  

Open in new window

0
I have a C# application that reads Excel spreadsheets.

using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

I have these two references in the code. This application needs to have Excel installed. My question is there a way to not have to install Excel? Is there some abbreviated install package that could be run that will install just enough to allow the code to run?
0
How to sort order by descending using Linq query in the DataTable?

DataTable Dt2 populates data .. and has the data.. I am trying to resort the data in the Dt2.

DataTable Dt2 = new DataTable();
            Dt2 = dt.AsEnumerable()
                .GroupBy(r => r.Field<string>("City"))
                .Select(g =>
                {
                    var row = dt.NewRow();
                    row["City"] = g.Key;
                    row["rating"] = g.Average(r => ParseInt32(r.Field<string>("rating")));
                    return row;
                }).CopyToDataTable();


            var results = from r in Dt2.AsEnumerable()                           
                            select new
                            {   
                                City = r.Field<string>("City"),
                                rating = r.Field<int>("rating")
                            };

Open in new window

0
Can removing multiple console.log from JavaScript, jQuery, AngularJS application cause any issues?

Thanks.
0
Error reading an Excel has become more apparent during testing. I was trying to determine why some files would be read just fine and others would fail. What I have discovered is that the errors are data driven. As an example, there are six item categories. The values will be something like this:
Item Group         - CLOTHING
Item Subgroup   - PANTS
Code                     - WARE
UofM                    - PAIR
Active                   - YES
UPC                      - 54329087

The problem I have is when I need to check for NULLS or blanks. Everything works fine as long as the cell has a value.

if (string.IsNullOrEmpty(xlRange.Cells[i, j].Value2))  - this works for the alphanumeric values

if (string.IsNullOrEmpty(xlRange.Cells[i, j].Value2.ToString())) - this works for the numeric value(UPC).

If I send a NULL down to string.IsNullOrEmpty(xlRange.Cells[i, j].Value2.ToString() and its a string value I get a message about can't pass null values to tostring().
If I send a NULL down to string.IsNullOrEmpty(xlRange.Cells[i, j].Value2) and its a numeric value I get a message about not being able to convert string.

How can I start with this xlRange.Cells[i, j].Value2 and somehow determine whether it is numeric or string so I can apply the proper test?
0
I am receiving the following error always when this method is executed through Window Service whether when the same code is executed through Web Portal it is working Fine.

Could not create ssl/tls secure channel. c#


using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;


 void wc1TwoSample2()
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                delegate(Object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.DefaultConnectionLimit = 9999;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
                string URL = "https:URL";
                string param = "/api/v1/accounts";
                string resp = URL + param;
                var http = 

Open in new window

0
I have working with an Rest api, which returns json data, but not sorted out the way I want. Api is not flexible enough, such that we can pass a sort parameter and it returns the result accordingly.

so, the data in such form

public class records {

....
      public Collection<Item> items ;

.....

}


in my c# code, I do something like this,


var results = CallApi();


var sortedResults = results.OrderBy(x => x.items.price);

return soretedResults.tolist();


I am concerned that this sorting and converting it back to the list , is expensive and as the results
grow larger, this might cause problem.

any thoughts in this?
0
Hi, I'm writing an dll in C#. as long I use functions without argument everything is going fine. Now I have to include function like this
 public void AmChan(int am) to my dll. When I compile code and include dll to the test project this function is invisible; I cannot call it.
But I can see and use functions without argument like this :     public void CleanBuffer(){}
What I'm doing wrong? I use Class Library (.NET Framework).
0
I'm trying to populate a list box and I keep getting the following error.

This is the error!

Here is my code:
     private static void DirectoryCopy(string sDir, string dDir, bool copySubDirs)
        {
            Cursor.Current = Cursors.WaitCursor;

            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sDir);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sDir);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();

            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(dDir))
            {
                Directory.CreateDirectory(dDir);
            }

            // Get the file info for each file in the in the directory
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string dst = Path.Combine(dDir, file.Name);
                string src = Path.Combine(sDir, file.Name);

                //Display which file is currently being worked on
                ChangeLabelText(file.Name);

                //use the SafeCopy() function to copy each file until it finishes before copying the next file.
                SafeCopy(src, dst, 10000);

                //add the name of the file that was just copied to the 

Open in new window

1
I am reading an Excel spreadsheet and came across a few dates where the value is "0/0/0000". I want to convert these to "1/1/1901". I have defined defDate as string "1/1"1901"
Every time my code encounters one of these it fails on date = double.Parse(sdate); with a message about invalid format. What must I change to get this to work? In the spreadsheet this column is defined as type date.

                                    if (xlRange.Cells[i, j].Value2.ToString() != "0/0/0000")
                                        sdate = xlRange.Cells[i, j].Value2.ToString();
                                    else
                                        sdate = defDate;

                                    date = double.Parse(sdate);    ---- THIS IS WHAT FAILS -----------

                                    var rdateTime = DateTime.FromOADate(date).ToString("yyyyMMdd");
                                    redistributionLastDate = rdateTime;
0
I have these  4 buttons across on all my c# windows application forms
(Save,Update,Delete and Exit)  see  buttons  below

Display of Buttons on ALL forms in my c
On 1 on the forms  I have done the following which works as desired.

1. on form_load  I  call a library  that accesses  the database to determine whether a button should be visible or not
see the form_load  call to the library below:

1. In my Form-Load Event

 FormPermissionsProcessor processor = new FormPermissionsProcessor();
 var result = processor.GetFormExecStatus();
 SetButtons();


2. In my Library the status each button is determined after reading this from a database

  public class FormPermissionsProcessor
    {
       
       
        public Tuple<string, string, string,string> GetFormExecStatus()
        {
            PermissionsModel model = new PermissionsModel();

            GlobalConfig.Connection.GetFormPermissions();       // This line goes into the database to fetch the variables below
            string libregstatus = LoginDetails.staticformexecute;
            string libreglevel =  LoginDetails.staticaddbutton;
            string liblicensetype = LoginDetails.staticupdatebutton;
            string libdel = LoginDetails.staticdeletebutton;

            return new Tuple<string, string, string,string>(libregstatus, libreglevel, liblicensetype,libdel);
        }
       
    }

Open in new window


3. Method in my form that processes the returned values

 private void SetButtons()
        {
            saveButton.Visible = false;
            updateButton.Visible = false;
            deleteButton.Visible = false;
            if (LoginDetails.staticaddbutton == "Y")
            {
                saveButton.Visible = true;
            }
            if (LoginDetails.staticupdatebutton == "Y")
            {
                updateButton.Visible = true;
            }
            if (LoginDetails.staticdeletebutton == "Y")
            {
                deleteButton.Visible = true;
            }
        }

Open in new window


Currently  this process works for 1 form but i don't want to be repeating
the method in 3 above on  every form

How can I achieve this particularly since the 4 buttons (Save,Update,Delete and Exit) are local to each form

Thanks

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