Friday, October 27, 2017

NuGet How I Hate Thee, Let Me Count the Ways

An error occurred while trying to restore packages: Unable to find version 2.0.1 of package Microsoft.AspNet.Providers.LocalDB.


Unable to find version '2.0.1' of package 'Microsoft.AspNet.Providers.LocalDB'.

Unable to find version '2.0.1' of package 'Microsoft.AspNet.Providers.LocalDB'.

Saturday, October 21, 2017

rare case of ternary operator I approve of

var  thingamajig= Request.QueryString["thingamajig"] ?? Request.Form["thingamajig"];

see  null-coalescing operator ?? double question-mark





Saturday, October 14, 2017

Gnossis or Gnosis

String product = ConfigurationManager.AppSettings["reportProduct"];
                String buildVersion = ConfigurationManager.AppSettings["appBuild"];
                string productVersionNumberFromDll = "";
                string fileVersionNumberFromDll = "";
                try
                {
                    string dllFile = Server.MapPath("bin/applicationWeb.dll");
                    FileVersionInfo dllFileVersionInfo = FileVersionInfo.GetVersionInfo(dllFile);
                    fileVersionNumberFromDll = dllFileVersionInfo.FileVersion;
                    productVersionNumberFromDll = dllFileVersionInfo.ProductVersion;
                }
                catch (Exception)
                {                 
                    //throw;
                }
             
                try
                {
                    string NETAssemblyVersion = Environment.Version.ToString();
                    string OS = Environment.OSVersion.ToString();
                    string MachineName = Environment.MachineName.ToString();
                    string UserDomainName = Environment.UserDomainName.ToString();
                    string UserName = Environment.UserName.ToString();

                    Response.Write("Product: " + product);
                    Response.Write("<BR>application Version: " + buildVersion);
                    Response.Write("<BR>dll File Version: " + fileVersionNumberFromDll);
                    Response.Write("<BR>dll Product Version: " + productVersionNumberFromDll);
                    Response.Write("<BR>");

                    Response.Write(".NET Version: " + NETAssemblyVersion + "<BR>");
                    Response.Write("OS: " + OS + "<BR>");
                    Response.Write("MachineName: " + MachineName + "<BR>");
                    Response.Write("UserDomainName: " + UserDomainName + "<BR>");
                 
                    Response.Write("UserName: " + UserName + "<BR>");

                    string myConn = DBConnection.getDBConnection();
                    Response.Write("<P>" + myConn);



                    Response.Write("URL Components<BR><HR><BR>");
                    Response.Write(" Request.Url.Scheme : " + Request.Url.Scheme + "<BR>");
                    Response.Write(" Request.Url.Host  : " + Request.Url.Host + "<BR>");
                    Response.Write(" Request.Url.IsDefaultPort : " + Request.Url.IsDefaultPort.ToString() + "<BR>");
                    Response.Write(" Request.Url.Port : " + Request.Url.Port + "<BR>");
                 
                    // string URLprefix = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    //throw;
                }

Error Handling in ASP.NET

In Global.asax:


void Application_Error(object sender, EventArgs e)
        {
            Exception exc = Server.GetLastError();

            if (exc is HttpUnhandledException)
            {
                if (ConfigurationManager.AppSettings["logErrorsInDb"] == "true")
                {
                    try
                    {
                        string UserId = "n/a";
                        if (Session["usernameEmail"] != null)
                        {
                            UserId = Session["usernameEmail"].ToString();
                        }

                        string Webpage = Request.PhysicalPath;

                        // get IP **********************************
                        string IP = "n/a";
                        System.Web.HttpContext context = System.Web.HttpContext.Current;
                        string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                        if (!string.IsNullOrEmpty(ipAddress))
                        {
                            string[] addresses = ipAddress.Split(',');
                            if (addresses.Length != 0)
                            {
                                IP = addresses[0];
                            }
                        }
                        else
                        {
                            IP = context.Request.ServerVariables["REMOTE_ADDR"];
                        }
                        // *******************************************

                        Persist persist = new Persist();
                        persist.logError(exc.InnerException.Message, UserId, exc.InnerException.StackTrace, Webpage, IP);
                    }
                    catch (Exception ex)
                    {


                    }
                }
                // Pass the error on to the error page.
                Server.Transfer("Oops.aspx?handler=Application_Error%20-%20Global.asax", true);
            }













My simple error logger:

public void logError(String Message, String UserId, String StackTrace, String Webpage, String IP)
        {
            using (SqlConnection cn = new SqlConnection(DBConnection.getDBConnection()))
            {
                int rowsAffected = 0;

                String sql = @"INSERT INTO [dbo].[ErrorLog](Message,UserId,StackTrace,Webpage,IP)
VALUES(@Message,@UserId,@StackTrace,@Webpage,@IP)";
             
SqlCommand cmd = new SqlCommand(sql, cn);
                cmd.CommandType = System.Data.CommandType.Text;
                if (Message.Length > 1000)
                {
                    Message = Message.Substring(0, 999);
                }
             
cmd.Parameters.AddWithValue("@Message", Message);
                cmd.Parameters.AddWithValue("@UserId", UserId);
                if (StackTrace.Length > 3000)
                {
                    StackTrace = StackTrace.Substring(0, 2999);
                }
             
cmd.Parameters.AddWithValue("@StackTrace", StackTrace);
                if (Webpage.Length > 500)
                {
                    Webpage = Webpage.Substring(0, 499);
                }
             
cmd.Parameters.AddWithValue("@Webpage", Webpage);
                cmd.Parameters.AddWithValue("@IP", IP);

                try
                {
                    cn.Open();
                    rowsAffected = cmd.ExecuteNonQuery();
                }
                catch (Exception err)
                {
}
            }
        }






















DDL for table:


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ErrorLog](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](1000) NULL,
[Timestamp] [datetime] NULL DEFAULT (getdate()),
[UserId] [nvarchar](50) NULL,
[StackTrace] [nvarchar](max) NULL,
[Webpage] [nvarchar](500) NULL,
[IP] [nvarchar](50) NULL,
 CONSTRAINT [PK_ErrorLog] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Thursday, October 5, 2017

Git Git!

  1. Commit will simply make record of your changes that you have made on your local machine. It will not mark the change in the remote repository.
  2. Commit and Push will do the above and push it to the remote repository. This means that any changes you have made will be saved to the remote repository as well.
  3. Commit and Sync does three things. First, it will commit. Second, it will perform a pull (grabs the updated information from the remote repo). Finally, it will push.
Microsoft tutorial here:


  • fetch , which downloads the changes from your remote repo but does not apply them to your code.
  • merge , which applies changes taken from fetch to a branch on your local repo.
  • pull , which is a combined command that does a fetch and then a merge.



Difference Between DBNull.Value and Null Reference

Let's say you are looking up some numerical value in a table, based on some id, like a PRODUCT ID, for example, the PRICE. 

If the table allows nulls for the PRICE (and in the real world, sometimes this happens, out of your control), then it is possible that there is a PRODUCT ID in the table that has a NULL price.  If you do a query in SQL Server Mgt Studio, you'll actually see it say in the cell, NULL.

On the other hand, let's say that the PRODUCT ID is erroneous, that is, it does not exist in the table.  So a query for the price would return no rows.

If you are using ExecuteScalar(), then you have two possible types of null situations to consider.

In the former situation, ExecuteScalar() would return an object which has the value of DBNull.Value.
In the latter, it would return null.


Example:
object returnValue = cmd.ExecuteScalar();
if(returnValue == DBNull.Value){
//table allows nulls for this field
}

if(returnValue == null) {
// no records were returned
}


if(returnValue != null && returnValue != DBNull.Value){
     double price = (double)returnValue;
}