Jump to content

Search the Community

Showing results for tags 'csharp'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

There are no results to display.

There are no results to display.


Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


LinkedIn Profile URL


About Me


Cloud Platforms


Cloud Experience


Development Experience


Current Role


Skills


Certifications


Favourite Tools


Interests

Found 7 results

  1. C# is an incredible powerful free and open-source programming language that powers a wide array of applications, including complex video game engines. However, whether you are a building a massively complex application or a simple console application, you might come across instances where you need to transmit the data. One of the most powerful data interchange formats is JSON. It offers a lightweight and human-readable format while supporting the complex data layout. In this tutorial, we will learn how to use the provided C# tools and features to read and parse the data from a JSON file in a C# application. Sample JSON File Let us start by setting up our JSON file that we are going to use for demonstration purposes. In our case, the JSON file is as follows: { "database": { "name": "admin", "type": "SQL", "server": "localhost:5904", "creds": { "username": "root", "password": "mysql" } } } In this case, we have a basic JSON file with nested values which allows us to demonstrate how to read an arrayed JSON file. Installing the Newtonsoft.JSON Package In order to quickly and efficiently parse and work with JSON data in C#, we will make use of a “.NET” external library. In this case, we use the Newtonsoft.JSON package to read and work with JSON data. Before using it, we need to ensure that we have it installed. We can run the following command in the NuGet Package Console as follows: Install-Package Newtonsoft.Json This should download and allow you to access the features from the Newtonsoft JSON package. Read and Deserialize the JSON File Once we have everything ready, we can proceed and read the JSON file. We can add the source code as follows: using System; using System.IO; class Program { static void Main() { string jsonFilePath = "config.json"; string jsonString; if (File.Exists(jsonFilePath)) { jsonString = File.ReadAllText(jsonFilePath); Console.WriteLine(jsonString); } else { Console.WriteLine("File not found!"); } } } In the given example code, we start by defining the path to the JSON file. Next, we define a new variable to store the raw JSON string that we read. Finally, we use the File.ReadAllText to read the JSON file. The next step is to deserialize the JSON string. Deserializing allows us to format JSON into a valid C# object. We can do this by creating a class that represents the structure of the JSON data from the file. An example code is as follows: using System; using System.IO; using Newtonsoft.Json; public class Creds { public string Username { get; set; } public string Password { get; set; } } public class Database { public string Name { get; set; } public string Type { get; set; } public string Server { get; set; } public Creds Creds { get; set; } } public class RootObject { public Database Database { get; set; } } class Program { static void Main() { string jsonFilePath = "config.json"; string jsonString; if (File.Exists(jsonFilePath)) { jsonString = File.ReadAllText(jsonFilePath); RootObject dbInfo = JsonConvert.DeserializeObject(jsonString); Console.WriteLine($"Database Name: {dbInfo.Database.Name}"); Console.WriteLine($"Type: {dbInfo.Database.Type}"); Console.WriteLine($"Server: {dbInfo.Database.Server}"); Console.WriteLine($"Username: {dbInfo.Database.Creds.Username}"); Console.WriteLine($"Password: {dbInfo.Database.Creds.Password}"); } else { Console.WriteLine("File not found!"); } } } In the given example, we define three main classes. The first is the “Credentials” class, the second is the “Database” class, and lastly, we have the “RootObject” classes. Each class maps the structure of the JSON data and the corresponding types. Finally, we use the JsonConvert.DeserializedObject method to convert the resulting JSON string from the file into a C# object. Read the JSON Arrays As you can guess, a JSON data in the real world is not as simplistic as shown in the previous example. One of the most complex features that you will encounter in JSON is the arrays or nested JSON objects. Let us see how we can handle such a layout in C#. In our case, we are dealing with a JSON file as follows: [ { "name": "admin", "type": "SQL", "server": "localhost:5094", "creds": { "username": "root", "password": "mysql" } }, { "name": "users", "type": "MongoDB", "server": "localhost:5095", "creds": { "username": "root", "password": "postgres" } } ] Once we define the previous code, we can proceed and deserialize the JSON file and read the file. An example code is as follows: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; public class Creds { public string Username { get; set; } public string Password { get; set; } } public class Database { public string Name { get; set; } public string Type { get; set; } public string Server { get; set; } public Creds Creds { get; set; } } class Program { static void Main() { string jsonFilePath = "config.json"; string jsonString; if (File.Exists(jsonFilePath)) { jsonString = File.ReadAllText(jsonFilePath); List databases = JsonConvert.DeserializeObject<List>(jsonString); foreach (var db in databases) { Console.WriteLine($"Database Name: {db.Name}"); Console.WriteLine($"Type: {db.Type}"); Console.WriteLine($"Server: {db.Server}"); Console.WriteLine($"Username: {db.Creds.Username}"); Console.WriteLine($"Password: {db.Creds.Password}"); Console.WriteLine(); } } else { Console.WriteLine("File not found!"); } } } You might notice that the previous program does not provide much difference than a regular JSON parsing. The main different thing is that in the JsonConvert.DeserializeObject method, we convert the JSON string into a List of Database object where each object contains information about each array from the JSON list. The resulting output is as follows: Database Name: admin Type: SQL Server: localhost:5094 Username: root Password: mysql Database Name: users Type: MongoDB Server: localhost:5095 Username: root Password: postgres Conclusion In this tutorial, we covered all the features of reading and working with JSON files in a C# application using the Newtonsoft.JSON application. View the full article
  2. As folders offer a systematic and organized approach to handling resources and documents inside an application, they play a significant role in the C# development. Directories aid in the logical organization of files and resources. You can quickly find and manage the files by putting them in a directory with other similar items. In C#, the application’s current working directory may be retrieved using the GetCurrentDirectory() function. The working directory refers to the location in the file system where the application is currently running. Since it acts as the beginning point for all associated file and folder activities, this directory is essential to comprehend. We are going to learn about the various code samples to talk about this in this guide. Example 1: Let’s move towards the first example of this guide to demonstrate the use of the GetCurrentDirectory() function in C#. The “using” directives allow the program to access the classes and methods from the “System” and “System.IO” namespaces. The “System” namespace provides fundamental types and basic system functionality, while “System.IO” provides classes for use with documents and directories. The next line defines a new class named “Dummy” via the “class” keyword. The name “Dummy” is arbitrary and can be changed to any valid identifier. The main() function starts with the static keyword which indicates that it is a class-level method, and it’s not necessary to invoke a class instance for it to work. The directory function call is about to happen. The GetCurrentDirectory() method can be used to get the application’s present working directory. The GetCurrentDirectory() function is a static function from the “Directory” class which is part of the “System.IO” namespace. It returns a string that represents the current directory and assigns it to the “cd” variable. The Console.WriteLine() method is used to display a line of text to the standard output (console). In this case, it prints the “My Current Directory:” message that is concatenated with the value of the “cd” variable which holds the current directory path. using System; using System.IO; class Dummy { static void Main() { string cd = Directory.GetCurrentDirectory(); Console.WriteLine("My Current Directory: " + cd); } } When you run this C# program, the “Main” method is executed, and the current directory is displayed on the console. In case you are using any online C# compiler, it displays the compiler path, i.e. /home/compiler. It might vary depending on how you execute the application (e.g., from Visual Studio, command prompt, or a different IDE). Example 2: Other than the “Directory” class, the environment of C# can also be used to get the current working directory. Let’s explain the given C# example code step by step. The code begins with the “using System;” statement which includes the “System” namespace in the program. The code defines a new class named “Test”. A string-type variable with the “dir” name is declared and is given a value inside the “Main” function. To obtain the application’s present active directory, utilize the Environment.CurrentDirectory attribute. The “Environment” class provides information about the environment in which the application is running including the information about the file system and system environment variables. The “Console.WriteLine” method is used to display the current directory on the console of the IDE that you have been using. The “+” operator is used to concatenate the “Current Directory:” string with the value that is stored in the “dir” variable. using System; class Test { static void Main() { string dir = Environment.CurrentDirectory; Console.WriteLine("Current Directory: " + dir); } } The “Main” method is invoked by default when the application is run. It starts by retrieving the current directory using the Environment.CurrentDirectory. Then, it displays the current directory by printing the “Current Directory:” message followed by the directory path to the console using the Environment.CurrentDirectory property. Example 3: Getting the application’s current directory is simple with the AppDomain.CurrentDomain.BaseDirectory attribute. We add another C# code example to demonstrate the use of AppDomain.CurrentDomain.BaseDirectory. After adding the “System” namespace, the code defines a class called “Test”. The “Main” method starts its execution by adding a line to retrieve the current working directory of the application. The “AppDomain” class represents an application domain and the “CurrentDomain” is a static property that returns the current application domain. The “BaseDirectory” property, in turn, provides the base directory (also known as the application’s root directory) of the current application domain. The next line declares a variable named “dir” of type string to store the current directory. The next consecutive line outputs the current directory to the console using the Console.WriteLine method. The “+” operator is used to concatenate the “Current Directory:” string with the value of the “dir” variable. using System; class Test { static void Main() { string dir = AppDomain.CurrentDomain.BaseDirectory; Console.WriteLine("Current Directory: " + dir); } } When you run this C# program, it displays the current directory of the application on the console. Example 4: It’s time for our final illustration from this guide. The provided a C# code is a simple console application that demonstrates to get the current directory using the “Path.GetDirectoryName()” and “Assembly.GetExecutingAssembly().Location” methods. In this code, three namespaces are imported: “System”, “System.IO”, and “System.Reflection”. These namespaces contain classes and methods that are required for various operations in the code. A “Main” method and a class called “Test” are defined in the code. To obtain the current working directory, the “Assembly.GetExecutingAssembly()” method returns an “Assembly” object that represents the currently executing assembly (i.e., the running executable). The “Location” property of the “Assembly” object gives the full path to the location of the running executable (including the filename). Now, the “Location” property might contain the full path to the executable including the filename. To extract only the directory part, the “Path.GetDirectoryName()” is used. The directory path that holds the file is returned by this function after accepting a file address as input. Finally, the code prints the obtained current directory to the console using “Console.WriteLine()”. The “+” operator is used to concatenate the “Current Directory:” string with the value of the “cd” variable (which holds the current directory path). using System; using System.IO; using System.Reflection; class Test { static void Main() { string cd = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Console.WriteLine("Current Directory: " + cd); } } When you run this C# program, it displays the current directory of the running executable on the console as per the output that is shown in the image: Conclusion The aforementioned instances obtain the application’s current file system using various C# methods and attributes. Keep in mind that the current path may change depending on the running environment and how the program is launched. View the full article
  3. The two basic components of computing that make it possible for individuals to interact using the program’s code are user input and output. In C#, console input can be used to take user input and console output can be used to display output. This article covers the fundamentals of both terms in C#. What is User Input in C#? In C#, user input can be obtained by using the console input. The Console.ReadLine() function is used for handling user input. This approach reads a string via the prompt window and delivers it back as a string. Syntax The Console.ReadLine() has the following syntax: string var_name= Console.ReadLine(); In this case, string refers to the data type that represents the input from the user using var_name which will contain the user’s input value using Console.ReadLine() method. Example Here’s an illustration of a simple program that takes a message (input) from the user and saves it in the text variable and shows it on the console: using System; public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Please Enter a message: "); string text= Console.ReadLine(); Console.WriteLine("The message is:" + text); } } The Console.WriteLine() method has been employed in the above example; it will show the message “Please Enter a message: ” on the terminal. The Console.ReadLine() function is then implemented to accept user input and save it in a string variable called “text”. Lastly, the Console.WriteLine() function is called to show the message “The message is:” followed by the user’s input (text). Note: The Console.ReadLine() function only accepts a single line of text, unless the user presses the Enter key. If the user types more than one word, the complete line is saved in a string variable. What is User Output in C#? In C#, user output refers to data or information that is presented or output to the user on the program’s execution. The result can take many different forms, including text, numbers, symbols, and even graphical representations. In C#, Console.WriteLine() is utilized for user output that is shown on screens and is frequently used to show the user the outcome of a calculation, the current state of a program, or other vital information. This method delivers a string to the console, accompanied by a line terminator. Syntax Below is the simple syntax that displays the user’s message on the terminal when writing it on the C# compiler: Console.WriteLine("Hello"); Example The following C# program shows the sum of two variables such as num1 and num2 in the output: using System; public class HelloWorld { public static void Main(string[] args) { int num1 = 30; int num2 = 20; int sum = num1 + num2; Console.WriteLine("The sum of num1 and num2 is " + sum); } } The Console.WriteLine() is used in the example above to show the expression “The sum of num1 and num2 is” with the sum of num1 and num2, which is equal to 50. The string is built with the concatenation operator (+). Conclusion This article covers the concept of user input alongside user output in C#. The Console.ReadLine() method accepts data provided by the user’s keyboard and the Console.WriteLine() to present the output to the user. These methods are basic to C# programming and are widely used in interactive programming applications. View the full article
  4. The LINQ Except() method in C#, it returns all the elements in the first dataset that are not present in the second data set. The data set can be an Array, List, ArrayList, SortedList, and etc. Syntax: input_source1.Except(input_source2); Where input_source1 is the first data source and input_source2 is the second data source. Example 1: Here, we will create two Arrays that have string elements and apply the Except() method to return only elements from the first Array that are not present in the second Array. using System; using System.Linq; using System.Collections; using System.Collections.Generic; class Linuxhint { static void Main() { //create array of strings with 5 strings string[] first_strings = {"Linuxhint","java","python","backbone.js","ember.js"}; //create array of strings with 3 strings string[] second_strings = {"Linuxhint","java","html"}; Console.WriteLine("--------First Array--------"); foreach (var values1 in first_strings) { Console.WriteLine(values1); } Console.WriteLine("--------Second Array--------"); foreach (var values1 in second_strings) { Console.WriteLine(values1); } //apply Except() var final=first_strings.Except(second_strings); Console.WriteLine("--------Final Result--------"); foreach (var values in final) { Console.WriteLine(values); } } } Output: Explanation: 1. So first, we created two String Arrays named first_strings,second_strings. 2. After that, we are displaying the actual values present in the two arrays using a foreach loop. 3. Use the Except() method and display the values using the foreach loop. Example 2: Here, we will create two Arrays that have integer elements and apply the Except() method to return only values from the first Array that are not present in the second Array. using System; using System.Linq; using System.Collections; using System.Collections.Generic; class Linuxhint { static void Main() { //create array of integers int[] first_integers = {20,34,56,23,67,100}; //create array of integers int[] second_integers = {20,23,34,56,67}; Console.WriteLine("--------First Array--------"); foreach (var values1 in first_integers) { Console.WriteLine(values1); } Console.WriteLine("--------Second Array--------"); foreach (var values1 in second_integers) { Console.WriteLine(values1); } //apply Except() var final=first_integers.Except(second_integers); Console.WriteLine("--------Final Result--------"); foreach (var values in final) { Console.WriteLine(values); } } } Output: Explanation: 1. So first, we created two Integer Arrays named first_integers and second_integers. 2. After that, we are displaying the actual values present in the two arrays using a foreach loop. 3. Use the Except() method and display the values using the foreach loop. Conclusion The LINQ Except() method in C# returns all the elements in the first dataset that are not present in the second data set. Here, we used Array as a data source. Make sure you have to include using System, using System.Linq, using System.Collections, and using System.Collections.Generic. View the full article
  5. I recently worked on a project where I was required to write an Azure Function that would watch for newly stored files in Azure Blob Storage, copy the new files over to separate Azure Storage Account, and then delete the original file. Sure, you can use azcopy from the command-line to copy blobs between Azure […] The article Azure Functions: Copy Blob Between Azure Storage Accounts in C# appeared first on Build5Nines. View the full article
  6. A powerful way to write and build Azure Functions is to use C# Script. This allows you to easily write function directly within the Azure Portal, or even using source control as simple .csx script files. You don’t need to pre-compile the function before deploying it to Azure and can easily edit and release changes. […] The article Deploy C# Script Function App using Azure DevOps YAML Pipeline appeared first on Build5Nines. View the full article
  7. A virtual function in C# may be overridden in subclasses. A virtual function in C# has both a parent and child class implementation. Whenever the core functionality of a method is almost the same, however, the subclass requires additional capability, and it is utilized. The virtual phrase is used to define a virtual function in the superclass, which is then overridden by the override phrase in the subclass. Whenever a function is specified as a virtual function in a superclass, the subclass can choose whether or not to override it. The overriding methodology allows a function to have many forms. As a result, it is a good illustration of polymorphism. Let’s get started with using some of the C# examples to elaborate the working of the “virtual” keyword to create and use the virtual functions in the code. We have to create a C# file in which we can add the code for virtual functions with the “touch” query as below. Example # 01 Let’s get started with the most basic example of using the virtual method in C#. We will be utilizing the System library within our code in the first line by using the “using” keyword as displayed. After this, we created a public base class named “Parent” using the keyword “class”. This base class contains a single function named “Show” of void return type and public access modifier, i.e., virtual function. This virtual function contains a simple WriteLine() function statement of the Console class to print out the simple text sentence on execution at our screen, i.e., “Virtual method in Parent Class”. Another public class named “Child” was created after that. As shown, this class has been derived from the “Parent” class. The method “Show” has been implemented within it that has been overridden from the base class “Parent” using the keyword “override” followed by the “void” return type and started with the “public” access modifier. As this virtual function has been overridden from the base class, it must contain some extra implementation. Thus, we have been using the WriteLine() statement of the Console class here to display a new text string at the shell stating “Overriding Virtual Method in Child Class”. Both the parent and child class functions are of the same name but a little different implementation. All this implementation will work after using the main() method in the code. So, we have created a new independent class named “New” with the keyword “class”. This class contains a static type Main() method with a void return type. The execution started from creating a Parent class object “o1” with the keyword “new” followed by the class name. We have used this new object o1 to call the virtual function “Show” from the Parent class. After this, we have created another object o2 for the Child class using the keyword “new,” starting with the base class name and ending with the Child class name. This shows the actual inheritance has been taking place in the C# code. The child class object “o2” has been used to call the overridden “Show” virtual function of the child class. The function call must not be mixed up while executing the main() method. Also, we should get the show() function of the Parent class executed first and then the show() function of the child class function. The class New has ended here, and our code is completed now. After saving this code within the text editor, we returned to the terminal as our code needs to be compiled with the “mcs” C# compiler. After the successful compilation, we have tried the execution of its “exe” file just created in the home folder with the “mono” runtime of C#. It executed the code and displayed the string of the virtual method from the parent class first and then the string text of the overridden show() method of the child class. Example # 02 Let’s make our code a little advanced and different from the above example. We have been starting it with the System library usage in the first line of code. After that, we utilized a global class names Test containing three more classes and a main() function. The first class, “Rectangle,” is a parent class of the other two classes. We have declared 3 double type public variables “h”, “w”, and “r” in it with 10, 4, and 3, respectively. A double type constant variable “p” has been declared with a built-in “Pi” value of mathematics. A virtual method “Area()” of double return type has been defined here that has been returning the multiplication result of “h” and “w” to the main() function of the Test class, i.e., the area of a rectangle is, height multiply by width. The class “Square” has been derived from the “Rectangle” class. This class is overriding the virtual function “Area” from its base class and returning the multiplication result of “h” and “h,” i.e., the area of a square is one side multiplied by the second side or height into height. Then, we have a derived class “Circle” overriding the virtual function “Area” from the base class Rectangle. This function returns the multiplication result of “p” and “r*r,” i.e., the area of a circle is “pi” multiplied by the square of a radius. Three classes have been defined and implemented in the code fully. Now, it’s the turn of the Main() function of C# to start its execution and gradually run the classes. Within the Main() method of Test class, we have created an object “o1” of parent class Rectangle at the first line using the name of a class with the “new” keyword. Using the Rectangle class, we have created objects o2 and o3 for derived classes Square and Circle, respectively. Three WriteLine() statements from the Console class have been used here to display the area of Rectangle, Square, and Circle, respectively. For calculating the area for three shapes, we have used the respective objects of each shape class. These objects have been calling their respective virtual functions defined in the Rectangle class and overridden within the derived classes, i.e., Square and Circle. It’s time to compile this newly created C# code in the shell with the “mcs” command instruction. After that, use the mono runtime instruction to execute the “exe” file that has been generated as a result of compilation. On execution of this “exe” file for the code, we have got the area of rectangle, square, and circle displayed on our screen as we have used the virtual function in one class and overridden it in the derived classes. Conclusion We have described how a simple C# virtual function can be used within the C# code and overridden within its subclasses. We have demonstrated its working within this article with the help of some examples. The first example illustrated the usage of virtual function within the single inheritance program, while the second example demonstrates that with the help of multiple inheritances. This is how we have shown how a simple method can be used to perform multiple calculations with the single definition of a function in C#. View the full article
  • Forum Statistics

    63.6k
    Total Topics
    61.7k
    Total Posts
×
×
  • Create New...