Determinate type of object and pass it through method

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 1903 Views - Last Post: 30 September 2014 - 07:17 AM Rate Topic: -----

#1 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Determinate type of object and pass it through method

Posted 18 September 2014 - 02:41 AM

Hi guys, i got base class called Statistic and inherited classes from it : lsp, cpu, memory. Those methods inheriting some of methods from Statistic and implement also theirself methods. I prepared some new class called ExecuteRequest which is taking Statistic object in the constructor. What i want to achieve is after i put e.g LSP to this class i would like to determinate what specific object it is in this case LSP right? Then having that i would like to put this object to RunRequest method. How can i achieve that? See my code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SOAP_testing
{
    public class ExecuteRequest
    {
        public Statistic KPI { get; set; }
        public LSPGetInventory LSPGetInventory { get; set; }
        public LSP LSP { get; set; }
        public CPU CPU { get; set; }
        public Memory Memory { get; set; }

        public ExecuteRequest(Statistic kpi)
        {
            this.KPI = kpi;
            DeterminateKpiType(KPI);
        }

        public void DeterminateKpiType(Statistic KPI)
        {
            if (KPI.GetType() == typeof(LSP))
            {
                LSP = KPI as LSP;
                RunRequest(LSP);
            }

             if (KPI.GetType() == typeof(CPU))
            {
                CPU = KPI as CPU;
                RunRequest(CPU);
            }

             if (KPI.GetType() == typeof(Memory))
            {
                Memory = KPI as Memory;
                RunRequest(CPU);
            }

        }

        public void RunRequest<T>(T kpi)
        {
            Console.WriteLine(kpi.GetType());

            //Note calculatePower method contain every kpis (cpu,lsp,memory) so basicaly after specyfi comming type
            //appripate method will be called

            kpi.CalculatePower;  //this will call CalculatePower method for the kpi which came to this RunRequest



Is This A Good Question/Topic? 0
  • +

Replies To: Determinate type of object and pass it through method

#2 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 04:53 AM

I'm unclear how that generic RunRequest will help you. It also seems like a questionable design to have the external class ExecuteRequest doing something the the class itself should be able to do. Why save the value passed?

I'd go with something like:
public class ExecuteRequest {
    public bool RunRequest(Statistic kpi) {
        bool valid = false;
        if (kpi!=null) { 
            valid = RunRequest(kpi as LSP)
                || RunRequest(kpi as CPU)
                // ..
                ;
            if (valid) {
                Console.WriteLine(kpi.GetType());
                //Note calculatePower method contain every kpis (cpu,lsp,memory) so basicaly after specyfi comming type
                //appripate method will be called
                kpi.CalculatePower;  //this will call CalculatePower method for the kpi which came to this RunRequest
            }
        }
        return valid;
    }

    public bool RunRequest(LSP kpi) {
        if (kpi==null) { return false; }
        //
        return true;
    }

    public void RunRequest(CPU kpi) {
        if (kpi==null) { return false; }
        //
        return true;
    }



Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#3 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 05:59 AM

to see my point you need to know that my 3 classes: lsp,cpu and memory using almost the same methods (some of them are inherited from Statistic class and some of them were created in classes itself. Now i am mostly doing the same process for all three classes like this:

var MEM_kpi = new Memory(Memory.ID, KPIName.MEM, IO.Memory_requestFN, IO.Memory_requestFP,
                              IO.Memory_resultFN, IO.Memory_resultFP, IO.MEMExcelFN, IO.MEMExcelFP,
                              IO.Memory_requestTemplateFP, standbyserver);

                Logger.Log(LogMsgType.INFO, "Starting MEM at: " + DateTime.Now, IO.LogDir);
                Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
                MEM_kpi.PutValueToLSPxmlRequestTemplate(IO.Memory_requestTemplateFP, MEM_kpi.KPIName);
                Logger.Log(LogMsgType.INFO, "Starting MEM request...", IO.LogDir);
                bool isError = false;
                MEM_kpi.ExecuteSOAP(IO.Memory_requestFP, MEM_kpi.Server, MEM_kpi.KPIName, IO.Memory_resultFP, out isError);
                if (isError == false)
                { //if Request error MEM process aborted
                    bool isErrorWithCopy = false;
                    bool isErrorWithDelete = false;
                    FTP.MyFTP(SAM.xml_outputFP, MEM_kpi.ResultFullPath, MEM_kpi.ResultFileName, MEM_kpi.KPIName, out isErrorWithCopy, out isErrorWithDelete);
                    if (isErrorWithCopy == false)
                    { //if FTP error MEM process aborted
                        if (isErrorWithDelete == true)
                        {
                            Logger.Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + KPIName.LSP, IO.LogDir);
                        }
                        var AttributesList = DataOperation.CreateDataTable(MEM_kpi.GetAttributes());
                        MEM_kpi.FillDTByXMLResult(AttributesList, MEM_kpi.ResultFullPath, MEM_kpi.KPIName);
                        if (AttributesList.Rows.Count != 0)
                        {
                            Logger.Log(LogMsgType.INFO, "Putting results to Excel", IO.LogDir);
                            isError = false;
                            MEM_kpi.ExportToExcel(AttributesList, MEM_kpi.ExcelFP, MEM_kpi.ExcelFileName, MEM_kpi.KPIName, out isError);
                            if (isError == false)
                            {
                                Logger.Log(LogMsgType.INFO, "Done with MEM part", IO.LogDir);
                            }
                        }
                        else
                        {
                            Logger.Log(LogMsgType.ERROR, "MEM Result file is empty", IO.LogDir);
                        }
                        Logger.Log(LogMsgType.INFO, "Ending MEM at: " + DateTime.Now, IO.LogDir);
}
                    else
                    {
                        Logger.Log(LogMsgType.ERROR, "MEM process aborted due to FTP download file failed " + DateTime.Now, IO.LogDir);
                    }
                }
                else
                {
                    Logger.Log(LogMsgType.FATAL, "MEM process aborted due to ExecuteSOAp method failed " + DateTime.Now, IO.LogDir);
                }



after that i am doing the same as above but for LSP and then for CPU. What is replacing in that code if you look at that is MEM_kpi is replaced by object LSP_kpi.
var LSP_kpi = new LSP(LSP.ID, KPIName.LSP, IO.LSP_requestFN, IO.LSP_requestFP,
                              IO.LSP_resultFN, IO.LSP_resultFP, IO.LSPFN, IO.LSPExcelFP,
                              IO.LSP_requestTemplateFP, standbyserver);

                Logger.Log(LogMsgType.INFO, "Starting LSP at: " + DateTime.Now, IO.LogDir);
                Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
                LSP_kpi.PutValueToLSPxmlRequestTemplate(IO.LSP_requestTemplateFP, LSP_kpi.KPIName);
                Logger.Log(LogMsgType.INFO, "Starting LSP request...", IO.LogDir);
.......



So to avoid 3 pieces of code doing exactly the same butfor difffrent object (lsp,mem, cpu) i would like to create one class which would contain one piece of code which i could pass cpu,mem or lsp and then fire it up.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 06:53 AM

This alone doesn't make much sense:
// you create an instance where you pass all these parameters
var MEM_kpi = new Memory(Memory.ID, KPIName.MEM, IO.Memory_requestFN, IO.Memory_requestFP,
                              IO.Memory_resultFN, IO.Memory_resultFP, IO.MEMExcelFN, IO.MEMExcelFP,
                              IO.Memory_requestTemplateFP, standbyserver);

// wait, you passed IO.Memory_requestTemplateFP in the constructor
// why the hell would you pass MEM_kpi.KPIName to a method of MEM_kpi?!?
MEM_kpi.PutValueToLSPxmlRequestTemplate(IO.Memory_requestTemplateFP, MEM_kpi.KPIName);
// again, every single one of these parameters should be available to your instance
// also, why out?
MEM_kpi.ExecuteSOAP(IO.Memory_requestFP, MEM_kpi.Server, MEM_kpi.KPIName, IO.Memory_resultFP, out isError);



Reasonably, you should be able to put something in thie base class for this? Or make certain attributes common for it?

void SoapLog(Kpi kpi) {
    Logger.Log(LogMsgType.INFO, "Starting " + kpi.Name + " at: " + DateTime.Now, IO.LogDir);
    Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
    // kpi.PutValueToLSPxmlRequestTemplate pointless
    Logger.Log(LogMsgType.INFO, "Starting " + kpi + " request...", IO.LogDir);
    if (!kpi.ExecuteSOAP()) { // returning true on falure is kind of bass akward
        bool isErrorWithCopy = false;
        bool isErrorWithDelete = false;
        // no avoiding the outs here: sad
        FTP.MyFTP(SAM.xml_outputFP, kpi.ResultFullPath, kpi.ResultFileName, kpi.KPIName, out isErrorWithCopy, out isErrorWithDelete);
        if (!isErrorWithCopy) {
            if (isErrorWithDelete) {
                Logger.Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + kpi.KPIName, IO.LogDir);
            }
            var AttributesList = DataOperation.CreateDataTable(kpi.GetAttributes());
            kpi.FillDTByXMLResult(AttributesList);
            if (AttributesList.Rows.Count != 0) {
                Logger.Log(LogMsgType.INFO, "Putting results to Excel", IO.LogDir);
                if (!kpi.ExportToExcel(AttributesList)) {
                    Logger.Log(LogMsgType.INFO, "Done with MEM part", IO.LogDir);
                }
            } else {
                Logger.Log(LogMsgType.ERROR, kpi.Name + " Result file is empty", IO.LogDir);
            }
            Logger.Log(LogMsgType.INFO, "Ending " + kpi.Name + " at: " + DateTime.Now, IO.LogDir);
        } else {
            Logger.Log(LogMsgType.ERROR, kpi.Name + " process aborted due to FTP download file failed " + DateTime.Now, IO.LogDir);
        }
    } else {
        Logger.Log(LogMsgType.FATAL, kpi.Name + " process aborted due to ExecuteSOAp method failed " + DateTime.Now, IO.LogDir);
    }
}


Was This Post Helpful? 1
  • +
  • -

#5 Charles:)   User is offline

  • D.I.C Regular

Reputation: 149
  • View blog
  • Posts: 359
  • Joined: 26-November 09

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 09:39 AM

Usually you would put the shared logic in the base class (Statistic) and the base class has virtual or abstract methods for the bits of behaviour that change depending on the derived class. Your derived classes (lsp, cpu, memory) then override those and implement their own specific behaviour.

If you go with the method that you're currently attempting then if you add another class that derives from Statistic, you'll have to remember to update your ExecuteRequest class so that it can handle the new class, which is easy to forget and error prone. Classes should be self-contained as much as possible.
Was This Post Helpful? 1
  • +
  • -

#6 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 10:43 AM

Thanks for your comments, i think the best would be me to share with you my code and get my point to be flly clear how its implemented here then understand what i mean and we can discus how it can be changed. So please take a look:

public enum KPIName
    {
        LSP=1,
        LSPInventory,
        MEM, 
        CPU
    };

public abstract class Statistic
    {
        public int Id { get; set; }
        public KPIName KPIName { get; set; }
        public string RequestFileName { get; set; }
        public string RequestFullPath { get; set; }
        public string ResultFileName { get; set; }
        public string ResultFullPath { get; set; }
        public string ExcelFileName { get; set; }
        public string ExcelFP { get; set; }
        public Server Server { get; set; }
        public string RequestFileTemplateFullPath { get; set; }

        public Statistic(int id, KPIName kpiName, string requestFileName,
                        string requestFullPath, string resultFileName,
                        string resultFullPath, string excelFileName,
                        string excelFP, string requestFileTemplateFullPath,
                        Server server)
        {
            Id = id;
            KPIName = kpiName;
            RequestFileName = requestFileName;
            RequestFullPath = requestFullPath;
            ResultFileName = resultFileName;
            ResultFullPath = resultFullPath;
            ExcelFileName = excelFileName;
            ExcelFP = excelFP;
            RequestFileTemplateFullPath = requestFileTemplateFullPath;
            Server = server;
        }

        public abstract IEnumerable<string> GetAttributes();

        #region ExecuteSoap
        public virtual void ExecuteSOAP(string RequestFullPath, Server server, KPIName KPIName, string ResultFullPath, out bool isError)
        {
            isError = false;
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(server.ServiceHttpAdress);
                request.Headers.Add(@"SOAP:Action");
                request.ContentType = "text/xml;charset=\"utf-8\"";
                request.Accept = "text/xml";
                request.Method = "POST";

                using (var fileRequestStream = File.OpenRead(RequestFullPath))
                using (Stream webRequestStream = request.GetRequestStream())
                    fileRequestStream.CopyTo(webRequestStream);

                using (WebResponse response = request.GetResponse())    //executing request
                {
                    if (KPIName == KPIName.LSPInventory)
                    {
                        using (var rd = new StreamReader(response.GetResponseStream()))
                        {
                            string soapResult = rd.ReadToEnd();

                            var xdoc = new XmlDocument();
                            xdoc.LoadXml(soapResult);
                            xdoc.Save(ResultFullPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                isError = true;
                Logger.Log(LogMsgType.ERROR, "inside ExecuteSOAP method for " + KPIName + " error message: " + ex.ToString(), IO.LogDir);
            }
        }
        #endregion

        #region ExportToExcel
        public virtual void ExportToExcel(DataTable dt, string ExcelPath, string ExcelFN, KPIName kpiname, out bool isError)
        {
           ...
        }  
        #endregion

        abstract public DataTable FillDTByXMLResult(DataTable dt, string ResultFullPath, KPIName kpiname);

        #region PutValueToLSPxmlRequestTemplate
        public virtual void PutValueToLSPxmlRequestTemplate(string RequestFileTemplateFullPath, KPIName kpiname)
        {
            .....
        }
        #endregion


 public class LSP : Statistic
    {
        #region Constructor
        public LSP(int id, KPIName kpiName, string requestFileName,
                        string requestFullPath, string resultFileName,
                        string resultFullPath, string excelFileName,
                        string excelFP, string requestFileTemplateFullPath,
                        Server server)
            : base(id, kpiName, requestFileName,
                        requestFullPath, resultFileName,
                        resultFullPath, excelFileName,
                        excelFP, requestFileTemplateFullPath,
                        server)
        {
        }
        #endregion

        #region LSP kpi ID
        private static int _id = 2;
        public static int ID
        {
            get { return _id; }
            set { _id = value; }
        }
        #endregion

        //IEnumerable can back list<string>, string[] so its better to use like this and not jusr List<> or array[]
        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            Attributes.Add("ElemStartTimeInPrograme");
            Attributes.Add("testedObject");
            Attributes.Add("minimumRoundTripTime");
            Attributes.Add("maximumRoundTripTime");
            Attributes.Add("averageRoundTripTime");
            Attributes.Add("packetsSent");
            Attributes.Add("responsesReceived");
            Attributes.Add("packetSize");
            Attributes.Add("packetsLost");
            Attributes.Add("lossPercentage");
            Attributes.Add("timeCaptured");
            Attributes.Add("timedout");

            return Attributes;
        }

        public override DataTable FillDTByXMLResult(DataTable dt, string ResultFullPath, KPIName kpiname)
        {
           .....
    }



 public class CPU : Statistic
    {
        #region Constructor
        public CPU(int id, KPIName kpiName, string requestFileName,
                        string requestFullPath, string resultFileName,
                        string resultFullPath, string excelFileName,
                        string excelFP, string requestFileTemplateFullPath,
                        Server server)
            : base(id, kpiName, requestFileName,
                        requestFullPath, resultFileName,
                        resultFullPath, excelFileName,
                        excelFP, requestFileTemplateFullPath,
                        server)
        {
        }
        #endregion

        #region KPI ID
        private static int _id = 3;
        public static int ID
        {
            get { return _id; }
            set { _id = value; }
        }
        #endregion

        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            return Attributes;
        }


        public override DataTable FillDTByXMLResult(DataTable dt, string ResultFullPath, KPIName kpiname)
        {
                ...
}


 public class Memory : Statistic
    {
        #region Constructor
        public Memory(int id, KPIName kpiName, string requestFileName,
                        string requestFullPath, string resultFileName,
                        string resultFullPath, string excelFileName,
                        string excelFP, string requestFileTemplateFullPath,
                        Server server)
            : base(id, kpiName, requestFileName,
                        requestFullPath, resultFileName,
                        resultFullPath, excelFileName,
                        excelFP, requestFileTemplateFullPath,
                        server)
        {
        }
        #endregion

        #region KPI ID
        private static int _id = 4;
        public static int ID
        {
            get { return _id; }
            set { _id = value; }
        }
        #endregion

        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            return Attributes;
        }

        public override DataTable FillDTByXMLResult(DataTable dt, string ResultFullPath, KPIName kpiname)
        {
            ...
}



And now the main program:
static void Main(string[] args)
        {
 
            //-- LSP Kpi part --  

                var LSP_kpi = new LSP(LSP.ID, KPIName.LSP, IO.LSP_requestFN, IO.LSP_requestFP, IO.LSP_resultFN,
                                      IO.LSP_resultFP, IO.LSPExcelFN, IO.LSPExcelFP, IO.LSP_requestTemplateFP,
                                      SAM);

                Logger.Log(LogMsgType.INFO, "Starting LSP at: " + DateTime.Now, IO.LogDir);
                Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
                LSP_kpi.PutValueToLSPxmlRequestTemplate(IO.LSP_requestTemplateFP, LSP_kpi.KPIName);
                Logger.Log(LogMsgType.INFO, "Starting LSP request...", IO.LogDir);
                bool isError = false;
                LSP_kpi.ExecuteSOAP(IO.LSP_requestFP, LSP_kpi.Server, LSP_kpi.KPIName, IO.LSP_resultFP, out isError);
                if (isError == false) { //if Request error LSP process aborted
                    bool isErrorWithCopy = false;
                    bool isErrorWithDelete = false;
                    FTP.MyFTP(SAM.xml_outputFP, LSP_kpi.ResultFullPath, LSP_kpi.ResultFileName, LSP_kpi.KPIName, out isErrorWithCopy, out isErrorWithDelete);
                    if (isErrorWithCopy == false) { //if FTP error LSP process aborted
                        if (isErrorWithDelete == true) {
                            Logger.Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + KPIName.LSP, IO.LogDir);
                        }
                        var AttributesList = DataOperation.CreateDataTable(LSP_kpi.GetAttributes());
                        LSP_kpi.FillDTByXMLResult(AttributesList, LSP_kpi.ResultFullPath, LSP_kpi.KPIName);
                        if (AttributesList.Rows.Count != 0) {
                            Logger.Log(LogMsgType.INFO, "Putting results to Excel", IO.LogDir);
                            isError = false;
                            LSP_kpi.ExportToExcel(AttributesList, LSP_kpi.ExcelFP, LSP_kpi.ExcelFileName, LSP_kpi.KPIName, out isError);
                            if (isError == false) {
                                Logger.Log(LogMsgType.INFO, "Done with LSP part", IO.LogDir);
                            }
                        }
                        else {
                            Logger.Log(LogMsgType.ERROR, "LSP Result file is empty", IO.LogDir);
                        }
                        Logger.Log(LogMsgType.INFO, "Ending LSP at: " + DateTime.Now, IO.LogDir);
                    }
                    else{
                        Logger.Log(LogMsgType.ERROR, "LSP process aborted due to FTP download file failed " + DateTime.Now, IO.LogDir);
                    }
                }
                else{
                    Logger.Log(LogMsgType.FATAL, "LSP process aborted due to ExecuteSOAp method failed " + DateTime.Now, IO.LogDir);
                }
            }


            //-------------------------------------------------------------------------------------------------------
            //-- MEMORY Kpi part --
            

                var MEM_kpi = new Memory(Memory.ID, KPIName.MEM, IO.Memory_requestFN, IO.Memory_requestFP,
                              IO.Memory_resultFN, IO.Memory_resultFP, IO.MEMExcelFN, IO.MEMExcelFP,
                              IO.Memory_requestTemplateFP, SAM);

                Logger.Log(LogMsgType.INFO, "Starting MEM at: " + DateTime.Now, IO.LogDir);
                Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
                MEM_kpi.PutValueToLSPxmlRequestTemplate(IO.Memory_requestTemplateFP, MEM_kpi.KPIName);
                Logger.Log(LogMsgType.INFO, "Starting MEM request...", IO.LogDir);
                bool isError = false;
                MEM_kpi.ExecuteSOAP(IO.Memory_requestFP, MEM_kpi.Server, MEM_kpi.KPIName, IO.Memory_resultFP, out isError);
                if (isError == false)
                { //if Request error MEM process aborted
                    bool isErrorWithCopy = false;
                    bool isErrorWithDelete = false;
                    FTP.MyFTP(SAM.xml_outputFP, MEM_kpi.ResultFullPath, MEM_kpi.ResultFileName, MEM_kpi.KPIName, out isErrorWithCopy, out isErrorWithDelete);
                    if (isErrorWithCopy == false)
                    { //if FTP error MEM process aborted
                        if (isErrorWithDelete == true)
                        {
                            Logger.Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + KPIName.LSP, IO.LogDir);
                        }
                        var AttributesList = DataOperation.CreateDataTable(MEM_kpi.GetAttributes());
                        MEM_kpi.FillDTByXMLResult(AttributesList, MEM_kpi.ResultFullPath, MEM_kpi.KPIName);
                        if (AttributesList.Rows.Count != 0)
                        {
                            Logger.Log(LogMsgType.INFO, "Putting results to Excel", IO.LogDir);
                            isError = false;
                            MEM_kpi.ExportToExcel(AttributesList, MEM_kpi.ExcelFP, MEM_kpi.ExcelFileName, MEM_kpi.KPIName, out isError);
                            if (isError == false)
                            {
                                Logger.Log(LogMsgType.INFO, "Done with MEM part", IO.LogDir);
                            }
                        }
                        else
                        {
                            Logger.Log(LogMsgType.ERROR, "MEM Result file is empty", IO.LogDir);
                        }
                        Logger.Log(LogMsgType.INFO, "Ending MEM at: " + DateTime.Now, IO.LogDir);
                    }
                    else
                    {
                        Logger.Log(LogMsgType.ERROR, "MEM process aborted due to FTP download file failed " + DateTime.Now, IO.LogDir);
                    }
                }
                else
                {
                    Logger.Log(LogMsgType.FATAL, "MEM process aborted due to ExecuteSOAp method failed " + DateTime.Now, IO.LogDir);
                }


            
            //-- CPU Kpi part --
            //------------------


                #region Process CPU
                var CPU_kpi = new CPU(CPU.ID, KPIName.CPU, IO.CPU_requestFN, IO.CPU_requestFP, IO.CPU_resultFN,
                              IO.CPU_resultFP, IO.CPUExcelFN, IO.CPUExcelFP, IO.CPU_requestTemplateFP, SAM);




So now you should see inside Main i need to have 3 pieces for LSP, MEmory and CPU. Thats why i want to have only 1 piece of code as for all thre of them the code is mostly the same. What can you propose?

BAAVGAI: So from your post as i understand i need something like this insid my Statistic class ?:

public void RunRequest()
        {
            Logger.Log(LogMsgType.INFO, "Starting " + KPIName + " at: " + DateTime.Now, IO.LogDir);
            Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", IO.LogDir);
            PutValueToLSPxmlRequestTemplate(RequestFileTemplateFullPath, KPIName);
            Logger.Log(LogMsgType.INFO, "Starting " + KPIName + " request...", IO.LogDir);
            bool isError = false;
            ExecuteSOAP(RequestFullPath, Server, KPIName, ResultFullPath, out isError);
            if (isError == false)
            { //if Request error LSP process aborted
                bool isErrorWithCopy = false;
                bool isErrorWithDelete = false;
                FTP.MyFTP(Server.xml_outputFP, ResultFullPath, ResultFileName, KPIName, out isErrorWithCopy, out isErrorWithDelete);
                if (isErrorWithCopy == false)
                { //if FTP error process aborted
                    if (isErrorWithDelete == true)
                    {
                        Logger.Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + KPIName, IO.LogDir);
                    }
                    var AttributesList = DataOperation.CreateDataTable(LSP_kpi.GetAttributes());
                    FillDTByXMLResult(AttributesList, ResultFullPath, KPIName);
                    if (AttributesList.Rows.Count != 0)
                    {
                        Logger.Log(LogMsgType.INFO, "Putting results to Excel", IO.LogDir);
                        isError = false;
                        ExportToExcel(AttributesList, ExcelFP, ExcelFileName, KPIName, out isError);
                        if (isError == false)
                        {
                            Logger.Log(LogMsgType.INFO, "Done with  " + KPIName + "  part", IO.LogDir);
                        }
                    }
                    else
                    {
                        Logger.Log(LogMsgType.ERROR, KPIName + "  Result file is empty", IO.LogDir);
                    }
                    Logger.Log(LogMsgType.INFO, "Ending  " + KPIName + "  at: " + DateTime.Now, IO.LogDir);
                }
                else
                {
                    Logger.Log(LogMsgType.ERROR, KPIName + "  process aborted due to FTP download file failed " + DateTime.Now, IO.LogDir);
                }
            }
            else
            {
                Logger.Log(LogMsgType.FATAL,  KPIName + "  process aborted due to ExecuteSOAp method failed " + DateTime.Now, IO.LogDir);
            }
        }



Is that ok? The only one issue i see inside this shared method would be this line then:
var AttributesList = DataOperation.CreateDataTable(LSP_kpi.GetAttributes());


as GetAttributes belong to specific inherited classes.

This post has been edited by nighttrain: 18 September 2014 - 11:23 AM

Was This Post Helpful? 0
  • +
  • -

#7 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 12:58 PM

Wow. Just... wow.

Alright:
// dummy classes I had to make up
static class IO {
    public static string LogDir { get; set; }
    public static StatisticPaths GetPaths(KPIName kpi) {
        // your code here
        return null;
    }
}
class Server {
    public string ServiceHttpAdress { get; }
    public string xml_outputFP { get; }
}

static class FTP {
    public static void MyFTP(string xml_outputFP, string ResultFullPath, string ResultFileName, KPIName kpiName, out bool isErrorWithCopy, out bool isErrorWithDelete) {
        isErrorWithCopy = isErrorWithDelete = false;
    }
}

static class DataOperation {
    public static DataTable CreateDataTable(IEnumerable<string> attrs) { return null; }
}

enum LogMsgType { ERROR, INFO, WARNING, FATAL }

public enum KPIName { LSP = 1, LSPInventory, MEM, CPU }

// all those paths... why not paths
public class StatisticPaths {
    public string RequestFileName { get; set; }
    public string RequestFullPath { get; set; }
    public string ResultFileName { get; set; }
    public string ResultFullPath { get; set; }
    public string ExcelFileName { get; set; }
    public string ExcelFP { get; set; }
    public string RequestFileTemplateFullPath { get; set; }
    public StatisticPaths() { }
    public StatisticPaths(string requestFileName,
                    string requestFullPath, string resultFileName,
                    string resultFullPath, string excelFileName,
                    string excelFP, string requestFileTemplateFullPath,
                    Server server) {
        RequestFileName = requestFileName;
        RequestFullPath = requestFullPath;
        ResultFileName = resultFileName;
        ResultFullPath = resultFullPath;
        ExcelFileName = excelFileName;
        ExcelFP = excelFP;
        RequestFileTemplateFullPath = requestFileTemplateFullPath;
    }

}

// and, the base class
public abstract class Statistic {
    public StatisticPaths Paths { get; set; }
    public Server Server { get; set; }

    public Statistic(StatisticPaths paths, Server server) {
        this.Server = server;
        this.Paths = paths;
    }
    public abstract int Id { get; }
    public abstract KPIName KPIName { get; }

    public virtual string Name { get { return this.KPIName.ToString(); } }

    public virtual IEnumerable<string> GetAttributes() { return new List<string>(); }
    public abstract DataTable FillDTByXMLResult(DataTable dt);
    public abstract bool ExportToExcel(DataTable dt);
    // public abstract DataTable FillDTByXMLResult(DataTable dt, string ResultFullPath);
    // public abstract bool ExportToExcel(DataTable dt, string ExcelPath, string ExcelFN);
    // public abstract void PutValueToLSPxmlRequestTemplate(string RequestFileTemplateFullPath);

    protected virtual void Log(LogMsgType lt, string msg) {

    }

    public virtual bool ExecuteSOAP() {
        var success = true;
        try {
            var request = (HttpWebRequest)WebRequest.Create(Server.ServiceHttpAdress);
            request.Headers.Add(@"SOAP:Action");
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept = "text/xml";
            request.Method = "POST";

            using (var fileRequestStream = File.OpenRead(Paths.RequestFullPath)) {
                using (Stream webRequestStream = request.GetRequestStream()) {
                    fileRequestStream.CopyTo(webRequestStream);
                }
            }

            using (WebResponse response = request.GetResponse()) {
                if (KPIName == KPIName.LSPInventory) {
                    using (var rd = new StreamReader(response.GetResponseStream())) {
                        var xdoc = new XmlDocument();
                        xdoc.LoadXml(rd.ReadToEnd());
                        xdoc.Save(Paths.ResultFullPath);
                    }
                }
            }
        } catch (Exception ex) {
            success = false;
            Log(LogMsgType.ERROR, "inside ExecuteSOAP method for " + KPIName + " error message: " + ex.ToString());
        }
        return success;
    }

    public virtual void CallExecuteSoap() {
        // var LSP_kpi = new LSP(LSP.ID, KPIName.LSP, IO.LSP_requestFN, IO.LSP_requestFP, IO.LSP_resultFN, IO.LSP_resultFP, IO.LSPExcelFN, IO.LSPExcelFP, IO.LSP_requestTemplateFP, SAM);

        Log(LogMsgType.INFO, "Starting " + this.Name + " at: " + DateTime.Now);
        Log(LogMsgType.INFO, "Aligning date for previous day...");
        // LSP_kpi.PutValueToLSPxmlRequestTemplate(IO.LSP_requestTemplateFP, LSP_kpi.KPIName);
        Log(LogMsgType.INFO, "Starting " + this.Name + " request...");
        if (ExecuteSOAP()) {
            bool isErrorWithCopy = false;
            bool isErrorWithDelete = false;
            FTP.MyFTP(Server.xml_outputFP, Paths.ResultFullPath, Paths.ResultFileName, this.KPIName, out isErrorWithCopy, out isErrorWithDelete);
            if (isErrorWithCopy == false) { //if FTP error LSP process aborted
                if (isErrorWithDelete == true) {
                    Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + Name);
                }
                var AttributesList = DataOperation.CreateDataTable(GetAttributes());
                FillDTByXMLResult(AttributesList);
                if (AttributesList.Rows.Count != 0) {
                    Log(LogMsgType.INFO, "Putting results to Excel");
                    if (ExportToExcel(AttributesList)) {
                        Log(LogMsgType.INFO, "Done with " + this.Name + " part");
                    }
                } else {
                    Log(LogMsgType.ERROR, this.Name + " Result file is empty");
                }
                Log(LogMsgType.INFO, "Ending LSP at: " + DateTime.Now);
            } else {
                Log(LogMsgType.ERROR, this.Name + " process aborted due to FTP download file failed " + DateTime.Now);
            }
        } else {
            Log(LogMsgType.FATAL, this.Name + " process aborted due to ExecuteSOAp method failed " + DateTime.Now);
        }
    }

}

public class LSP : Statistic {
    public LSP(StatisticPaths paths, Server server) : base(paths, server) { }
    public override int Id { get { return 2; } }
    public override KPIName KPIName { get { return KPIName.LSP; } }

    public override IEnumerable<string> GetAttributes() {
        List<string> Attributes = new List<string>();
        Attributes.Add("ElemStartTimeInPrograme");
        Attributes.Add("testedObject");
        Attributes.Add("minimumRoundTripTime");
        Attributes.Add("maximumRoundTripTime");
        Attributes.Add("averageRoundTripTime");
        Attributes.Add("packetsSent");
        Attributes.Add("responsesReceived");
        Attributes.Add("packetSize");
        Attributes.Add("packetsLost");
        Attributes.Add("lossPercentage");
        Attributes.Add("timeCaptured");
        Attributes.Add("timedout");

        return Attributes;
    }
}


public class CPU : Statistic {
    public CPU(StatisticPaths paths, Server server) : base(paths, server) { }
    public override int Id { get { return 3; } }
    public override KPIName KPIName { get { return KPIName.CPU; } }
}


public class Memory : Statistic {
    public Memory(StatisticPaths paths, Server server) : base(paths, server) { }
    public override int Id { get { return 4; } }
    public override KPIName KPIName { get { return KPIName.MEM; } }
}

static class Program {
    static void Main(string[] args) {
        Server SAM = null;

        //-- LSP Kpi part --  
        // var LSP_kpi = new LSP(LSP.ID, KPIName.LSP, IO.LSP_requestFN, IO.LSP_requestFP, IO.LSP_resultFN, IO.LSP_resultFP, IO.LSPExcelFN, IO.LSPExcelFP, IO.LSP_requestTemplateFP, SAM);
        // var MEM_kpi = new Memory(Memory.ID, KPIName.MEM, IO.Memory_requestFN, IO.Memory_requestFP, IO.Memory_resultFN, IO.Memory_resultFP, IO.MEMExcelFN, IO.MEMExcelFP, IO.Memory_requestTemplateFP, SAM);
        // var CPU_kpi = new CPU(CPU.ID, KPIName.CPU, IO.CPU_requestFN, IO.CPU_requestFP, IO.CPU_resultFN, IO.CPU_resultFP, IO.CPUExcelFN, IO.CPUExcelFP, IO.CPU_requestTemplateFP, SAM);

        new LSP(IO.GetPaths(KPIName.LSP), SAM).CallExecuteSoap();
        new Memory(IO.GetPaths(KPIName.MEM), SAM).CallExecuteSoap();
        new CPU(IO.GetPaths(KPIName.CPU), SAM).CallExecuteSoap();

    }
}



Judging from this, your classes seem pointless. It's hard to tell with all the global mess. You could just pass paths, type, and attributes and run all methods off of that.

Hope this helps.
Was This Post Helpful? 2
  • +
  • -

#8 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 18 September 2014 - 01:33 PM

thanks Bavgai i will check the code later. The target of that code is requesting some server for each kpi (send xmla soap requests by http protocol) and get the data after that by ftp - then put to db and excel files. Dont know how i could implement it other way as all kpis mostly doing same job thats why i created base class Statistic and all diffrent kpis inheriting from it. And most of those kpis using same methods. Thats why maybe its so simple its hard to implement other solution. Maybe you would have something that can be better way of implement that solution?

This post has been edited by nighttrain: 18 September 2014 - 01:43 PM

Was This Post Helpful? 0
  • +
  • -

#9 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 22 September 2014 - 08:58 AM

Baavgai just one more question. Imagine that i have additional class "FTP" which inside i got two functions which i need to execute for each statistic (lsp or cpu or memory) for that class i need fields which are partly already in Statistic class (Paths) - and some of them i need are inside Server which is also in Statistic constructor. I thinki can add additional field to Statistic constructor - FTP ftp just after StatisticPath and Server. But heres the question how can i implement that i mean where can i create FTP instance with all nesecary fields which are required for two methods inside FTP and then raise it according to what we already have in new LSP or new CPU... ?
Was This Post Helpful? 0
  • +
  • -

#10 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 22 September 2014 - 11:20 AM

For now, forget objects. I don't honestly see that you're currently using them in a meaningful way. Instead, think about configuration. Things like paths and all the other moving parts.

If you can see how OO would help, use it. However, you currently seem only confused by it; so don't use it.

How would I improve what I see? I'd strip out all the gratuitous classes and just get the thing to run. I'd organized into classes later, as needed.

e.g.
class Server {
    public string ServiceHttpAdress { get; }
    public string xml_outputFP { get; }
}

enum LogMsgType { ERROR, INFO, WARNING, FATAL }

class StatisticPaths {
    public string RequestFileName { get; set; }
    public string RequestFullPath { get; set; }
    public string ResultFileName { get; set; }
    public string ResultFullPath { get; set; }
    public string ExcelFileName { get; set; }
    public string ExcelFP { get; set; }
    public string RequestFileTemplateFullPath { get; set; }
    public StatisticPaths() { }
}

class MyClient {
    public enum KPI { LSP, LSPInventory, MEM, CPU };
    public enum FtpResult { Success, CopyError, DeleteError };

    private readonly Server server;
    private readonly IDictionary<KPI, StatisticPaths> allPaths;
    public MyClient(Server server, IDictionary<KPI, StatisticPaths> allPaths) {
        this.server = server;
        this.allPaths = allPaths;
    }

    public IEnumerable<string> GetAttributes(KPI kpi) {
        List<string> attrs = new List<string>();
        if (kpi == KPI.LSP) {
            attrs.Add("ElemStartTimeInPrograme");
            attrs.Add("testedObject");
            attrs.Add("minimumRoundTripTime");
            attrs.Add("maximumRoundTripTime");
            attrs.Add("averageRoundTripTime");
            attrs.Add("packetsSent");
            attrs.Add("responsesReceived");
            attrs.Add("packetSize");
            attrs.Add("packetsLost");
            attrs.Add("lossPercentage");
            attrs.Add("timeCaptured");
            attrs.Add("timedout");
        }
        return attrs;
    }

    public string LogDir { get; set; }

    //public static void MyFTP(string xml_outputFP, string ResultFullPath, string ResultFileName, KPIName kpiName, out bool isErrorWithCopy, out bool isErrorWithDelete) {
    public FtpResult Ftp(KPI kpi) {
        // your code here
        return FtpResult.Success;
    }
    public DataTable CreateDataTable(IEnumerable<string> attrs) { return null; }

    private void ProcessReponse(KPI kpi, WebResponse res) {
        if (kpi == KPI.LSPInventory) {
            using (var rd = new StreamReader(res.GetResponseStream())) {
                var xdoc = new XmlDocument();
                xdoc.LoadXml(rd.ReadToEnd());
                xdoc.Save(allPaths[kpi].ResultFullPath);
            }
        }
    }

    private void Log(LogMsgType t, string msg) { /* your code here */  }

    private DataTable FillDTByXMLResult(KPI kpi, DataTable dt) {
        /* your code here */
        return dt;
    }

    public bool ExportToExcel(DataTable dt) { return false; /* your code here */ }

    public bool ExecuteSOAP(KPI kpi) {
        var success = true;
        var paths = allPaths[kpi];
        try {
            var request = (HttpWebRequest)WebRequest.Create(server.ServiceHttpAdress);
            request.Headers.Add(@"SOAP:Action");
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept = "text/xml";
            request.Method = "POST";

            using (var fileRequestStream = File.OpenRead(paths.RequestFullPath)) {
                using (Stream webRequestStream = request.GetRequestStream()) {
                    fileRequestStream.CopyTo(webRequestStream);
                }
            }
            using (WebResponse response = request.GetResponse()) { ProcessReponse(kpi, response); }
        } catch (Exception ex) {
            success = false;
            Log(LogMsgType.ERROR, "inside ExecuteSOAP method for " + kpi + " error message: " + ex.ToString());
        }
        return success;
    }


    private void CallExecuteSoapSuccess(KPI kpi) {
        var name = kpi.ToString();
        var AttributesList = CreateDataTable(GetAttributes(kpi));
        FillDTByXMLResult(kpi, AttributesList);
        if (AttributesList.Rows.Count != 0) {
            Log(LogMsgType.INFO, "Putting results to Excel");
            if (ExportToExcel(AttributesList)) {
                Log(LogMsgType.INFO, "Done with " + name + " part");
            }
        } else {
            Log(LogMsgType.ERROR, name + " Result file is empty");
        }
        Log(LogMsgType.INFO, "Ending LSP at: " + DateTime.Now);
    }



    public void CallExecuteSoap(KPI kpi) {
        var name = kpi.ToString();
        Log(LogMsgType.INFO, "Starting " + name + " at: " + DateTime.Now);
        Log(LogMsgType.INFO, "Aligning date for previous day...");
        Log(LogMsgType.INFO, "Starting " + name + " request...");
        if (ExecuteSOAP(kpi)) {
            var ftpResult = Ftp(kpi);
            if (ftpResult == FtpResult.CopyError) {
                Log(LogMsgType.ERROR, name + " process aborted due to FTP download file failed " + DateTime.Now);
            } else if (ftpResult == FtpResult.DeleteError) {
                Log(LogMsgType.WARNING, "Couldnt delete file from FTP location for: " + name);
            } else {
                CallExecuteSoapSuccess(kpi);
            }
        } else {
            Log(LogMsgType.FATAL, name + " process aborted due to ExecuteSOAp method failed " + DateTime.Now);
        }
    }



}

static class Program {
    static void Main(string[] args) {
        var client = new MyClient(null, null); // these wouldn't be null
        foreach (var kpi in new MyClient.KPI[] { MyClient.KPI.LSP, MyClient.KPI.MEM, MyClient.KPI.CPU }) {
            client.CallExecuteSoap(kpi);
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#11 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 27 September 2014 - 08:41 AM

Hi baavgai,
I am still modyfing my application. Could you please take a look what i've done so far and give your opinion is it better right now than before?

P.S What do you think about FTP usage inside statistic class is it ok with my method FTP() to get new instance of FTP class in this way and use it in accordance to OOP?

Abstract class "Statistic" :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.IO;
using System.Xml;
using Excel = Microsoft.Office.Interop.Excel;

namespace CollectionLayer
{
    public abstract class Statistic
    {
        #region Properties
        private FTP Ftp { get; set; }
        private FtpResult ftpResult = new FtpResult();
        public virtual string Name { get { return this.KPIName.ToString(); } }
        public abstract int Id { get; }
        public abstract KPIName KPIName { get; }
        protected StatisticPaths Paths { get; set; }
        protected Server Server { get; set; }
        #endregion

        #region Constructor
        public Statistic(StatisticPaths paths)
        {
            this.Server = GetServer();
            this.Paths = paths;
            SetUnixTime();
        }
        #endregion

private Server GetServer()
        {
            return new Server(@"http://145.45.34.234:8080/ser", @"ftp://133.33.333.33/",
                      "login", "pass", @"/tmp/rty");
        }

private void SetUnixTime()
        {
            UnixTime.StartDate = DateTime.Today.AddDays(-1).AddSeconds(3);
            UnixTime.EndDate = DateTime.Today;
            UnixTime.UnixStartDate = UnixTime.ConvertDateTimeTo(UnixTime.StartDate);
            UnixTime.UnixEndDate = UnixTime.ConvertDateTimeTo(UnixTime.EndDate);
        }

        #region Get Attributes for each kpi
        public virtual IEnumerable<string> GetAttributes() { return new List<string>(); }
        #endregion

        #region Fill Datatable by retreived XML result file
        public abstract DataTable FillDTByXMLResult(DataTable dt);
        #endregion

        #region ExportToExcel
        public virtual bool ExportToExcel(DataTable dt)
        {
            bool success = false;
            try
            {
                if (dt == null || dt.Columns.Count == 0)
                    Logger.Log(LogMsgType.ERROR, "in ExportToExcel: Null or empty input table for " + this.Name, Paths.LogPath);
                // load excel, and create a new workbook
                Excel.Application excelApp = new Excel.Application();
                excelApp.Workbooks.Add();
                // single worksheet
                Excel._Worksheet workSheet = excelApp.ActiveSheet;
                // column headings
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    workSheet.Cells[1, (i + 1)] = dt.Columns[i].ColumnName;
                }
                // rows
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    // to do: format datetime values before printing
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        workSheet.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
                    }
                }
                // check fielpath
                if (Paths.ExcelFP != null && Paths.ExcelFP != "")
                {
                    try
                    {
                        string Filename = Paths.ExcelFP + String.Format("{0:yyyyMMdd}", DateTime.Now.AddDays(-1)) + "_" + Paths.ExcelFileName;
                        workSheet.SaveAs(Filename);
                        excelApp.Quit();
                        //MessageBox.Show("Excel file saved!");
                    }
                    catch (Exception ex)
                    {
                        success = true;
                        Logger.Log(LogMsgType.ERROR, "inside ExportToExcel method for " + this.Name + " error message: " + ex.ToString(), IO.LogDir);
                    }
                }
                else  // no filepath is given
                {
                    excelApp.Visible = true;
                }
            }
            catch (Exception ex)
            {
                success = true;
                Logger.Log(LogMsgType.ERROR, "inside ExportToExcel method for " + this.Name + " error message: " + ex.ToString(), IO.LogDir);
            }
            return success;
        }
        #endregion
        #region Execute SOAP
        public virtual bool ExecuteSOAP()
        {
            var success = true;
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(Server.ServiceHttpAdress);
                request.Headers.Add(@"SOAP:Action");
                request.ContentType = "text/xml;charset=\"utf-8\"";
                request.Accept = "text/xml";
                request.Method = "POST";

                using (var fileRequestStream = File.OpenRead(Paths.RequestFullPath))
                {
                    using (Stream webRequestStream = request.GetRequestStream())
                    {
                        fileRequestStream.CopyTo(webRequestStream);
                    }
                }

                using (WebResponse response = request.GetResponse())
                {
                    if (KPIName == KPIName.LSPInventory)
                    {
                        using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                        {
                            var xdoc = new XmlDocument();
                            xdoc.LoadXml(rd.ReadToEnd());
                            xdoc.Save(Paths.ResultFullPath);
                            xdoc = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                Logger.Log(LogMsgType.ERROR, "inside ExecuteSOAP method for " + KPIName + " error message: " + ex.ToString(), Paths.LogPath);
            }
            return success;
        }
        #endregion

        #region Call Execute SOAP
        public virtual void CallExecuteSoap()
        {
            Logger.Log(LogMsgType.INFO, "Starting " + this.Name + " at: " + DateTime.Now, Paths.LogPath);
            Logger.Log(LogMsgType.INFO, "Aligning date for previous day...", Paths.LogPath);
            PutValueToLSPxmlRequestTemplate();
            Logger.Log(LogMsgType.INFO, "Starting " + this.Name + " request...", Paths.LogPath);
            if (ExecuteSOAP())
            {
                ftpResult = FTP();
                if (ftpresult.Download == FtpResultTypes.DownloadOk) {
                    var AttributesList = DataOperation.CreateDataTable(GetAttributes());
                    FillDTByXMLResult(AttributesList);
                    if (AttributesList.Rows.Count != 0)
                    {
                        Logger.Log(LogMsgType.INFO, "Putting results to Excel", Paths.LogPath);
                        if (!ExportToExcel(AttributesList))
                        {
                            Logger.Log(LogMsgType.INFO, "Done with " + this.Name + " part", Paths.LogPath);
                        }
                    }
                    else
                    {
                        Logger.Log(LogMsgType.ERROR, this.Name + " Result file is empty", Paths.LogPath);
                    }
                    Logger.Log(LogMsgType.INFO, "Ending LSP at: " + DateTime.Now, Paths.LogPath);
                }
                else
                {
                    Logger.Log(LogMsgType.ERROR, this.Name + " process aborted due to FTP download file failed " + DateTime.Now, Paths.LogPath);
                }
            }
            else
            {
                Logger.Log(LogMsgType.FATAL, this.Name + " process aborted due to ExecuteSOAp method failed " + DateTime.Now, Paths.LogPath);
            }
        }
        #endregion

        #region FTP - take and execute
        public virtual FtpResult FTP()
        {
            Ftp = new FTP(Server.FtpIP, Server.FtpUser, Server.FtpPassword, Server.xml_outputFP + Paths.ResultFileName, Paths.ResultFullPath,
                            Paths.ResultFileName, KPIName, Paths.LogPath);
            return Ftp.FtpProcess();
        }
        #endregion

        #region PutValueToLSPxmlRequestTemplate
        public virtual void PutValueToLSPxmlRequestTemplate()
        {
            XmlReader xmlFile = null;
            int Col = new int();
            int Row = new int();
            int TableSeq = new int();
            // Open the predefined xml file 
            xmlFile = XmlReader.Create(Paths.RequestFileTemplateFullPath, new XmlReaderSettings());
            // Load data from xml file into memory
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFile);
            // Fill in the "first" and "second" objects
            ds.Tables[7].Rows[Row][1] = UnixTime.UnixStartDate;
            ds.Tables[7].Rows[Row][2] = UnixTime.UnixEndDate;
            //Save the data in a dataset as XML to a file 
            ds.WriteXml(Paths.RequestFullPath);
        }
        #endregion

    }
}



Class "StatisticPaths" :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public class StatisticPaths
    {
        public string RequestFileName { get; set; }
        public string RequestFullPath { get; set; }
        public string ResultFileName { get; set; }
        public string ResultFullPath { get; set; }
        public string ExcelFileName { get; set; }
        public string ExcelFP { get; set; }
        public string RequestFileTemplateFullPath { get; set; }
        public string LogPath { get; set; }
        public string OutputFullPath { get; set; }
        public StatisticPaths() { }
        public StatisticPaths(string requestFileName,
                        string requestFullPath, string resultFileName,
                        string resultFullPath, string excelFileName,
                        string excelFP, string requestFileTemplateFullPath, string logPath, string outputFullPath)
        {
            RequestFileName = requestFileName;
            RequestFullPath = requestFullPath;
            ResultFileName = resultFileName;
            ResultFullPath = resultFullPath;
            ExcelFileName = excelFileName;
            ExcelFP = excelFP;
            RequestFileTemplateFullPath = requestFileTemplateFullPath;
            LogPath = logPath;
            OutputFullPath = outputFullPath;
        }

    }
}



Class "Server" :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public class Server
    {
        public string ServiceHttpAdress { get; set; }
        public string FtpIP { get; set; }
        public string FtpUser { get; set; }
        public string FtpPassword { get; set; }
        public string xml_outputFP { get; set; }

        public Server(string ServiceHttpAdress, string FtpIP, string FtpUser, string FtpPassword, string xml_outputFP)
        {
            this.ServiceHttpAdress = ServiceHttpAdress;
            this.FtpIP = FtpIP;
            this.FtpUser = FtpUser;
            this.FtpPassword = FtpPassword;
            this.xml_outputFP = xml_outputFP;
        }
    }
}



enum KPIName:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public enum KPIName { LSP = 1, LSPInventory, MEM, CPU }
}



class IO:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public static class IO
    {
        public static  StatisticPaths statisticPaths { get; set; }
        public static string LogDir { get; set; }
        public static StatisticPaths GetPaths(KPIName kpi)
        {
            string RootDir = @"D:\Project";
            string LogDir = RootDir + @"\log.txt";
            string LSPRootDir = RootDir + @"\LSP";
            string LSPScriptDir = LSPRootDir + @"\Scripts\";
            string LSPOutputDir = LSPRootDir + @"\CurrentOutput\";
            string LSPHistoricalDir = LSPRootDir + @"\Historical\";
            string LSPResultDir = LSPRootDir + @"\Result\";

            switch (kpi)
            {
                case KPIName.LSP:

                    string LSP_requestTemplateFN = "LSP_requestTemplate.xml";
                    string LSP_requestTemplateFP = LSPScriptDir + LSP_requestTemplateFN;
                    string LSP_requestFN = "LSP_request.xml";
                    string LSP_resultFN = "LSP_result.xml";
                    string LSP_requestFP = LSPOutputDir + LSP_requestFN;
                    string LSP_resultFP = LSPOutputDir + LSP_resultFN;
                    string LSPExcelFN = "LSP.xlsx";
                    string LSPExcelFP = LSPResultDir;

                    statisticPaths = new StatisticPaths(LSP_requestFN, LSP_requestFP, LSP_resultFN,
                        LSP_resultFP, LSPExcelFN, LSPExcelFP, LSP_requestTemplateFP, LogDir, LSPOutputDir);

                    break;

                case KPIName.LSPInventory:

                    string LSPGetInv_requestFN = "GetInventory.xml";
                    string LSPGetInv_resultFN = "GetInventory_result.xml";
                    string LSPGetInv_requestFP = LSPScriptDir + LSPGetInv_requestFN;
                    string LSPGetInv_resultFP = LSPOutputDir + LSPGetInv_resultFN;
                    string LSPGetInvExcelFN = "LSPGetInv.xlsx";
                    string LSPGetInvExcelFP = LSPResultDir;
                    string LSPGetInv_requestTemplateFP = LSPScriptDir + LSPGetInv_requestFN;

                    statisticPaths = new StatisticPaths(LSPGetInv_resultFN, LSPGetInv_requestFP, LSPGetInv_resultFN,
               LSPGetInv_resultFP, LSPGetInvExcelFN, LSPGetInvExcelFP, LSPGetInv_requestTemplateFP, LogDir, LSPOutputDir);

                    break;

                case KPIName.MEM:

                    string MEMRootDir = RootDir + @"\Memory";
                    string MEMScriptDir = MEMRootDir + @"\Scripts\";
                    string MEMOutputDir = MEMRootDir + @"\CurrentOutput\";
                    string MEMHistoricalDir = MEMRootDir + @"\Historical\";
                    string MEMResultDir = MEMRootDir + @"\Result\";
                    string Memory_requestTemplateFN = "Memory_requestTemplate.xml";
                    string Memory_requestTemplateFP = MEMScriptDir + Memory_requestTemplateFN;
                    string Memory_requestFN = "Memory_request.xml";
                    string Memory_resultFN = "Memory_result.xml";
                    string Memory_requestFP = MEMOutputDir + Memory_requestFN;
                    string Memory_resultFP = MEMOutputDir + Memory_resultFN;
                    string MEMExcelFN = "Memory.xlsx";
                    string MEMExcelFP = MEMResultDir;

                    statisticPaths =  new StatisticPaths(Memory_requestFN, Memory_requestFP, Memory_resultFN,
                Memory_resultFP, MEMExcelFN, MEMExcelFP, Memory_requestTemplateFP, LogDir, MEMOutputDir);

                    break;

                case KPIName.CPU:

                    string CPURootDir = RootDir + @"\CPU";
                    string CPUScriptDir = CPURootDir + @"\Scripts\";
                    string CPUOutputDir = CPURootDir + @"\CurrentOutput\";
                    string CPUHistoricalDir = CPURootDir + @"\Historical\";
                    string CPUResultDir = CPURootDir + @"\Result\";
                    string CPU_requestTemplateFN = "CPU_requestTemplate.xml";
                    string CPU_requestTemplateFP = CPUScriptDir + CPU_requestTemplateFN;
                    string CPU_requestFN = "CPU_request.xml";
                    string CPU_resultFN = "CPU_result.xml";
                    string CPU_requestFP = CPUOutputDir + CPU_requestFN;
                    string CPU_resultFP = CPUOutputDir + CPU_resultFN;

                    string CPUExcelFN = "CPU.xlsx";
                    string CPUExcelFP = CPUResultDir;

                    statisticPaths =  new StatisticPaths(CPU_requestFN, CPU_requestFP, CPU_resultFN,
            CPU_resultFP, CPUExcelFN, CPUExcelFP, CPU_requestTemplateFP, LogDir, CPUOutputDir);

                    break;

                default:
                    break;
            }
            return statisticPaths;
        }
    }
}



