Google+ All posts by admin

Peter Bromberg's .NET Blog All Things Programming

How to Block Redirect Hackers in web.config

30. November 2021 17:37 by admin in

 

<system.webServer><security><requestFiltering>
<denyUrlSequences> <add sequence="ggkit.com" /> </denyUrlSequences>
</requestFiltering></security>
</system.webServer> </configuration>

HTTP Error 500.31 - ANCM Failed to Find Native Dependencies in IIS

28. July 2021 12:39 by admin in .NET CORE, API

There isn't very good documentation on this issue but usually it means you do not have the proper .NET Core SDK installed. In my case it was the latest for Visual Studio 2019.

Download it from here  https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-3.1.411-windows-x64-installer

 

Also, often you may find that the CORE hosting bundlle is the issue, even though it may be installed. Simply run the installer and choose to "Repair"

 

Keep It Simple Stupid Easy Database Exception Logger

12. June 2021 14:11 by admin in EXCEPTIONS, LOGGING

There are a number of very nice logging frameworks like Serilog, Log4net, ELMAH, NLog, and others. Almost without exception, they require fancy configuration setups because they were designed to log stuff in several different ways.  For beginning developers and even for some of us seasoned pros, set up and usage can be daunting. All I want is to be able to write a message, stack trace, and date of occurrence to my database Logs table and that's it. So I came up with KISSEDEL: Keep It Simple Stupid Easy Database Exception Logger. You can plug this into any app that uses a database and be going in five minutes!

First let's create a table in SQL Server:

 USE [DBName]
GO

    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE[dbo].[Logs]
    (
   [Id][int] IDENTITY(1,1) NOT NULL,
   [Date] [datetime]     NOT NULL,
  [Message] [varchar] (4000) NOT NULL,
   [Exception] [varchar] (2000) NOT NULL,
CONSTRAINT[PK_Log] PRIMARY KEY CLUSTERED
   [Id] ASC)
WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON[PRIMARY]
) ON[PRIMARY]
GO

Next configure your connection string in app.Config or web.config:

<connectionStrings>
<add name ="con" connectionString="Data Source=.;Initial Catalog=YOURDATBASE;Trusted_Connection=true"/>
</connectionStrings>

The only other thing we need is a class to handle logging:

using System;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

public static class Logger

{

    public static void Log(Exception ex)

    {

        string constr = ConfigurationManager.ConnectionStrings["con"].ToString();

        SqlConnection con;

        con = new SqlConnection(constr);

        con.Open();

        SqlCommand com = new SqlCommand("Log", con);

        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@Date", DateTime.Now);

        com.Parameters.AddWithValue("@Message", ex.Message.ToString());

        com.Parameters.AddWithValue("@Exception", ex.StackTrace.ToString());

        com.ExecuteNonQuery();

        con.Close();

    }

}

Finally, we want a stored proc to make the inserts:

USE [YOURDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Log]
@Date DateTime,
@Message varchar(500),
@Exception varchar(8000)
AS
insert into logs(Date, Message, Exception)
VALUES (@date,@message, @exception)

 

That's all there is to it. If you want to log something "Informational", just create a new Exception object and put the information in its Message property.

usage:

 try
                {
                  // your work here

                }

                catch (Exception ex)

                {

                    Logger.Log(ex);

                } 

 Have fun!

How to Send Mail With Gmail And C#

3. June 2021 14:27 by admin in

Many developers have difficulty sending mail through Gmail because of security issues. Google provides what is called an "app-specific password" that can be used if you have 2-factor authentication turned on (you should!).

Here is the URL to set this up: https://myaccount.google.com/apppasswords  And here is some sample C# code to use it. You simply replace your regular gmai password with the app-specific password that you set up in your Google settings.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace SendMail
{
class Program
{
static string smtpAddress = "smtp.gmail.com";
static int portNumber = 587;
static bool enableSSL = true;

static string emailFromAddress = "youremail@gmail.com"; //Sender Email Address
static string password = "APPSPECIFICPWD"; //APP SPECIFIC PWD Generated at Google Account
static string emailToAddress = "you@gmail.com"; //Receiver Email Address
static string subject = "Hello";
static string body = "Hello, This is Email sending test using gmail.";

static void Main(string[] args)
{
SendEmail();

}

public static void SendEmail()
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFromAddress);
mail.To.Add(emailToAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// mail.Attachments.Add(new Attachment("C:\\Temp\\TestFile.txt"));//--Uncomment this to send any attachment

using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}

}
}