Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 29 November 2024

CSRF Attack

 A CSRF (Cross-Site Request Forgery) attack is a type of security vulnerability that tricks a user into performing actions on a website or web application without their knowledge or consent. This type of attack takes advantage of the trust a website has in the user's browser.

How CSRF Works:

  1. Victim logged in: The victim is authenticated and logged into a web application (e.g., a banking website).
  2. Malicious website: The attacker creates a malicious website or web page that includes a hidden request, such as a form submission, image, or a link, targeting the victim's authenticated session.
  3. User visits malicious site: The victim, still logged in to the original application, unknowingly visits the attacker’s malicious website.
  4. Request sent automatically: The malicious site sends a request (such as transferring money, changing account settings, etc.) to the target website on behalf of the victim, using the victim’s session.
  5. Action executed: The target website processes the action, assuming it is a legitimate request from the victim, and performs it (e.g., transferring money, changing the password).

Example Scenario:

  • A user is logged into their banking account and has an active session.
  • They unknowingly visit a malicious site, which sends a request to transfer money from the user's account to the attacker’s account.
  • Since the user is authenticated, the bank processes the request, and the money is transferred without the user’s knowledge.

CSRF Attack Mechanisms:

  • The attacker might exploit a GET or POST request, tricking the victim’s browser into sending it.
  • This attack can be hidden in various forms, such as in an image <img> tag, a form <form> submission, or a request triggered by JavaScript.

Protection Against CSRF:

To prevent CSRF attacks, websites use several techniques:

  1. CSRF Tokens: A unique token (often random) is generated by the server and included in forms or URLs. When a form is submitted, the server checks if the token matches the one sent with the request. If not, the request is rejected.
  2. SameSite Cookies: This cookie attribute restricts how cookies are sent with cross-site requests, preventing the browser from sending authentication cookies in unauthorized requests.
  3. Referer and Origin Header Validation: Websites can validate the Referer or Origin HTTP headers to ensure that the request originated from the same domain.
  4. Captcha: Using Captcha systems in sensitive actions (like fund transfers or password changes) can help prevent automated CSRF attacks, as the attacker cannot bypass the CAPTCHA.

Types of CSRF Attacks

  • GET-based CSRF: The attacker tricks the victim into making a GET request to a vulnerable web application, such as by embedding an image, script, or hyperlink in a malicious site.
    • Example: <img src="http://example.com/transfer?amount=1000&to=attacker_account">

  • POST-based CSRF: The attacker uses a POST request to send data to the target site, often through a hidden form submission. This is more dangerous since POST requests can modify data.
    • Example: Hidden HTML form submission with a predefined action and data:
      <form action="http://example.com/transfer" method="POST">
        <input type="hidden" name="amount" value="1000">
        <input type="hidden" name="to" value="attacker_account">
      </form>

Tools to Test CSRF Vulnerabilities

Several tools and frameworks can help developers test for CSRF vulnerabilities in their applications:

  1. OWASP ZAP (Zed Attack Proxy): A popular security testing tool for web applications that can be used to identify CSRF vulnerabilities.
  2. Burp Suite: A widely used security testing suite that can scan for and help mitigate CSRF vulnerabilities.
  3. CSRFTester: A specialized tool for testing CSRF vulnerabilities in web applications.

In essence, CSRF exploits the trust a website has in the user, while other attacks like XSS (Cross-Site Scripting) exploit the trust a user has in a website.

Continue Reading →

Thursday, 21 November 2024

Identify application performance

Below are steps and methods you can use to diagnose application performance problems:

1. Monitor Server Metrics