Class FTP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace CollectionLayer
{
    public class FTP
    {
        private string Host { get; set; }
        private string User { get; set; }
        private string Pass { get; set; }
        private string XML_Output { get; set; }
        private string CopyresultTo { get; set; }
        private string ResultFileName { get; set; }
        private KPIName KpiName { get; set; }
        private string LogPath { get; set; }
        private string RemoteFileFP { get; set; }
        private FtpWebRequest ftpRequest = null;
        private FtpWebResponse ftpResponse = null;
        private Stream ftpStream = null;
        private int bufferSize = 2048;
        private FtpResult _ftpResult;

        /* Construct Object */
        public FTP(string host, string user, string pass, string xml_outputFP, string copyTo, string resultFN, KPIName kpiname, string logPath)
        {
            Host = host;
            User = user;
            Pass = pass;
            XML_Output = xml_outputFP;
            CopyresultTo = copyTo;
            ResultFileName = resultFN;
            KpiName = kpiname;
            LogPath = logPath;
            RemoteFileFP = XML_Output + ResultFileName;
        }

        public FtpResult FtpProcess()
        {
            FTP ftpClient = null;
            _ftpResult = new FtpResult();
            try
            {
                try
                {
                    Logger.Log(LogMsgType.INFO, "Taking data via ftp", LogPath);
                    _ftpResult.Download = ftpClient.download();
                    /* Delete a File */
                }
                catch (Exception ex)
                {
                    Logger.Log(LogMsgType.ERROR, "exception inside MyFTP-ftpClient.download part for " + KpiName + " error message: " + ex.ToString(), LogPath);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogMsgType.ERROR, "inside MyFTP method for " + KpiName + " error message: " + ex.ToString(), LogPath);
            }
            finally
            {
                ftpClient = null;
            }
            return _ftpResult;
        }

        /* Download File */
        public FtpResultTypes download()
        {
            var dlresult = new FtpResultTypes();
            dlresult = FtpResultTypes.DownloadOk;
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Host + "/" + RemoteFileFP);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(User, Pass);
                /* When in doubt, use these options */
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                /* Get the FTP Server's Response Stream */
                ftpStream = ftpResponse.GetResponseStream();
                /* Open a File Stream to Write the Downloaded File */
                FileStream localFileStream = new FileStream(CopyresultTo, FileMode.Create);
                /* Buffer for the Downloaded Data */
                byte[] byteBuffer = new byte[bufferSize];
                int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
                try
                {
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                    }
                }
                catch (Exception ex)
                {
                    dlresult = FtpResultTypes.DownloadError;
                    Logger.Log(LogMsgType.ERROR, "inside FTP download method for " + KpiName + " error message: " + ex.ToString(), LogPath);
                }
                /* Resource Cleanup */
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                dlresult = FtpResultTypes.DownloadError;
                Logger.Log(LogMsgType.ERROR, "inside FTP download method for " + KpiName + " error message: " + ex.ToString(), LogPath);
            }
            return dlresult;
        }



