Sunday, 14 June 2020

C# - Protecting against SQL Injection


Protecting against SQL Injection
Good Ways To Prevent SQL Injection

ORM
Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection. Your risk is reduced your risk simply by using an ORM like Linq2Entities, Linq2SQL, NHibrenate.

Paramaterized Queries
By using the SqlCommand and its child collection of parameters all the pain of checking for SQL injection is taken away from you and will be handled by these classes.

Example 1
private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored
    // in an xml column.
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

}

Example 2
For example, a secure way of running a SQL query in JDBC using a parameterized statement would be:

// Define which user we want to find.
String email = "user@email.com";
// Connect to the database.
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
// Construct the SQL statement we want to run, specifying the parameter.
String sql = "SELECT * FROM users WHERE email = ?";
// Run the query, passing the 'email' parameter value...
ResultSet results = stmt.executeQuery(sql, email);

while (results.next()) {
  // ...do something with the data returned.
}

Contrast this to explicit construction of the SQL string, which is very, very dangerous:

// The user we want to find.
String email = "user@email.com";
// Connect to the database.
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
// Bad, bad news! Don't construct the query with string concatenation.
String sql = "SELECT * FROM users WHERE email = '" + email + "'";
// I have a bad feeling about this...
ResultSet results = stmt.executeQuery(sql);
while (results.next()) {
  // ...oh look, we got

Example 3
Stored Procedure

CREATE PROCEDURE SP_GetLogin @username varchar(100), @password varchar(100) AS
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT * FROM users' +
                            ' FROM Product Where username = ''' +
                                             @username + ''' AND password = '''+@password+''''

EXECUTE sp_executesql @sql





Wednesday, 10 June 2020

C# - Delegates and Lambdas


Example 1
using System;
using System.Linq;

public class Program
{
    public delegate string Reverse(string s);

    static string ReverseString(string s)
    {
        return new string(s.Reverse().ToArray());
    }

    static void Main(string[] args)
    {
        Reverse rev = ReverseString;

        Console.WriteLine(rev("a string"));
    }
}

Example 2
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> list = new List<int>();

        for (int i = 1; i <= 100; i++)
        {
            list.Add(i);
        }

        List<int> result = list.FindAll(
          delegate (int no)
          {
              return (no % 2 == 0);
          }
        );

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
}

Example 3
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> list = new List<int>();

        for (int i = 1; i <= 100; i++)
        {
            list.Add(i);
        }

        List<int> result = list.FindAll(i => i % 2 == 0);

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
}


C# - Parse Date and Time Strings in .NET



DateTime oDate00 = Convert.ToDateTime("5/29/2020 8:02:41 AM",
CultureInfo.InvariantCulture);
DateTime oDate000 = Convert.ToDateTime("09/05/2020 8:02:41 AM",
CultureInfo.InvariantCulture);
DateTime oDate0000 = Convert.ToDateTime("9/5/2020 8:02:41 AM",
CultureInfo.InvariantCulture);
DateTime oDate00000 = Convert.ToDateTime("5/9/2020 8:02:41 AM",
CultureInfo.InvariantCulture);


DateTime oDate000000 = DateTime.ParseExact("28/05/2020 12:53:55 PM",
"dd/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
DateTime oDate0000000 = DateTime.ParseExact("25/12/2017 4:00 PM",
"dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);


Example

string dateInput = "Jan 1, 2009";
var parsedDate = DateTime.Parse(dateInput);
Console.WriteLine(parsedDate);
// Displays the following output on a system whose culture is en-US:
//       1/1/2009 00:00:00

var cultureInfo = new CultureInfo("de-DE");
string dateString = "12 Juni 2008";
var dateTime = DateTime.Parse(dateString, cultureInfo);
Console.WriteLine(dateTime);
// The example displays the following output:
//       6/12/2008 00:00:00

var cultureInfo = new CultureInfo("de-DE");
string dateString = "12 Juni 2008";
var dateTime = DateTime.Parse(dateString, cultureInfo,
                                DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(dateTime);
// The example displays the following output if the current culture is en-US:
//      6/12/2008 00:00:00

ParseExact

var cultureInfo = new CultureInfo("en-US");
string[] dateStrings = { " Friday, April 10, 2009", "Friday, April 10, 2009" };
foreach (string dateString in dateStrings)
{
    try
    {
        var dateTime = DateTime.ParseExact(dateString, "D", cultureInfo);
        Console.WriteLine(dateTime);
    }
    catch (FormatException)
    {
        Console.WriteLine("Unable to parse '{0}'", dateString);
    }
}
// The example displays the following output:
//       Unable to parse ' Friday, April 10, 2009'
//       4/10/2009 00:00:00

Tuesday, 2 June 2020

C# LINQ - OrderBy vs OrderByDescending


var dates = new DateTime[] {
        new DateTime(2015, 2, 15),
        new DateTime(2015, 3, 25),
        new DateTime(2015, 1, 5)
    };

var ResultOrderBy = dates.OrderBy(d => d);

var ResultOrderByDescending = dates.OrderByDescending(d => d);
foreach (DateTime dt in ResultOrderBy)
    Console.WriteLine(dt);

//Output
//1/5/2015 12:00:00 AM
//2/15/2015 12:00:00 AM
//3/25/2015 12:00:00 AM

foreach (DateTime dt in ResultOrderByDescending)
    Console.WriteLine(dt);

//Output
//3/25/2015 12:00:00 AM
//2/15/2015 12:00:00 AM
//1/5/2015 12:00:00 AM



//DateTime
//OrderByDesc
//New - Old
//First - Last