Before diving deep into the application, gather information about the server’s resource usage:

  • CPU Usage: Check if the server's CPU is being heavily utilized (over 85% usage for extended periods) which could indicate that your application or system processes are CPU-bound.
  • Memory Usage: Excessive memory usage can result in swapping to disk, slowing down performance. Monitor memory and swap usage to ensure there’s enough available RAM.
  • Disk I/O: Look for high disk usage or latency, which could be a sign of a disk bottleneck (e.g., slow reads/writes). Tools like iostat or vmstat can help.
  • Network Traffic: High network latency, packet loss, or network saturation could also degrade application performance, especially for web services or cloud-hosted applications.
  • System Load: The system load average should give you a quick overview of how many processes are being executed relative to the number of available CPUs.

Tools for monitoring:

  • Windows Task Manager or Resource Monitor for Windows

2. Examine Application Logs

  • Error Logs: Look for exceptions, timeouts, or resource constraints in the application’s error logs.
  • Application Logs: Review logs for slow query warnings, function call traces, or resource exhaustion issues.
  • System Logs: Check for OS-level resource issues or kernel-level errors that may affect your application.

3. Identify Slow Parts of Code

  • Benchmarking: Measure the performance of specific parts of your code to identify bottlenecks (e.g., long-running loops, inefficient algorithms).

4. Analyze External Dependencies

If your application depends on third-party services or APIs, external latency could be affecting performance:

  • API Call Latency: Measure response times from external services. If your app makes synchronous API calls, delays in these services can cause slowdowns.
  • Database Latency: Ensure database queries are optimized and that indexes are properly used. Even simple queries on large datasets can cause performance issues.
  • Service Health: Monitor if there are any issues with external systems (e.g., cloud services, third-party APIs, CDNs) that the application depends on.

5. Load Testing

  • Stress Testing: Simulate heavy loads on the application to identify how it behaves under stress. Tools like Apache JMeter, Gatling, or Locust can help simulate concurrent users and requests.
  • Benchmarking: Compare your application’s current performance against baseline metrics or historical data to assess if performance has deteriorated.

6. Database Optimization

  • Indexing: Ensure that your database tables are properly indexed, especially for frequently queried columns.
  • Query Optimization: Review slow or inefficient queries using database profiling tools. Look for things like unnecessary joins, missing indexes, or unoptimized queries.
  • Connection Pooling: Use connection pooling to avoid the overhead of opening and closing connections frequently.
By following these steps systematically, you can identify the root cause of application performance issues and take corrective actions to improve the situation.



Continue Reading →

Wednesday, 20 November 2024

Prevent SQL injection

To prevent SQL injection in a C# web application or web API, it's essential to follow best practices for interacting with databases. SQL injection occurs when malicious users insert or manipulate SQL queries to perform unauthorized actions on the database. Here are several strategies you can implement to prevent SQL injection:

  1. Use Parameterized Queries: The parameters are treated as data, not executable code. The database engine knows to treat them as literal values, not as part of the SQL query syntax, preventing SQL injection.
  2. Use ORM Frameworks : usually handle query generation safely and abstract away direct SQL execution, making it harder to introduce SQL injection vulnerabilities.
  3. Use Stored Procedures (With Caution) : Stored procedures can also help mitigate SQL injection risks, but they must be used correctly. Ensure the stored procedure itself is written safely with parameters, not by concatenating values directly into the query.
  4. Validate and Sanitize Input : Ensure that the data entered matches the expected type, expected length and If possible, define a list of allowed values and reject anything that doesn't match. 
  5. Use Web Application Firewall (WAF) : A WAF can detect and block malicious SQL injection attempts and other common web vulnerabilities before they reach your application.
    • Examples: AWS WAF, Azure WAF, Cloudflare WAF.
  6. Use Web API Authentication and Authorization : Ensure that your web API is properly authenticated (using tokens, OAuth, etc.) and authorized (ensuring the caller has appropriate access rights) to prevent unauthorized database access, which could amplify the risk of SQL injection.
  7. Log and Monitor for Suspicious Activity : Monitor your application for unusual query patterns that might indicate an attempted SQL injection attack. Set up logging and alerts for failed login attempts, unusual request patterns, or any attempts to bypass your validation.
  8. SQL Injection Testing and Security Tools : Regularly test your application for SQL injection vulnerabilities using:
    • OWASP ZAP or Burp Suite for security testing.
    • SQLMap for automated SQL injection testing.