class "FTPResult" :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public class FtpResult
    {
        public FtpResultTypes Download { get; set; }
        public FtpResultTypes Delete { get; set; }
    }
}



class FtpResultTypes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionLayer
{
    public enum FtpResultTypes
    {
        Done,
        DownloadError,
        DownloadOk,
        DeleteError,
        DeleteOk
    }
}



class "DataOperation":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace CollectionLayer
{
    public static class DataOperation
    {
        public static DataTable dt { get; set; }
        public static DataTable CreateDataTable(IEnumerable<string> columns)
        {
            var dt = new DataTable();
            dt.Clear();
            foreach (string item in columns)
            {
                dt.Columns.Add(item);
            }
            return dt;
        }
    }
}



class: "LSP":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;

namespace CollectionLayer
{
    public class LSP : Statistic
    {
        public LSP(StatisticPaths paths) : base(paths) { }
        public override int Id { get { return 2; } }
        public override KPIName KPIName { get { return KPIName.LSP; } }

        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            Attributes.Add("something1");
            Attributes.Add("something2");

            return Attributes;
        }

        public override DataTable FillDTByXMLResult(DataTable dt)
        {

            XmlReader xmlFile = null;
            int Col = new int();
            int Row = new int();
            int TableSeq = new int();
            // Open the predefined xml file 
            xmlFile = XmlReader.Create(Paths.ResultFullPath, new XmlReaderSettings());
            // Load data from xml file into memory
            var ds = new DataSet();
            ds.ReadXml(xmlFile);

            if (ds.Tables.Count != 0)
            {
                for (Row = 0; Row <= ds.Tables[0].Rows.Count - 1; Row++)
                {
                    DataRow dr = dt.NewRow();
                    dr["something1"] = DateTime.Now.ToString();
                    dr["something2"] = ds.Tables[0].Rows[Row][51];
                    dt.Rows.Add(dr);

                    DateTime something1= DateTime.Now;
                    string something2= Convert.ToString(ds.Tables[0].Rows[Row][51]);

                    DAL.InsertLSP(something1, something2);

                }
            }
            return dt;
        }
    }
}



