Google+ All posts by admin

Peter Bromberg's .NET Blog All Things Programming

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);
}
}
}

}
}

Track Yahoo Finance News with Blazor

28. March 2021 16:13 by admin in BLAZOR

RapidAPI publishes a lot of different APIs including many from Yahoo Finance. Limited accounts are usually free.   You can get the full source code for this app at github here:

  Github Repo

 For this i used the stock Blazor Server app template from Visual Studio 2019, and stripped out everything related to the stock "Weather Service" that it creates. Then I added a Finance News model class, and a FinanceNews Service class. Both appear below.

 

 

 

 

How to block tracking cookies in Google Chrome

27. April 2018 15:08 by admin in CHROME, SECURITY

 

Web sites plant cookies for all kinds of reasons, some good, and many not so good. If you visit the New York Times, for example, there are nearly 80 cookies planted, many from services that do nothing but collect your browsing habits and track you all over the web.

1. Click the favicon at the left of the address bar. If it's https, click the green "Secure" icon. You'll see a popup with a list of options. 
2. Near the bottom will be "cookies" Click that and you will see the screen in the photo. From here you can block any cookies you don't like. You're welcome.

NOTE: If you like to stay signed in to your Google account, don't block any Google cookies.