The best way to prevent SQL injection in a C# web application is to always use parameterized queries or prepared statements, avoid direct SQL query construction with user input, and leverage ORM frameworks like Entity Framework. Combining input validation, principle of least privilege, and proper security testing can help further mitigate risks.

Continue Reading →

Saturday, 16 November 2024

Dynamically passing method : Action, Func delegates

 In C#, you can dynamically pass a method or a delegate to another method by using either delegates or Action/Func types. These approaches allow you to abstract the invocation of methods in a flexible and reusable way.

Let’s look at how to pass methods dynamically using Action (for methods that return void) or Func<T> (for methods that return a value). Both Action and Func are predefined generic delegates in .NET.

Using Action Delegate

  static void Main(string[] args)
  {
    ExecuteAction(printMessage); //Passing method via Action delegate

// Passing an anonymous method (lambda) via Action delegate
    ExecuteAction(() => Console.WriteLine("Hello from Lamda expression"));
  }

// Method that accepts an Action delegate
  static void ExecuteAction(Action action)
  {
      action();
  }
 
// A method that matches the Action delegate signature (void method)
  static void printMessage()
  {
      Console.WriteLine("Hello world");
  }
OUTPUT
  //Hello world
  //Hello from Lamda expression

Using Func<T>Delegate

  static void Main(string[] args)
  {
    int result = ExecuteFunc(getSum, 4, 5);
    int result2 = ExecuteFunc((a, b) => a + b, 5, 6);
    Console.WriteLine(result);
    Console.WriteLine("Result from Lamda: "+result2);
  }

  static int ExecuteFunc(Func<int, int, int> func, int n1, int n2)
  {
      return func(n1, n2);
  }

  static int getSum(int a, int b)
  {
      return a + b;
  }

OUTPUT
  //9
  //Result from Lamda: 11

Key Points:

  • Action<T>: Used for methods that return void.
  • Func<T, TResult>: Used for methods that return a value.
  • You can pass both named methods and lambda expressions (anonymous methods) as delegates.
  • Delegates are type-safe, meaning that they require the method signature to match.

This flexibility lets you dynamically pass any method or lambda expression to another method in C#.


Continue Reading →

Coding Test: Extension method

Create an extension method to filter out odd and even numbers from a collection like a list or array. Below is an example of how you can write such extension methods.

1. Extension Method to Filter Odd Numbers

This method filters odd numbers from a collection of integers.

using System;
using System.Collections.Generic;

public static class NumberExtensions
{
    // Extension method to get odd numbers from an IEnumerable<int>
    public static IEnumerable<int> GetOddNumbers(this IEnumerable<int> numbers)
    {
        foreach (var number in numbers)
        {
            if (number % 2 != 0)
            {
                yield return number;
            }
        }
    }