class "Memory":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;

namespace CollectionLayer
{
    public class Memory : Statistic
    {
        public Memory(StatisticPaths paths) : base(paths) { }
        public override int Id { get { return 4; } }
        public override KPIName KPIName { get { return KPIName.MEM; } }

        public override DataTable FillDTByXMLResult(DataTable dt)
        {
            XmlReader xmlFile = null;
            int Col = new int();
            int Row = new int();
            int TableSeq = new int();
            // Open the predefined xml file 
            xmlFile = XmlReader.Create(Paths.ResultFullPath, new XmlReaderSettings());
            // Load data from xml file into memory
            var ds = new DataSet();
            ds.ReadXml(xmlFile);

            if (ds.Tables.Count != 0)
            {
                for (Row = 0; Row <= ds.Tables[0].Rows.Count - 1; Row++)
                {
                    DataRow dr = dt.NewRow();
                    dr["something10"] = DateTime.Now.ToString();
                    dr["something20"] = ds.Tables[0].Rows[Row][0];
                    dr["something30"] = ds.Tables[0].Rows[Row][0];
                    dt.Rows.Add(dr);

                    DateTime something10= DateTime.Now;
                    long something20 = Convert.ToInt64(ds.Tables[0].Rows[Row][0]);
                    DateTime something30 = UnixTime.ConvertTimestampTo((Convert.ToInt64(ds.Tables[0].Rows[Row][1])));

                    DAL.InsertMEM(something10,something20,something30);
                }

            }
            return dt;
        }

        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            Attributes.Add("something10");
            Attributes.Add("something20");
            Attributes.Add("something30");

            return Attributes;
        }
    }
}



class "LSPGetInventory" :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;

namespace CollectionLayer
{
	public class LSPGetInventoryClass : Statistic
	{
		public LSPGetInventoryClass(StatisticPaths paths) : base(paths) { }
		public override int Id { get { return 1; } }
		public override KPIName KPIName { get { return KPIName.LSPInventory; } }
		public override DataTable FillDTByXMLResult(DataTable dt)
		{
			XmlReader xmlFile = null;
			int Col = new int();
			int Row = new int();
			int TableSeq = new int();
			// Open the predefined xml file 
			xmlFile = XmlReader.Create(Paths.ResultFullPath, new XmlReaderSettings());
			// Load data from xml file into memory
			var ds = new DataSet();
			ds.ReadXml(xmlFile);

			if (ds.Tables.Count != 0)
			{
				for (Row = 0; Row <= ds.Tables[5].Rows.Count - 1; Row++)
				{

					DataRow dr = dt.NewRow();
					dr["SOME1"] = DateTime.Now.ToString();
					dr["SOME2"] = ds.Tables[5].Rows[Row][0];
					dt.Rows.Add(dr);

					DateTime SOME1= DateTime.Now;
					string SOME2= Convert.ToString(ds.Tables[5].Rows[Row][0]);
					DAL.InsertLSPGetInv(SOME1,SOME2);
				}

			}
			return dt;
		}
        public override void CallExecuteSoap()
        {
            Logger.Log(LogMsgType.INFO, " --------------------------------------------------------------- ", Paths.LogPath);
            Logger.Log(LogMsgType.INFO, "Starting program at: " + DateTime.Now, Paths.LogPath);
            Logger.Log(LogMsgType.INFO, "Starting " + this.Name + " request", Paths.LogPath);
            if (ExecuteSOAP())
            {
                    var AttributesList = DataOperation.CreateDataTable(GetAttributes());
                    DAL.DeleteLSPInventory();
                    FillDTByXMLResult(AttributesList);
                    if (AttributesList.Rows.Count != 0)
                    {
                        Logger.Log(LogMsgType.INFO, "Putting results to Excel", Paths.LogPath);
                        if (!ExportToExcel(AttributesList))
                        {
                            Logger.Log(LogMsgType.INFO, "Done with " + this.Name + " part", Paths.LogPath);
                        }
                    }
                    else
                    {
                        Logger.Log(LogMsgType.ERROR, this.Name + " Result file is empty", Paths.LogPath);
                    }
                    Logger.Log(LogMsgType.INFO, "Ending LSP at: " + DateTime.Now, Paths.LogPath);
            }
            else
            {
                Logger.Log(LogMsgType.FATAL, this.Name + " process aborted due to ExecuteSOAp method failed " + DateTime.Now, Paths.LogPath);
            }
        }

        public override IEnumerable<string> GetAttributes()
        {
            List<string> Attributes = new List<string>();
            Attributes.Add("SOME1");
            Attributes.Add("SOME2");
            return Attributes;
        }

	}
}



and class Program:
    class Program
    {
        static void Main(string[] args)
        {
            //Execute kpi's
            new LSPGetInventoryClass(IO.GetPaths(KPIName.LSPInventory)).CallExecuteSoap();
            new LSP(IO.GetPaths(KPIName.LSP)).CallExecuteSoap();
            new Memory(IO.GetPaths(KPIName.MEM)).CallExecuteSoap();
            new CPU(IO.GetPaths(KPIName.CPU)).CallExecuteSoap();
        }
    }


This post has been edited by nighttrain: 27 September 2014 - 11:20 AM

Was This Post Helpful? 0
  • +
  • -

#12 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 29 September 2014 - 05:48 AM

I'm really not sure what you're after. As I said before:

View Postbaavgai, on 22 September 2014 - 02:20 PM, said:

How would I improve what I see? I'd strip out all the gratuitous classes and just get the thing to run. I'd organized into classes later, as needed.


Your FTP class doesn't even work a presented:
public FtpResult FtpProcess() {
    FTP ftpClient = null; // so, this is null
    _ftpResult = new FtpResult(); // is there a point to this?
    try {
        try {
            Logger.Log(LogMsgType.INFO, "Taking data via ftp", LogPath); // stop passing LogPath around
            // ftpClient is still null
            // This should have a fiery death
            _ftpResult.Download = ftpClient.download();



That switch with the paths seems epically redundant and complex. If I were to do that, I'd probably do something like:
class StatisticPaths {
    public string RequestFileName { get { return Name + "_request.xml"; } }
    public string RequestFullPath { get { return OutputFullPath + RequestFileName; } }
    public string ResultFileName { get { return Name + "_result.xml"; } }
    public string ResultFullPath { get { return OutputFullPath + ResultFileName; } }
    public string ExcelFileName { get { return Name + ".xlsx"; } }
    public string ExcelFP { get { return RootDir + @"\Result\"; } }
    public string RequestFileTemplateFullPath { get { return RootDir + @"\Scripts\" + Name + "_requestTemplate.xml" } }
    public string OutputFullPath { get; private set; }
    public KPIName Kpi { get; private set; }
    private string RootDir { get; private set; }
    public string Name { get; private set; }
    private StatisticPaths() { }
    public StatisticPaths(string rootDir, KPIName kpi) {
        Name = "NA";
        if (Kpi == KPIName.LSP) { Name = "LSP"; } 
        else if (Kpi == KPIName.LSPInventory) { Name = "LSPInventory"; } 
        else if (Kpi == KPIName.MEM) { Name = "Memory"; } 
        else if (Kpi == KPIName.CPU) { Name = "CPU"; }
        this.RootDir = rootDir + "\\" + Name;
    }
}



However, all your static, and the resulting global instances, are just asking for pain.

For a logger, I'd try something like:
enum LogMsgType { ERROR, INFO, WARNING, FATAL }

public class Logger {
    public class LoggerEx : Exception {
        public LogMsgType MsgType { get; private set; }
        public LoggerEx(LogMsgType t, string msg)
            : base(msg) {
            this.MsgType = t;
        }
        public LoggerEx(LogMsgType t, string msg, Exception ex)
            : base(msg, ex) {
            this.MsgType = t;
        }
    }
    public Logger(string logDir) { this.LogDir = logDir; }
    public string LogDir { get; private set; }
    public void Log(LogMsgType t, string msg) {
        // your code here
    }
}



Note the custom exception. Because, honestly, you should be throwing instead of logging on some of those.

Your FTP is super busy. Why custom classes for results? Why store the world in an FTP class? As a class it makes sense to have something store basically side and login info; but that's about it.

I'd do something like:
public class FTP {
    private string Host { get; private set; }
    private string User { get; private set; }
    private string Pass { get; private set; }
    private const int BufferSize = 2048;
    public FTP(string host, string user, string pass) {
        Host = host;
        User = user;
        Pass = pass;
    }

    private FtpWebRequest GetFtpWebRequest(string src) {
        var ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Host + "/" + src); // RemoteFileFP);
        ftpRequest.Credentials = new NetworkCredential(User, Pass);
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
        return ftpRequest;
    }

    public void Download(string src, string dst) {
        try {
            var ftpRequest = GetFtpWebRequest(src);
            var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            var ftpStream = ftpResponse.GetResponseStream();
            FileStream localFileStream = new FileStream(dst, FileMode.Create);
            byte[] byteBuffer = new byte[BufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
            try {
                while (bytesRead > 0) {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
                }
            } catch (Exception ex) {
                throw new Logger.LoggerEx(LogMsgType.ERROR, "inside MyFTP method", ex);
            } finally {
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
            }
        } catch (Logger.LoggerEx iex) {
            throw iex;
        } catch (Exception ex) {
            throw new Logger.LoggerEx(LogMsgType.ERROR, "inside FTP download method", ex);
        }
    }
}



For the program itself, I'd use a structure like:
class Program {
    private readonly string serviceHttpAdress, rootDir;
    private readonly FTP ftp;
    private readonly Logger logger;

    public Program(string serviceHttpAdress, FTP ftp, Logger logger, string rootDir) {
        this.serviceHttpAdress = serviceHttpAdress;
        this.ftp = ftp;
        this.logger = logger;
        this.rootDir = rootDir;
    }

    private void Log(LogMsgType t, string msg) {
        this.logger.Log(t, msg);
    }

    // WTF do you need this, btw?
    // private DataTable CreateDataTable(IEnumerable<string> columns) {

    private void ExportToExcel(KPIName kpi) {
        // your code here
    }

    private void ProcessResult(string filename) {
        // your code here
    }

    private void ExecuteSoap(string src, string dst) {
        // your code here
    }

    private string GetSoapUrl(KPIName kpi) {
        // your code here
        return null;
    }

    private string GetResponsePath(KPIName kpi) {
        // your code here
        return null;
    }

    private void ExecuteSoap(KPIName kpi) {
        // your code here
    }

    public void Run(KPIName kpi) {
        try {
            var responsePath = GetResponsePath(kpi);
            ExecuteSoap(GetSoapUrl(kpi), responsePath);
            // your code here
        } catch (Logger.LoggerEx iex) {
            Log(iex.MsgType, iex.Message);
        } catch (Exception ex) {
            Log(LogMsgType.ERROR, "Unknown error for " + kpi + ex.Message);
        }

    }


    public void Run() {
        Run(KPIName.LSPInventory);
        Run(KPIName.LSP);
        Run(KPIName.MEM);
        Run(KPIName.CPU);
    }

    static void Main(string[] args) {
        // public Program(string serviceHttpAdress, FTP ftp, Logger logger, string rootDir) 
        var pgm = new Program(
            "http://145.45.34.234:8080/ser",
            new FTP(@"ftp://133.33.333.33/", "login", "pass"),
            new Logger(@"C:\\temp"), 
            "");
        pgm.Run();
    }
}



Get rid off all the static. Store fewer variables in instances. Pass more variables to methods. Code only what you need, get rid of the extra.

Again, make it work for one type. Then two. Then, stop and consider what you can generalize and if you need a class for it.

Ultimately, there is no one way to do any program. You only need worry about style points after it runs.

Good luck.
Was This Post Helpful? 1
  • +
  • -

#13 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 29 September 2014 - 09:17 AM

According to first - it will work check again how i implemented that:

in class FTP i have provate field:
 private FtpResult _ftpResult;


and method:
public FtpResult FtpProcess()
	        {
	            FTP ftpClient = null; // <-----------forget about this is wrong putted
	            _ftpResult = new FtpResult();
	            try
	            {
	                try
	                {
	                    Logger.Log(LogMsgType.INFO, "Taking data via ftp", LogPath);
	                    _ftpResult.Download = ftpClient.download();



and inside Statistic class:
 private FTP Ftp { get; set; }
        private FtpResult ftpResult = new FtpResult();   //is it also ok to do like this?


and method:
   public virtual FtpResult FTP()
	        {
	            Ftp = new FTP(Server.FtpIP, Server.FtpUser, Server.FtpPassword, Server.xml_outputFP + Paths.ResultFileName, Paths.ResultFullPath,
	                            Paths.ResultFileName, KPIName, Paths.LogPath);
	            return Ftp.FtpProcess();
	        }


and usage inside CallExecuteSoap:
 ftpResult = FTP();
	                if (ftpresult.Download == FtpResultTypes.DownloadOk) {



My main question was is this way correct according to OOP can i implement things to be worked like this i mean mainly about get instance of in this case FTP - inside Statistic class and use it like this? Can i call new instance of FTP this way inside other class to be used within?

Similar would be as i did also inside Statistic class:
	private Server GetServer()
	        {
	            return new Server(@"http://145.45.34.234:8080/ser", @"ftp://133.33.333.33/",
	                      "login", "pass", @"/tmp/rty");
	        }


and then within same Statistic class create it inside cosntructor:
public Statistic(StatisticPaths paths)
	        {
	            this.Server = GetServer(); <---------------------
	            this.Paths = paths;
	            SetUnixTime();
	        }


This post has been edited by nighttrain: 29 September 2014 - 09:20 AM

Was This Post Helpful? 0
  • +
  • -

#14 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7505
  • View blog
  • Posts: 15,553
  • Joined: 16-October 07

Re: Determinate type of object and pass it through method

Posted 29 September 2014 - 12:09 PM

View Postnighttrain, on 29 September 2014 - 12:17 PM, said:

My main question was is this way correct according to OOP


Ok... static, or class level, methods essentially aren't OOP; they're just procedures in class clothing. Worse, class variables can be globals, a more mortal code sin. This guy did a pretty good write up on static: http://simpleprogram...will-shock-you/

View Postnighttrain, on 29 September 2014 - 12:17 PM, said:

can i implement things to be worked like this i mean mainly about get instance of in this case FTP - inside Statistic class and use it like this?


You're the programmer. If it works, you can do it. Should you do it? I've already stated several times than you require very few of the classes you have and that they are ill conceived. I honestly don't know what more I can say on the matter.

View Postnighttrain, on 29 September 2014 - 12:17 PM, said:

Similar would be as i did also inside Statistic class:

Your Statistic class is becoming a God object. Sure, you can do it. However, if you are going to squeeze all the code you can into it, does it really have meaning as a class anymore?

View Postnighttrain, on 29 September 2014 - 12:17 PM, said:

public Statistic(StatisticPaths paths)
	        {
	            this.Server = GetServer(); <---------------------
	            this.Paths = paths;



Yes on paths, no on server. Again, stop using so many global variables. If you pass server, then fine. If you have a GetServer method, then why would you want to store an instance in the object when you can just call it as needed? This is kind of the worst of the both.
Was This Post Helpful? 1
  • +
  • -

#15 nighttrain   User is offline

  • D.I.C Regular

Reputation: 8
  • View blog
  • Posts: 487
  • Joined: 22-September 10

Re: Determinate type of object and pass it through method

Posted 29 September 2014 - 12:29 PM

you know whats my problem lets say i know from meritorical point of view how classes should looks like and so on but i got always problems when it comes to stick it together. For instance when i prepare couple classes e.g FTP, StatisticPath, Logger, Server and so on. Then when it comes to stick it together i mean how to call each other i am confused how to pass they instances to each other then i am most of time "loosing" with accessing variables and so on thats why i am asking when to use diresctly new CLASS() how to pass parameters with no duplication or use already existing once and when to pass instancs of other classes directly to constructor or maybe call it from some method etc... For instance now i wanted to add StatisticPaths based on your code to Program class what i did is:
  class Program
    {
        private readonly string serviceHttpAdress, rootDir;
        private readonly FTP ftp;
        private readonly Logger logger;
        private readonly Server server;
        private StatisticPaths statisticPaths;                        // <---------------------------- added



and then still inside Program class:
 private void GetKpiPaths(KPIName kpi)                   
        {
            statisticPaths = new StatisticPaths(rootDir, kpi);          // <---------------------------added create statisticPaths for specific KPI
        }


and then i could use statisticPaths variable inside other methods within Program class is this for instance correct ? For instance (still within Program class:
  public virtual bool ExportToExcel(DataTable dt, KPIName kpi)
        {
      ...
string Filename = statisticPaths.ExcelFP; //<------------------------------------------------------------- here like this
....
        }





Let me thiunk about again on this program and i will come with something hope better.

This post has been edited by nighttrain: 29 September 2014 - 12:39 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2