• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 576
  • Last Modified:

NullReferenceException in VS2010 from VS2005

I inherited this project that was created in VS2005. When I recompile it I keep getting the following error below. The code follows. What may cause this? Thanks.

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=COMPANYLOG
  StackTrace:
       at COMPANYLOG.COMPANYLOG.COMPANYLOG_Load(Object sender, EventArgs e) in F:\DMOSTAT\COMPANYLOG\COMPANYLOG\COMPANYLOG.cs:line 111
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at COMPANYLOG.Program.Main() in F:\DMOSTAT\COMPANYLOG\COMPANYLOG\Program.cs:line 17
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.SqlServer.Server;

namespace COMPANYLOG
{
    public partial class COMPANYLOG : Form
    {
        public COMPANYLOG()
        {
            InitializeComponent();
        }

        private string datasource = "Data Source=111.0.0.1;Initial Catalog=COMPANYorders;Persist Security Info=True;User ID=COMPANYlog;Password=XXXXX";
        private string excel_path = @"D:\data\COMPANYsql\reports\temp\COMPANY.xls";
        private string excel_path2 = @"D:\data\COMPANYsql\reports\temp\COMPANY_count.xls";
        public enum ExportFormat : int { CSV = 1, Excel = 2 };
        private int yes = 0;
        private int no = 0;

        private void COMPANYLOG_Load(object sender, EventArgs e)
        {
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.Visible = false;
            this.ShowInTaskbar = false;
            this.Hide();

            SqlConnection conn;
            SqlCommand cmd;
            DataSet ds = new DataSet("logs");
            string start_date = DateTime.Now.AddDays(-7).ToShortDateString();
            string end_date = DateTime.Now.AddDays(1).ToShortDateString();

            conn = new SqlConnection(datasource);
            cmd = new SqlCommand("COMPANYorders.dbo.logs", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                DataTable dt = new DataTable();
                dt.TableName = "logs";
                dt.Load(reader);
                dt.Columns.Add(new DataColumn("Request", typeof(string)));
                dt.Columns.Add(new DataColumn("RequestData", typeof(string)));
                dt.Columns.Add(new DataColumn("ReturnedData", typeof(string)));
                ds.Tables.Add(dt);
            }
            catch (SqlException)
            {
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
            }

            conn = new SqlConnection(datasource);
            cmd = new SqlCommand("COMPANYorders.dbo.logs_count", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                DataTable dt = new DataTable();
                dt.TableName = "logscount";
                dt.Load(reader);
                dt.Columns.Add(new DataColumn("dmwsusr1", typeof(string)));
                dt.Columns.Add(new DataColumn("dmwsusr2", typeof(string)));
                dt.Columns.Add(new DataColumn("ReturnedData", typeof(string)));
                dt.Columns.Add(new DataColumn("ReturnedNoData", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByAccountNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByEmailAddress", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByFullNameZipNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByNameZipNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByOrderNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByPhoneNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByZipAcctNum", typeof(string)));  
                dt.Columns.Add(new DataColumn("GetCustomerByZipOrderNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetCustomerByZipWebConfNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetOrderByOrderNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetOrderByWebOrderNum", typeof(string)));
                dt.Columns.Add(new DataColumn("GetOrdersForCustomer", typeof(string)));
                ds.Tables.Add(dt);
            }
            catch (SqlException)
            {
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
            }

            foreach (DataRow row in ds.Tables["logs"].Rows)
            {
                row.BeginEdit();
                string[] change = Regex.Split(row[1].ToString(), "::");
                try
                {
                    row[1] = Regex.Replace(change[0].Trim(), @"COMPANYSQLSRV3", "").Remove(0, 1);
                    row[2] = Regex.Replace(change[1].Trim(), "GetCustomerByWebConfNum", "GetCustomerByZipWebConfNum");
                    row[3] = "'" + change[2].Trim() + "'";
                    if (Convert.ToInt32(change[3]) > 0)
                    {
                        row[4] = "Yes";
                        yes++;
                    }
                    else
                    {
                        row[4] = "No";
                        no++;
                    }
                }
                catch (IndexOutOfRangeException)
                {
                }
                Array.Clear(change, 0, change.Length);
                row.AcceptChanges();
                row.EndEdit();
            }

            foreach (DataRow row in ds.Tables["logscount"].Rows)
            {
                row.BeginEdit();
                string[] change = Regex.Split(row[0].ToString(), "::");
                try
                {
                    row[1] = "'" + change[0].Trim() + "'";
                    row[2] = "'" + change[1].Trim() + "'";
                    row[3] = "'" + yes.ToString() + "'";
                    row[4] = "'" + no.ToString() +"'";
                    row[5] = "'" + change[2].Trim() + "'";
                    row[6] = "'" + change[3].Trim() + "'";
                    row[7] = "'" + change[4].Trim() + "'";
                    row[8] = "'" + change[5].Trim() + "'";
                    row[9] = "'" + change[6].Trim() + "'";
                    row[10] = "'" + change[7].Trim() + "'";
                    row[11] = "'" + change[8].Trim() + "'";
                    row[12] = "'" + change[9].Trim() + "'";
                    row[13] = "'" + change[10].Trim() + "'";
                    row[14] = "'" + change[11].Trim() + "'";
                    row[15] = "'" + change[12].Trim() + "'";
                    row[16] = "'" + change[13].Trim() + "'";
                }
                catch (Exception)
                {
                }
                Array.Clear(change, 0, change.Length);
                row.AcceptChanges();
                row.EndEdit();
            }

            DataTable dt2 = new DataTable();
            dt2 = ds.Tables["logscount"].Copy();
            dt2.Columns.Remove("dmwsusr");
            DataSet ds2 = new DataSet();
            ds2.Tables.Add(dt2);

            ExportDetails(ds.Copy().Tables["logs"], ExportFormat.Excel, excel_path);
            ExportDetails(ds2.Copy().Tables["logscount"], ExportFormat.Excel, excel_path2);

            Thread.Sleep(200);
            Sendmail mail = new Sendmail();
            mail.Send("Report Summary Date Range: " + DateTime.Now.AddDays(-7).ToShortDateString() + " - " + DateTime.Now.ToShortDateString() + "", "DM OSTAT WEEKLY STATISTICS REPORT");
            mail = null;

            Thread.Sleep(10000);

            //File.Delete(excel_path);
            //File.Delete(excel_path2);

            Thread.Sleep(200);
            this.Close();
        }

        public void ExportDetails(DataTable DetailsTable, ExportFormat FormatType, string FileName)
        {
            try
            {
                if (DetailsTable.Rows.Count == 0)
                {
                    throw new Exception("There are no details to export.");
                }

                DataSet dsExport = new DataSet("Export");
                DataTable dtExport = DetailsTable.Copy();
                dtExport.TableName = "Values";
                dsExport.Tables.Add(dtExport);

                string[] sHeaders = new string[dtExport.Columns.Count];
                string[] sFileds = new string[dtExport.Columns.Count];

                for (int i = 0; i < dtExport.Columns.Count; i++)
                {
                    sHeaders[i] = dtExport.Columns[i].ColumnName;
                    sFileds[i] = dtExport.Columns[i].ColumnName;
                }
                    ExportExcel(dsExport, sHeaders, sFileds, FormatType, FileName);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        public void ExportDetails(DataTable DetailsTable, int[] ColumnList, ExportFormat FormatType, string FileName)
        {
            try
            {
                if (DetailsTable.Rows.Count == 0)
                    throw new Exception("There are no details to export");

                DataSet dsExport = new DataSet("Export");
                DataTable dtExport = DetailsTable.Copy();
                dtExport.TableName = "Values";
                dsExport.Tables.Add(dtExport);

                if (ColumnList.Length > dtExport.Columns.Count)
                    throw new Exception("ExportColumn List should not exceed Total Columns");

                string[] sHeaders = new string[ColumnList.Length];
                string[] sFileds = new string[ColumnList.Length];

                for (int i = 0; i < ColumnList.Length; i++)
                {
                    if ((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))
                        throw new Exception("ExportColumn Number should not exceed Total Columns Range");

                    sHeaders[i] = dtExport.Columns[ColumnList[i]].ColumnName;
                    sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;
                }

                    ExportExcel(dsExport, sHeaders, sFileds, FormatType, FileName);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        public void ExportExcel(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
        {
            try
            {					
                MemoryStream stream = new MemoryStream();
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                
                CreateStylesheet(writer, sHeaders, sFileds, FormatType);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
                XslTransform xslTran = new XslTransform();
                xslTran.Load(new XmlTextReader(stream), null, null);

                System.IO.StringWriter sw = new System.IO.StringWriter();
                xslTran.Transform(xmlDoc, null, sw, null);
								
                StreamWriter strwriter = new StreamWriter(FileName);
                strwriter.WriteLine(sw.ToString());
                strwriter.Close();

                sw.Close();
                writer.Close();
                stream.Close();
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        private void CreateStylesheet(XmlTextWriter writer, string[] sHeaders, string[] sFileds, ExportFormat FormatType)
        {
            try
            {
                // xsl:stylesheet
                string ns = "http://www.w3.org/1999/XSL/Transform";
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("xsl", "stylesheet", ns);
                writer.WriteAttributeString("version", "1.0");
                writer.WriteStartElement("xsl:output");
                writer.WriteAttributeString("method", "text");
                writer.WriteAttributeString("version", "4.0");
                writer.WriteEndElement();

                // xsl-template
                writer.WriteStartElement("xsl:template");
                writer.WriteAttributeString("match", "/");

                // xsl:value-of for headers
                for (int i = 0; i < sHeaders.Length; i++)
                {
                    writer.WriteString("\"");
                    writer.WriteStartElement("xsl:value-of");
                    writer.WriteAttributeString("select", "'" + sHeaders[i] + "'");
                    writer.WriteEndElement(); // xsl:value-of
                    writer.WriteString("\"");
                    if (i != sFileds.Length - 1) writer.WriteString((FormatType == ExportFormat.CSV) ? "," : "	");
                }

                // xsl:for-each
                writer.WriteStartElement("xsl:for-each");
                writer.WriteAttributeString("select", "Export/Values");
                writer.WriteString("\r\n");

                // xsl:value-of for data fields
                for (int i = 0; i < sFileds.Length; i++)
                {
                    writer.WriteString("\"");
                    writer.WriteStartElement("xsl:value-of");
                    writer.WriteAttributeString("select", sFileds[i]);
                    writer.WriteEndElement(); // xsl:value-of
                    writer.WriteString("\"");
                    if (i != sFileds.Length - 1) writer.WriteString((FormatType == ExportFormat.CSV) ? "," : "	");
                }

                writer.WriteEndElement(); // xsl:for-each
                writer.WriteEndElement(); // xsl-template
                writer.WriteEndElement(); // xsl:stylesheet
                writer.WriteEndDocument();
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        protected virtual SqlParameter getParam(string name, int value)
        {
            SqlParameter param = new SqlParameter("@" + name, SqlDbType.Int);
            param.Value = value;
            return param;
            //cmd.Parameters.Add(getParam("user", ""));
        }

        protected virtual SqlParameter getParam(string name, string value)
        {
            SqlParameter param = new SqlParameter("@" + name, SqlDbType.VarChar);
            param.Value = value;
            return param;
        }

        protected virtual SqlParameter getParam(string name, bool value)
        {
            SqlParameter param = new SqlParameter("@" + name, SqlDbType.Bit);
            param.Value = value;
            return param;
        }
    }
}

Open in new window

0
ironpen45
Asked:
ironpen45
  • 4
  • 3
1 Solution
 
Julian HansenCommented:
If the source file is exactly as it is on your side then line 111 is this line

foreach (DataRow row in ds.Tables["logs"].Rows)

Which means that ds.Tables['logs'] is not being found.

This probably means that code before this failed.

If you put a debug message in the first catch - you will probably see output from that as it is probably something in the try loop that is failing which is why the logs table is not being added.

If you step throug the code with a debugger from lines 48 to 61 you should see which line is failing - it will throw you to the catch statement - you can then look at that statement which should give you more info on what is happening.
0
 
ironpen45Author Commented:
@julianh. i stepped thru the code and found that the problem was connecting to the SQL Server. apparently the connection string (line 26) works when this EXE runs on the the same box.

i'm running this from another box on the same network, i have Windows Authentication rights to the SQL Server as well.

am i missing something or need to change the connection string?
0
 
Julian HansenCommented:
Depends on the installation of sql server. If you are using Express the default install is to only allow local conections.

What version of SQL are you running?
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
ironpen45Author Commented:
@julianh: definitely MS SS 2005.

I just realized that the path included the "built in" ip address of 12.0.0.1. so i changed to the right ip address. so this time it went a bit further until i ran into the following error:


System.IO.IOException was caught
  Message=The device is not ready.

  Source=COMPANYLOG
  StackTrace:
       at COMPANYLOG.COMPANYLOG.ExportExcel(DataSet dsExport, String[] sHeaders, String[] sFileds, ExportFormat FormatType, String FileName) in F:\DMOSTAT\COMPANYLOG\COMPANYLOG\COMPANYLOG.cs:line 287
       at COMPANYLOG.COMPANYLOG.ExportDetails(DataTable DetailsTable, ExportFormat FormatType, String FileName) in F:\DMOSTAT\COMPANYLOG\COMPANYLOG\COMPANYLOG.cs:line 216
  InnerException:

any further ideas?
0
 
Julian HansenCommented:
I guess the message is quite clear "Device is not ready" indicates something it is trying to write to is not available.

You need to look at line 287 and 216 of COMPANYLOG.cs to see what the ExportExcel and ExportDetails functions are trying to do with respect to external resources.

You said you are
running this on another box
- so maybe this new machine does not have the same destination for output that the previous one had?
0
 
ironpen45Author Commented:
@julianH: you convinced me to run the app back on the server. even after modifying it on another machine, it still works from where it's supposed to run from. thanks.
0
 
Julian HansenCommented:
Ok - you are welcome. Thanks for the points
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now