    // Extension method to get even numbers from an IEnumerable<int>
    public static IEnumerable<int> GetEvenNumbers(this IEnumerable<int> numbers)
    {
        foreach (var number in numbers)
        {
            if (number % 2 == 0)
            {
                yield return number;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Filter odd numbers using extension method
        var oddNumbers = numbers.GetOddNumbers();
        Console.WriteLine("Odd Numbers:");
        foreach (var number in oddNumbers)
        {
            Console.WriteLine(number);
        }

        // Filter even numbers using extension method
        var evenNumbers = numbers.GetEvenNumbers();
        Console.WriteLine("Even Numbers:");
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

Output: 

Odd Numbers: 1 3 5 7 9 Even Numbers: 2 4 6 8 10

Summary:

  • The GetOddNumbers and GetEvenNumbers methods are simple extension methods that work on any collection implementing IEnumerable<int>.
  • yield return is used in the methods to lazily return the filtered numbers without creating a new list upfront, making it memory efficient.
Continue Reading →

Flags Attribute in C#

 In C#, the Flags Attribute is used to indicate that an enumeration (enum) can be treated as a bit field,  where individual bits represent different values that can be combined using bitwise operations. This allows you to represent multiple options or states in a single variable using a combination of flags.

Purpose of the Flags Attribute:

  • The Flags attribute provides a way to describe an enum where its values can be combined using bitwise operations like AND (&), OR (|), and XOR (^).

How to Use the Flags Attribute:

To use the Flags attribute in C#, you define an enum and then apply the [Flags] attribute to it. You also make sure that the enum values are powers of two (i.e., 1, 2, 4, 8, 16, etc.), so that each value corresponds to a single bit position.

  using System;

[Flags]
public enum Permissions
{
    None = 0,       // No permissions
    Read = 1,       // 0001 in binary
    Write = 2,      // 0010 in binary
    Execute = 4,    // 0100 in binary
    Delete = 8,     // 1000 in binary
    All = Read | Write | Execute | Delete  // Combine all flags
}

class Program
{
    static void Main()
    {
// Set My Permission
      Permissions myPerm = Permissions.Read | Permissions.Write;
  Console.WriteLine($"HasReadPermission:{myPerm.HasFlag(Permissions.Read)}");
  Console.WriteLine($"HasWritePermission:{myPerm.HasFlag(Permissions.Write)}");
Console.WriteLine($"HasExecutePermission:{myPerm.HasFlag(Permissions.Execute)}");

        // Combine multiple flags
        Console.WriteLine($"Permissions: {myPerm}");
    }
}

Explanation:

  • The [Flags] attribute indicates that the Permissions enum represents a set of flags.
  • Each flag (e.g., Read, Write, Execute, etc.) corresponds to a power of two.
  • You can combine multiple flags using the bitwise OR operator (|), as shown in myPermissions = Permissions.Read | Permissions.Write.
  • The HasFlag method checks if a specific flag is set in a variable.

Output:

Has Read Permission: True Has Write Permission: True Has Execute Permission: False Permissions: Read, Write

Key Points:

  1. Bitwise Operations: You can combine and check flags using bitwise operations like |, &, and ^.
    • | (OR) combines flags.
    • & (AND) checks if a flag is set.
    • ^ (XOR) can toggle a flag.
  2. HasFlag Method: The HasFlag method is a convenient way to check if a specific flag is set.
  3. Enum Values as Powers of Two: For bitwise operations to work properly, each flag should be a power of two.

Important Considerations:

  • 0 as Default: The value 0 is typically used for the "None" flag, representing no flags set.
  • Combining Flags: If you want to represent a combination of multiple flags, you can do so using the | operator, e.g., Permissions.Read | Permissions.Write.
  • Readability: Using the Flags attribute doesn't change the underlying behavior of enums, but it does enhance their clarity when printed or logged. If you print an enum without the Flags attribute, it will display the integer value instead of a comma-separated list of flags.

Example of Output with ToString():

If you print the myPermissions variable directly, you will get the readable flag names:

  Console.WriteLine(myPermissions); // Output: Read, Write

This approach is useful for scenarios like permissions, configurations, state management, and other cases where multiple independent options need to be combined.

2: Program 2

  public class Program
  {
      // Define an Enum with FlagsAttribute.
      [Flags]
      enum MultiHue
      {
          None = 0,
          Black = 1,
          Red = 2,
          Green = 4,
          Blue = 8
      };
 
      static void Main(string[] args)
      {
 
          var multihue1 = (int)MultiHue.Black | (int)MultiHue.Blue | (int)MultiHue.Red;
          var multihue2 = MultiHue.Black | MultiHue.Blue | MultiHue.Red;
          var multihue3 = (int)MultiHue.None;
 
          Console.WriteLine(multihue1);     // Output:11
          Console.WriteLine(multihue2);     // Output:Black, Red, Blue
          Console.WriteLine(multihue3);    // Output:0
          Console.WriteLine((MultiHue)11); // Output: Black, Red, Blue
 
          Console.Read();
      }
  }

3: Program 3

  public class Program
  {
      // Define an Enum with FlagsAttribute.
      [Flags]
      enum MultiHue
      {
          None = 0,
          Black = 1,
          Red = 2,
          Green = 4,
          Blue = 8
      };
 
      static void Main(string[] args)
      {
          // Display all combinations of values, and invalid values.
          Console.WriteLine(
               "\nAll possible combinations of values with FlagsAttribute:");
 
          for (int val = 0; val <= 16; val++)
          {
              Console.WriteLine("{0}-{1}", val, (MultiHue)val);
          }
 
          Console.Read();
      }
  }

Output

All possible combinations of values with FlagsAttribute:

0-None
1-Black
2-Red
3-Black, Red
4-Green
5-Black, Green
6-Red, Green
7-Black, Red, Green
8-Blue
9-Black, Blue
10-Red, Blue
11-Black, Red, Blue
12-Green, Blue
13-Black, Green, Blue
14-Red, Green, Blue
15-Black, Red, Green, Blue
16-16

  • & (AND) checks if a flag is set. See below code
//You can combine multiple flags using bitwise OR (|) and
//check if a flag is set using bitwise AND (&).
var multiHue = MultiHue.Black | MultiHue.Red;
 Console.WriteLine("multiHue: "+ multiHue); // Output: Black, Red

 bool hasBlack = (multiHue & MultiHue.Black) == MultiHue.Black;
 bool hasRed = (multiHue & MultiHue.Red) == MultiHue.Red;
 bool hasBlue = (multiHue & MultiHue.Blue) == MultiHue.Blue;

  Console.WriteLine("hasBlack: "+ hasBlack);  // Output: True
  Console.WriteLine("hasRed: " + hasRed);  // Output: True
  Console.WriteLine("hasBlue: " + hasBlue);  // Output: False


Continue Reading →

Thursday, 7 November 2024

Implement Retry Logic in C#

 Often, we have transient problems in our application, such as a network failure, system rebooting, or anything else that throws an exception. In this article, we are going to learn how to implement retry logic in C# to help us handle these problems.

Let’s start.

Simulate a Failure in Our Application

Before we create the retry logic in C#, we need a method that can create a transient problem. That said, let’s create a very basic logic to simulate the failure:

public static void FirstSimulationMethod()
{
    const int forbiddenNumber = 3;
    Console.Write("Write a number: ");
    var number = int.Parse(Console.ReadLine() ?? "0");
    if (number == forbiddenNumber)
        throw new ArgumentException($"The generated number must be different from
{forbiddenNumber}");
    Console.Write("Not Equal");
}

First, this method asks for a number. After parsing this number into an integer, it compares this number to a forbidden number we previously set.

If the input number is equal to the forbidden number, this method is going to throw an exception with a message, otherwise, it prints the “Not Equal” message in the console.

This exception simulates a transient problem that may occur by a brief network failure or something like this.

Creating the Second Method

Let’s inspect the second method:

public static int SecondSimulationMethod()
{
    const int forbiddenNumber = 3;
    Console.Write("Write a number: ");
    var number = int.Parse(Console.ReadLine() ?? "0");
    if (number == forbiddenNumber)
        throw new ArgumentException($"The generated number must be different from
{forbiddenNumber}");
    Console.Write("Not Equal");
    return number;
}

Note that this method is very similar to the FirstSimulationMethod, however, in the end, it returns the input value. This method is important to show how to implement retry logic using Action or Func delegates.

Implementing the Retry Logic in C#

Once we have the methods to simulate the transient problems, we can focus on writing the retry logic in C#. Let’s create an Executor static class with an Execute method:

public static class Executor
{
    public static void Execute(Action action, int numberOfRetries)
    {
        var tries = 0;
        while (tries <= numberOfRetries)
        {
            try
            {
                action();
                return;
            }
            catch
            {
                tries++;
            }
        }
        throw new Exception($"Error after {tries} tries");
    }
}

The Execute method is responsible to execute the logic several times if there’s any problem. It receives an Action as a first parameter and the number of times we want to retry (numberOfRetries) as a second parameter.

Then, we need to loop and execute the method until the tries variable value is lower or equal to the numberOfRetries variable value. If the Action executes successfully, the retry logic finishes its execution. However, in case of exception, it increments the tries variable and retries to execute the Action.

When the tries value is greater or equal than the numberOfRetries, it finishes the execution and throws an exception with some message.

Retry Logic in C# With the Func Delegate

Now, let’s create a new overload of the Execute method:

public static TResult? Execute<TResult>(Func<TResult> func, int numberOfRetries)
{
    var tries = 0;
   
    while (tries <= numberOfRetries)
    {
        try
        {
            return func();
        }
        catch
        {
            tries++;
        }
    }
    throw new Exception($"Error after {tries} tries");
}

Note that the main difference is that this time this is a generic method with a return type.

Once it has a return type, instead of receiving an Action as a parameter, this method receives a Func, and then, we return the result of this Func.

With both previous methods, we can use this retry logic in C# for both, Action and Func delegates.

Using the Executor Class

Once we have defined the Executor class and its methods, it is time to execute the FirstSimulationMethod and the SecondSimulationMethod methods.

Let’s check it:

Executor.Execute(FirstSimulationMethod, 3);

We call the Execute method under the Executor class passing the method we want to execute, and the maximum number of retries as parameters.

Now, let’s use the overload method:

var result = Executor.Execute(SecondSimulationMethod, 3);

This time, we pass a Func as the first parameter. That said, we need to declare a result variable to receive the return from this Func.

It is good to mention that when we send 3 as the number of retries, this method is going to execute 4 times. The first execution and three retries. 

We can Implement Retry logic with Polly https://www.pollydocs.org

Continue Reading →

Tuesday, 31 October 2023

C# String data type : Exercises

 C# String data type : Exercises, Practice, Solution

Write a C# Sharp program to find the length of a string without using a library function.

  using System;  
  public class Exercise2
  {  
      public static void Main()
  {
      string str; /* Declares a string of size 100 */
      int l= 0;
   
        Console.Write("Input the string : ");
        str = Console.ReadLine();
 
           foreach(char chr in str)
          {
              l += 1;
          }
     Console.Write("Length of the string is : {0}\n\n", l);
    }
  }

Write a program in C# Sharp to count the total number of words in a string.

  using System;  
  public class Exercise5
  {  
      public static void Main()
      {
          string str;
          int i, wrd,l;
   
            Console.Write("Input the string : ");
            str = Console.ReadLine();
   
             l = 0;
             wrd = 1;
 
      /* loop till end of string */
      while (l <= str.Length - 1)
      {
          /* check whether the current character is white space or new line or tab character*/
          if(str[l]==' ' || str[l]=='\n' || str[l]=='\t')
          {
              wrd++;
          }
 
          l++;
      }
 
     Console.Write("Total number of words in the string is : {0}\n", wrd);
    }
  }

Write a program in C# Sharp to compare two strings without using a string library functions.

  using System;  
  public class Exercise6
  {  
      public static void Main()
  {
      string str1, str2;
      int flg=0;
      int i = 0, l1, l2, yn = 0;
     
        Console.Write("Input the 1st string : ");
        str1 = Console.ReadLine();    
       
        Console.Write("Input the 2nd string : ");
        str2 = Console.ReadLine();    
 
      l1=str1.Length;
      l2=str2.Length;
      /*compare checking when they are equal in length*/    
      if(l1==l2)
    {
      for(i=0;i<l1;i++)
        {
            if(str1[i] != str2[i])
            {
              yn= 1;
              i= l1;       
            }
        }
    }
  /*initialize the flag where they are equal, smaller and greater in length*/  
      if(l1 == l2)
          flg=0;
      else if(l1 > l2)
          flg=1;
      else if(l1 < l2)
          flg=-1;
  /*display the message where the strings are same or smaller or greater*/  
      if(flg == 0)
      {
         if(yn==0)
         Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
         else
              Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
      }
      else if(flg == -1)
      {
         Console.Write("\nThe length of the first string is smaller than second.\n\n");
      }
      else
      {
         Console.Write("\nThe length of the first string is greater than second.\n\n");
      }
    }
  }

Write a program in C# Sharp to count the number of alphabets, digits and special characters in a string.

using System;  
  public class Exercise7  
  {  
   public static void Main()
  {
      string str;
      int alp, digit, splch, i,l;
      alp = digit = splch = i = 0;
 
        Console.Write("Input the string : ");
        str = Console.ReadLine();
        l=str.Length;
 
       /* Checks each character of string*/
 
      while(i<l)
      {
          if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              alp++;
          }
          else if(str[i]>='0' && str[i]<='9')
          {
              digit++;
          }
          else
          {
              splch++;
          }
 
          i++;
      }
 
     Console.Write("Number of Alphabets in the string is : {0}\n", alp);
     Console.Write("Number of Digits in the string is : {0}\n", digit);
     Console.Write("Number of Special characters in the string is : {0}\n\n", splch);
    }
  }

Write a program in C# Sharp to copy one string to another string.

using System;  
public class Exercise8  
{  
    public static void Main()
{
    string str1;
    int  i,l;

      Console.Write("\n\nCopy one string into another string :\n");
      Console.Write("-----------------------------------------\n");  
      Console.Write("Input the string : ");
      str1 = Console.ReadLine();
     
      l=str1.Length;
      string[] str2=new string[l];

    /* Copies string1 to string2 character by character */
    i=0;
    while(i<l)
    {
        string tmp=str1[i].ToString();
        str2[i] = tmp;
        i++;
    }
   Console.Write("\nThe First string is : {0}\n", str1);
   Console.Write("The Second string is : {0}\n", string.Join("",str2));
   Console.Write("Number of characters copied : {0}\n\n", i);
  }
}

Write a C# Sharp program to count the number of vowels or consonants in a string.

  public class Exercise9  
  {  
  public static void Main()
  {
      string str;
      int i, len, vowel, cons;
     
      Console.Write("Input the string : ");
      str = Console.ReadLine();  
 
      vowel = 0;
      cons = 0;
      len = str.Length;
 
      for(i=0; i<len; i++)
      {
 
          if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
          {
              vowel++;
          }
          else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              cons++;
          }
      }
     Console.Write("\nThe total number of vowel in the string is : {0}\n", vowel);
     Console.Write("The total number of consonant in the string is : {0}\n\n", cons);
    }
  }

Write a C# Sharp program to find the maximum number of characters in a string.  Click here

Find the character and Number of Occurrence in given word where number of Occurrence is more then 1

            string val = "Interview";

            Dictionary<string, int> dict = new Dictionary<string, int>();
            for (int i = 0; i < val.Length; i++)
            {
                string c = val[i].ToString().ToLower();
                if (dict.ContainsKey(c))
                {
                    dict[c] = dict[c] + 1;
                }
                else
                {
                    dict[c] = 1;
                }
            }

            foreach (var d in dict.Where(x=> x.Value > 1))
            {
                Console.WriteLine("Key: "+d.Key+" Value: "+d.Value);
            }

Output:

Key: i Value: 2

Key: e Value: 2


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives