Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using EZLogger. I included its .cs file in my C# project. I referenced it in my using statement (can you tell I'm a little new at C#?) and I instantiate and use it in my main program.

But I want methods located in another class to be able to use the initial instance of the class. I can't quite figure out how to scope it to make it work.

I know it's simple, but I just need a little push here....

Thanks.

Jim

The code:

using System;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Office.Interop.Access;
using RavSoft;                              // Namespace for EZLogger

namespace BuyerFeedback
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set up the logging system.
            string logPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string logLocation = logPath + "\\CPAS\\BuyerFeedback.log";
            uint logLevels = (uint)EZLogger.Level.All;
            EZLogger logger =
              new EZLogger(logLocation,                 // log filename
                        true,                       // don't append
                        logLevels);                 // log levels of interest
            bool bStatus = logger.Start();
            logger.Info("Run Begins");
            int docCount = 0;                           // counts the number of documents processed
            Utilities u = new Utilities();
            // Set up the List Service class, pointing to the Buyer Feedback Site.
            BuyerFeedbackSite.Lists listService = new BuyerFeedback.BuyerFeedbackSite.Lists();
            listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            listService.Url = "http://moss.mava.xxx.com/FACSEC/mtvfacilities/MTVCONSTRUCTION/CPASBuyerFeedback/_vti_bin/lists.asmx";     // Buyer Feedback Site
            string listGUID = "32B85C43-824A-44F9-BA26-C4A201913534";   // Buyer Feedback Tasks
            string activeItemViewGUID = "99AA7CC4-D5A0-4110-BF28-AB1AE01E6000"; // "Task" View
            System.Xml.XmlNode activeItemData = listService.GetListItems(listGUID, activeItemViewGUID, null, null, "500", null, "");
            // Set up the XML documents the listservice will retrieve.
            XmlDocument doc = new XmlDocument();
            string temp=activeItemData.InnerXml.Replace("\ref\ref","");
            doc.LoadXml(temp);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("z","#RowsetSchema");
            nsmgr.AddNamespace("rs","urn:schemas-microsoft-com:rowset");
            XmlNodeList xl=doc.SelectNodes("/rs:data/z:row",nsmgr);
            // Process each document.
            foreach (XmlNode node in xl)
            {
                string id = node.Attributes["ows_ID"].InnerText;
                string link = node.Attributes["ows_WorkflowLink"].InnerText;
                string author = node.Attributes["ows_Author"].InnerText;
                string status = node.Attributes["ows_Status"].InnerText;
                link = link.Split(',')[0];              //strips off the stuff after the comma
                string blah = u.postSheet(link,author,id);
                blah = u.UpdateList(listService, id, blah);
                logger.Info("ID " + id.ToString() + " Posted");
                docCount++;
            }
            StringBuilder logInfo = new StringBuilder("BuyerFeedback Finished.  Processed ");
            logInfo.Append(docCount);
            logInfo.Append("  Documents");
            logger.Info(logInfo.ToString());
            logger.Stop();
        }
    }
    class Utilities
    {
        public string postSheet(string sheet, string spCreator, string ID)
        {
            StringBuilder errorMessage = new StringBuilder();
            int rowsDeleted = 0;
            int rowsUpdated = 0;
            int rowsInserted = 0;
            const string deleteQuery = "DELETE * FROM tblBuyerFeedbackDetail";
            const string dbName = @"H:\mtv\secure\Construction\Access\CPAS WorkArea\Jim\CPASBuyerFeedback.accdb";
            
            System.Data.OleDb.OleDbConnection conn = 
                new System.Data.OleDb.OleDbConnection(
                "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + dbName);
            Microsoft.Office.Interop.Access.ApplicationClass oAccess = 
                new Microsoft.Office.Interop.Access.ApplicationClass();
            try
            {
                oAccess.OpenCurrentDatabase(dbName, false, null);
                conn.Open();
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(deleteQuery, conn);
                rowsDeleted = cmd.ExecuteNonQuery();
            
                object tblBuyerFeedbackDetail = "tblBuyerFeedbackDetail";
                oAccess.DoCmd.TransferSpreadsheet(AcDataTransferType.acImport,
                            Microsoft.Office.Interop.Access.AcSpreadSheetType.acSpreadsheetTypeExcel12Xml,
                            tblBuyerFeedbackDetail,
                            sheet,
                            true,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value);
                System.Threading.Thread.Sleep(5000);
                string now = DateTime.Now.ToShortDateString();
                string strSQL = @"UPDATE tblBuyerFeedbackDetail SET SPDocID=" + ID + @", SPCreateDate=#" + now + @"#" + @", SPCreateUser='" + parseAccount(spCreator) + @"'";
                cmd.CommandText = strSQL;
                rowsUpdated = cmd.ExecuteNonQuery();
                StringBuilder oSB= new StringBuilder("INSERT INTO tblShipDetail ( ShipPLID, ShipComment, ShipUserID, ShipEntryDate, Ordered, ShipDate )");
                oSB.Append(@" SELECT tblPickListDetail.PLDetailID, '{SP (' & [SPDocID] & ') ' & [SPCreateDate] & '}' & IIf(IsNull([PONbr]),'',' PO ' & [PONbr]) & IIf(IsNull([EstGRDate]),'',' ETA ' & [EstGRDate]) & [buyercomments] AS ConstructedComment, tblBuyerFeedbackDetail.SPCreateUser, tblBuyerFeedbackDetail.SPCreateDate, True AS Ord, tblBuyerFeedbackDetail.EstGRDate ");
                oSB.Append(@" FROM tblBuyerFeedbackDetail INNER JOIN tblPickListDetail ON tblBuyerFeedbackDetail.BoMDetailID = tblPickListDetail.PLBoMDetailID");
                strSQL = oSB.ToString();
                cmd.CommandText = strSQL;
                rowsInserted = cmd.ExecuteNonQuery();
                System.Data.DataTable tbls = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] {null,null,null});
                int RowCount=0;
                String errorTable = "";
                for (RowCount = 0; (RowCount <= (tbls.Rows.Count - 1)); RowCount++) 
                {
                    errorTable = tbls.Rows[RowCount]["TABLE_NAME"].ToString();
                    if (errorTable.Contains(@"_ImportErrors"))
                    {
                        //Console.WriteLine(tbls.Rows[RowCount]["TABLE_NAME"]);
                        errorMessage.Append(parseErrors(errorTable,conn));
                        cmd.CommandText = "Drop Table [" + errorTable + "]";
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            finally
            {
                conn.Close();
                oAccess.CloseCurrentDatabase();
            }
            StringBuilder oSB1 = new StringBuilder();
            oSB1.Append(errorMessage);
            string returnValue = oSB1.ToString();
            return returnValue;
        }
        public string parseAccount (string inAccount)
        {
            string[] halfs = inAccount.Split(')');
            string[] leftHalves = halfs[0].Split('(');
            return leftHalves[1];
        }
        public string UpdateList(BuyerFeedbackSite.Lists ListService, string ID, string ErrorMessage)
        {
            string completionStatus="Processed";
            if (string.IsNullOrEmpty(ErrorMessage)==false)
                completionStatus="Processed With Errors";
            string strBatch =
                "<Method ID='1' Cmd='Update'>" +
                "<Field Name='ID'>" + ID + "</Field>" +
                "<Field Name='Errors'>" + ErrorMessage + "</Field>" +
                "<Field Name='Status'>" + completionStatus + "</Field>" +
                "</Method>";
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
            elBatch.SetAttribute("OnError", "Continue");
            elBatch.SetAttribute("ListVersion", "1");
            elBatch.SetAttribute("ViewName", "");
            elBatch.InnerXml = strBatch;
            XmlNode ndReturn = ListService.UpdateListItems("Feedback Posting Status (Tasks)", elBatch);
            return ndReturn.InnerText;
        }
        public string parseErrors(string TableName,System.Data.OleDb.OleDbConnection Connection)
        {
            string sql = "SELECT * FROM [" + TableName + "]";
            string row;
            string field;
            string message;
            StringBuilder sbErrors=new StringBuilder();
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, Connection);
            System.Data.OleDb.OleDbDataReader reader=cmd.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    row = reader.GetInt32(2).ToString();
                    field = reader.GetString(1).ToString();
                    message = reader.GetString(0).ToString();
                    sbErrors.Append("Row ");
                    sbErrors.Append(row);
                    sbErrors.Append(" Column ");
                    sbErrors.Append(field);
                    sbErrors.Append(" ");
                    sbErrors.AppendLine(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            finally
            {
                reader.Close();
            }
            return sbErrors.ToString();
        }
        public void updateProjectBudgets()
        {
            const string appendQuery = @"INSERT INTO tblCPTransaction ( CPTransType, CPTransAmount, CPProjectID, CPTransComment, CPTransUserID, CPTransCreateDate ) SELECT 2 AS Expr1, P.ProjectBudget, P.ID, 'Auto Added -- JS' AS Expr2, 'JAMESSHAFFER' AS Expr3, Date() AS Expr4 FROM tblProjects AS P LEFT JOIN tblCPTransaction AS T ON P.ID = T.CPProjectID WHERE (((T.CPTransID) Is Null) AND ((P.ProjectBudget) Is Not Null))";
            int rowsInserted = 0;
            System.Data.OleDb.OleDbConnection conn = null;
            conn = new System.Data.OleDb.OleDbConnection(
                "Provider=Microsoft.ACE.OLEDB.12.0; " +
                @"Data Source=H:\mtv\secure\Construction\Access\CPAS\Backend\Composite_be.accdb");
            try
            {
                conn.Open();
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(appendQuery, conn);
                rowsInserted = cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
            finally
            {
                conn.Close();
            }
        }
        
    }
    public static class Globals
    {
        private EZLogger logger = new EZLogger();
        public EZLogger Logger { get; set; }
    }
}
Posted
Updated 25-May-11 2:37am
v2

Create a static class that instantiates EZLogger, and then you can do something like this:

C#
public static class Globals
{
    private EZLogger logger = new EZLogger();
    public EZLogger Logger { get; set; }
}


And refer to it like this, anywhere in your code:

C#
Globals.Logger.blah blah
 
Share this answer
 
Comments
Jim from Indy 20-May-11 16:06pm    
I put it in the same namespace as my main program. It said "cannot declare instance members in a static class..." and "Inconsistent accessibility: property type 'RavSoft.EZLogger' is less accessible than property 'BuyerFeedback.Globals.Logger'" -- EZLogger, obviously, is in a different namespace.
Jim from Indy 23-May-11 9:37am    
John, any ideas?
#realJSOP 24-May-11 20:38pm    
Modify your original question with the source code. My first guess is that you didn't make either the class itself or the property public. BTW, just because you made a mistake doesn't mean my answer wasn't correct. :)
Jim from Indy 25-May-11 10:48am    
I am grateful for your answer. I needed to understand what I misunderstood so I could make it work. I looked up static classes in my reference book, and it gives them short shrift, so I needed to rely on you to understand what I did wrong. Never suggested you were wrong. Sorry if I gave that impression.
Jim from Indy 25-May-11 10:58am    
I did change the EZLogger declaration in the .cs file from "class EZLogger" to "public class EZLogger", and that eliminated the "inconsistent accessibility" error. The other two errors persist. Should point out I'm using VS2005.
There are several options

Create the class as a static object
Create a container class that exposes the logging functionality
Create another assembly that handles logging
Expose events that the other classes call to log something
Pass the instance of the logger class to the other classes
Use another logger, such as the Microsoft Enterprise Library.
 
Share this answer
 
Comments
Jim from Indy 20-May-11 15:52pm    
Mark, I think you exceeded my expertise. I don't want to pass the instance. Too many methods. I don't know how to create the clas as a static object. I'm not sure how to create a container class for this, though since I'm only using a few methods, this sounds intriguing. I didn't understand "Expose events....", and I just printed the article on the Microsoft Enterprise Library.

Thanks for the push. If you'd care to expound on the options I didn't understand, I'll be grateful, but you've gotten me started. Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900