Exemplo n.º 1
0
 public ServerCommand(CommandDispatcher dispatcher, string name, string sourceCodeScript)
 {
     _Dispatcher    = dispatcher;
     _Name          = name;
     _CommandSyntax = sourceCodeScript;
     _result        = new UAReturn();
 }
 public ServerCommand(CommandDispatcher dispatcher, string name, string sourceCodeScript)
 {
     _Dispatcher = dispatcher;
     _Name = name;
     _CommandSyntax = sourceCodeScript;
     _result = new UAReturn();
 }
        public UAReturn UABinomial(ServerDataSource dataSource, List<string> vars, double p, string alternative, double confidenceLevel, bool descriptives, bool quartiles, int missing)
        {
            UAReturn result = new UAReturn();

            if (string.IsNullOrEmpty(alternative)) alternative = "two.sided";

            result.CommandString = string.Format(PrototypeBinomial, toRCollection(vars), p, alternative, confidenceLevel, descriptives, quartiles, dataSource.FileName, missing);

            result.Data = EvaluateToObjectXml(result.CommandString);

            result.Success = true;

            return result;
        }
 public override UAReturn Execute(string commandString)
 {
     UAReturn result = new UAReturn();
     try
     {
         _journal.WriteLine(commandString);//06Jul2015
         result.Data = dispatcher.EvaluateToXml(commandString);
         result.Success = true;
     }
     catch (Exception ex)
     {
         logService.WriteToLogLevel("Could not evaluate : <" + commandString + " > ", LogLevelEnum.Error);
     }
     return result;
 }
 public override UAReturn GetRodbcTables(string fname) //27Jan2014
 {
     bool isxlsx = fname.ToLower().EndsWith(".xlsx") ? true : false;
     UAReturn result = new UAReturn();
     result.SimpleTypeData = GetODBCTableList(fname, isxlsx);
     return result;
 }
 public override UAReturn DataSourceReadCell(ServerDataSource dataSource, int row, int col)
 {
     UAReturn result = new UAReturn();
     //R is now 0 Based
     row++; col++;
     result.Data = dispatcher.EvaluateToXml(RCommandStrings.GetDataFrameCellValue(dataSource, row, col));
     return result;
 }
        public UAReturn RefreshDataset(ServerDataSource dataSource)//04Mar2015 refresh on new row added by compute
        {
            UAReturn result = new UAReturn() { Success = false };
            if (true)//dispatcher.GetErrorText().Contains(BSky.Statistics.R.RService.RCommandReturn.Success))
            {
                //Get matrix columns
                string subCommand = RCommandStrings.GetDataFrameColumnNames(dataSource);

                object colnames = dispatcher.EvaluateToObject(subCommand, false);
                //if colnames are null. Because we were unable to open the dataset because of any reason.
                if (colnames == null)
                {
                    CloseDataset(dataSource);
                    result.Success = false;
                    result.Error = "Error Opening Dataset.";
                    return result;
                }

                //if colnames are duplicate then we dont load the dataset and show error message. Also we clean R
                if (isDuplicateColnames(colnames))
                {
                    CloseDataset(dataSource);
                    result.Success = false;
                    result.Error = "Dulicate Column Names in Dataset";
                    return result;
                }
                if (colnames != null)
                {
                    string[] columnNames = null;//var columnNames = new string[] { "aaa", "bbb" };
                    Type retType = colnames.GetType();
                    if (retType.Name == "String[]")//for multicols
                    {
                        columnNames = (String[])colnames;
                    }
                    else if (retType.Name == "String")//for single col
                    {
                        columnNames = new string[1];
                        columnNames[0] = (String)colnames;
                    }
                    else
                    {
                        return new UAReturn() { Success = false };
                    }

                    //maximum factors allowed
                    object maxf = (getMaxFactors(dataSource));
                    //sym = maxf as SymbolicExpression;

                    int mxf;//sym.AsInteger()[0];
                    bool parseSuccess = int.TryParse(maxf.ToString(), out mxf);
                    dataSource.MaxFactors = parseSuccess ? mxf : 40; //Hardcoded Default max factor count   //int.Parse(maxf.ToString());

                    dataSource.Variables.Clear();
                    int rowcount = GetRowCount(dataSource);//31Dec2014
                    int columnindex = 1;
                    SymbolicExpression symex = null;
                    foreach (object s in columnNames)
                    {
    
                        symex = dispatcher.EvaluateToSymExp(string.Format("UAgetColProperties(dataSetNameOrIndex='{0}', colNameOrIndex={1}, asClass=FALSE)", dataSource.Name, columnindex));
                        GenericVector gv = symex.AsList();

                        string colclass = dispatcher.RawEvaluateGetstring(string.Format("class({0}[[{1}]])", dataSource.Name, columnindex));//,true);
                        if (colclass == null)
                        {
                            colclass = "";
                        }

                        string lab = (gv[2] != null && gv[2].AsCharacter() != null && gv[2].AsCharacter()[0] != null) ? gv[2].AsCharacter()[0].ToString() : string.Empty;
                        DataColumnTypeEnum dtyp = (gv[1] != null && gv[1].AsCharacter() != null && gv[1].AsCharacter()[0] != null) ? GetCovertedDataType(gv[1].AsCharacter()[0].ToString()) : DataColumnTypeEnum.Character;
                        string mistyp = (gv[5] != null && gv[5].AsCharacter() != null && gv[5].AsCharacter()[0] != null) ? gv[5].AsCharacter()[0].ToString() : string.Empty;
                        

                        DataSourceVariable var = new DataSourceVariable()
                        {
                            Name = s.ToString(),
                            Label = lab,
                            DataType = dtyp,
                            DataClass = colclass,
                            Measure = DataColumnMeasureEnum.Scale,
                            Width = 4,
                            Decimals = 0,
                            Columns = 8,
                            MissType = mistyp,
                            RowCount = rowcount //GetVectorLength(dataSource, s.ToString())

                        };

                        if (symex != null)
                        {

                            //if (gv.Length == 1)
                            {
                                ////Set Measure
                                switch (gv[7].AsCharacter()[0].ToString())
                                {
                                    case "factor":
                                        var.Measure = DataColumnMeasureEnum.Nominal;
                                        break;

                                    case "ordinal":
                                        var.Measure = DataColumnMeasureEnum.Ordinal;
                                        break;

                                    default:
                                        if(var.DataType == DataColumnTypeEnum.Character) //02Jun2015 treating "character" type as Nominal in UI. In R its not factor
                                        {
                                            var.Measure = DataColumnMeasureEnum.Nominal;
                                        }
                                        else
                                        var.Measure = DataColumnMeasureEnum.Scale;
                                        break;
                                }

                                CharacterVector cv = gv[3].AsCharacter();
                                string[] vals = cv.ToArray();
                                if (vals != null && vals.Length > 0)
                                {
                                    if (vals.Length > 1)
                                    {
                                        var.Values.AddRange(vals);//more than 1 strings
                                    }
                                    else if (vals[0].Trim().Length > 0)
                                    {
                                        var.Values.Add(vals[0]);//1 string
                                    }
                                }

                                if (!(var.MissType == "none"))
                                {
                                    CharacterVector cvv = gv[3].AsCharacter();
                                    string[] misvals = cvv.ToArray();
                                    if (misvals != null && misvals.Length > 0)
                                    {
                                        if (misvals.Length > 1)
                                        {
                                            var.Missing.AddRange(misvals);//more than 1 strings
                                        }
                                        else if (misvals[0].Trim().Length > 0)
                                        {
                                            var.Missing.Add(misvals[0]);//1 string
                                        }
                                    }
                                }
                                else
                                {
                                    string misval = "none";
                                    var.Missing.Add(misval);
                                }

                            }
                        }

                        if (dataSource.Extension == "rdata")// if filetype is RDATA.
                        {
                            if (gv[9].AsCharacter() != null && gv[9].AsCharacter()[0].ToString() != "-2146826288")
                                var.Width = Int32.Parse(gv[9].AsCharacter()[0].ToString());

                            if (gv[10].AsCharacter() != null && gv[10].AsCharacter()[0].ToString() != "-2146826288")
                                var.Decimals = Int32.Parse(gv[10].AsCharacter()[0].ToString());

                            if (gv[11].AsCharacter() != null && gv[11].AsCharacter()[0].ToString() != "-2146826288")
                                var.Columns = UInt32.Parse(gv[11].AsCharacter()[0].ToString());
                        }

                        try
                        {
                            ////////// Alignment  ////////////
                            //logService.WriteToLogLevel("Get-Set Alignment start : " + s.ToString(), LogLevelEnum.Info);
                            string align = gv[6].AsCharacter()[0].ToString();
                            if (align == "-2146826288") align = "Left";
                            DataColumnAlignmentEnum alignVal = (DataColumnAlignmentEnum)Enum.Parse(typeof(DataColumnAlignmentEnum), align);
                            if (Enum.IsDefined(typeof(DataColumnAlignmentEnum), alignVal))
                                var.Alignment = alignVal;
                            else
                                var.Alignment = DataColumnAlignmentEnum.Left;

                            var.Role = DataColumnRole.Input;// Role is not used, I guess, so 'if' is commented above
                            //logService.WriteToLogLevel("Get-Set Alignment start : " + s.ToString(), LogLevelEnum.Info);
                        }
                        catch (ArgumentException)
                        {
                            logService.WriteToLogLevel("Not a member of enum(Alignment) ", LogLevelEnum.Error);
                        }

                        dataSource.Variables.Add(var);
                        columnindex++;
                        dataSource.RowCount = Math.Max(dataSource.RowCount, dataSource.Variables.Last().RowCount);
                    }

                    result.Datasource = dataSource;
                    result.Success = true;

                    this.DataSources.Add(dataSource);
                }
                else // no need of this 'else' unless you want to put custom error message in result
                {
                }
            }
            return result;
        }
        public override List<FactorMap> getColFactormap(string colName, ServerDataSource dataSource)
        {
            UAReturn result = new UAReturn() { Success = false };
            List<FactorMap>
                factormap = getColumnFmap(colName, dataSource);

            return factormap;
            //
        }
 public UAReturn saveDataset(ServerDataSource dataSource)//, string fname, string ftype, string datasetNameOrIndex)//Anil #4
 {
     UAReturn result = new UAReturn() { Success = false };
     result.CommandString = RCommandStrings.SaveDatasetToFile(dataSource);//fname,ftype,datasetNameOrIndex);
     if (result.CommandString != null)
         this.Evaluate(result.CommandString);
     return result;
 }
 //06Dec2013 show installed packages
 public override UAReturn ShowInstalledPackages()
 {
     UAReturn result = new UAReturn() { Success = false };
     object obj = rpm.GetInstalledPackages();
     if (obj != null)
     {
         result.SimpleTypeData = obj;
         result.Success = true;
     }
     //result.CommandString = command;// "Show Installed Packages";
     return result;
 }
 // Returns string[] by converting SimplDataType object that holds results
 public string[] GetUAReturnStringResult(UAReturn rlst)
 {
     string[] strarr = null;
     if (rlst != null && rlst.Success && rlst.SimpleTypeData != null)
     {
         if (rlst.SimpleTypeData.GetType().Name.Equals("String"))
         {
             strarr = new string[1];
             strarr[0] = rlst.SimpleTypeData as string;
         }
         else if (rlst.SimpleTypeData.GetType().Name.Equals("String[]"))
         {
             strarr = rlst.SimpleTypeData as string[];
         }
     }
     return strarr;
 }
Exemplo n.º 12
0
        ///14Jun2013 For new R framework. We need XML doc for errors as well as additional result value
        public UAReturn EvaluateToUAReturn(string commandString)
        {
            UAReturn returnRecults = new UAReturn();
            returnRecults.CommandString = commandString;
            XmlDocument returnErrWarn;

            try
            {
                //16Apr2013///
                bool batchcommand = false;
                if (!batchcommand)
                    this._RServer.Evaluate("tmp<-" + commandString); // executing R Command with no left-hand var
                else
                    this._RServer.Evaluate(commandString);///16Apr2013 for commands like a<-somfun(..) and b = some expr. left hand var exists.
            }
            catch (Exception e)
            {
                string errm = "R.NET Error Msg not implemented";// this._RServer.GetErrorText();
                logService.WriteToLogLevel("Could not execute: < " + commandString + " >", LogLevelEnum.Error);
            }
            if (false)//this._RServer.GetErrorText() != RCommandReturn.Success)
            {
                returnErrWarn = null;

            }
            else if (!Conversions.ToBoolean(this._RServer.Evaluate("is.null(tmp)").AsLogical()[0]))
            {
                returnErrWarn = ParseToXmlDocument("tmp");
                ///here returnErrWarn will contain DOM. Having Error/Warn and Return results
            }
            else
            {
                returnErrWarn = null;
            }

            returnRecults.Data = returnErrWarn;
            returnRecults.SimpleTypeData = returnVal;// "Put results here. Should be used for RCommandStrings and nothing else.
            returnVal = null; // resetting so that old value does not get assigned to result of urrent command under execution.
            return returnRecults;
        }
Exemplo n.º 13
0
 public void Execute()
 {
     Debug.Assert(this.Validate());
     _result = this.Dispatcher.Execute(this);
 }
 //Uninstall multiple packages.
 public UAReturn UninstallMultiPakckage(string[] packagenames)
 {
     UAReturn res = new UAReturn() { Success = false };
     UAReturn tmp = null;//11May2014 for temporary return value
     StringBuilder sb = new StringBuilder("");
     StringBuilder comm = new StringBuilder(""); //11May2014 for storing multiple commands in single place
     foreach (string pkgname in packagenames)
     {
         tmp = UninstallPackage(pkgname.Trim());
         if (tmp != null)
         {
             if (tmp.CommandString != null) //11May2014
             {
                 if (comm.Length > 1) comm.Append("\n"); // if there is already something then only add new line
                 comm.Append(tmp.CommandString);
             }
             if (tmp.Error != null && tmp.Error.Length > 1) // if there is some error msg
             {
                 sb.Append(tmp.Error);
             }
         }
     }
     res.Success = sb.Length > 0 ? false : true;
     res.Error = sb.ToString();
     res.CommandString = comm.ToString();//11May2014
     return res;
 }
        public override object ExecuteR(ServerCommand Command, bool hasReturn, bool hasUAReturn)
        {

            _journal.WriteLine(Command.CommandSyntax);

            UAReturn result = new UAReturn();
            result.Success = true;
            result.Data = null;
            object o = dispatcher.SyntaxEditorEvaluateToObject(Command.CommandSyntax, hasReturn, hasUAReturn);

            return o;
        }
        //Install BlueSky R pacakge if its not already installed. Dont install on each launch. But check in each launch if installation is needed or not
        private UAReturn CheckAndInstallBlueSkyRPackage()
        {
            bool isinstalled = false;// package already installed
            bool islatestinstalled = true; //already installed package is the latest version.
            UAReturn res = new UAReturn() { Success = false };

            //Get BlueSky R .zip package names and location
            string BSkyMainPackagePath = string.Empty;//Main pacakge fullpathfilename.Assuming in future BlueSky R pacakge may break down in multiple R pacakges.
            string[] RpackageFullPathFilenames = null;//for all BlueSky*.zip package names
            string parentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace('\\', '/') + "/R Packages/BlueSky R Package(s)";
            if (Directory.Exists(parentDir))
            {
                //find all the .zip file in RPacakges directory
                RpackageFullPathFilenames = Directory.GetFiles(parentDir.Replace('/', '\\'), "BlueSky*.zip");//only look for packages with names "BlueSky*.zip"
                BSkyMainPackagePath = Array.Find(RpackageFullPathFilenames, element => element.Contains("BlueSky_"));
            }

            //Now check if BlueSky R pacakge is already installed.
            isinstalled = IsRPacakgeInstalled("BlueSky");
            if (isinstalled) //if BlueSky R package is already installed then check the version
            {
                string existingVersion = rpm.GetInstalledPacakgeVersion("BlueSky");
                string newVersion = string.Empty;
                string pkgname = rpm.GetPackageNameFromZip(BSkyMainPackagePath, out newVersion);
                if (rpm.CompareVersion(newVersion, existingVersion) == 1) //new version in BlueSky app and old is already installed
                {
                    islatestinstalled = false; //latest not already installed.
                }
            }

            //Install BlueSky R package(s) if not already installed OR if installed one is not the latest
            //To Update BlueSky R pacakge there is different menu options.
            if (!isinstalled || !islatestinstalled) 
            {
                logService.WriteToLogLevel("Install BlueSky R pacakge if its not already installed or not latest:", LogLevelEnum.Info);
                //string parentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace('\\', '/') + "/RPackages/BlueSky R Package(s)";
                if (Directory.Exists(parentDir))
                {
                    //find all the .zip file in RPacakges directory
                    //string[] RpackageFullPathFilenames = Directory.GetFiles(parentDir, "BlueSky*.zip");//only look for packages with names "BlueSky*.zip"
                    res = rpm.InstallMultiPackageFromZip(RpackageFullPathFilenames, true, true);
                }
                else
                {
                    res.Error = "Could not find BlueSky R package(s). Please install them by going to Tools > Package > Update BlueSky package from zip (Restart App)";
                }
            }
            return res;
        }
        public UAReturn OpenEmptyDataset(ServerDataSource dataSource)//03Jan2014
        {
            string commstr = string.Empty;
            UAReturn result = new UAReturn() { Success = false };

            result.CommandString = RCommandStrings.LoadEmptyDataSource(dataSource);
            commstr = result.CommandString;
            result = this.Evaluate(commstr);

            UAReturn result2 = RefreshNewDataset(dataSource);//26Mar2013 to avoid code redundancy.(code here was separated out to a function)
            result.Datasource = result2.Datasource;
            result.Success = result2.Success;
            result.CommandString = commstr;//21Oct2013
            return result;
        }
 public UAReturn Datasetclose(ServerDataSource dataSource)//Anil #4
 {
     UAReturn result = new UAReturn() { Success = false };
     result.CommandString = RCommandStrings.closeDataset(dataSource);
     if (result.CommandString != null)
         this.Evaluate(result.CommandString);
     return result;
 }
 //06Dec2013 show currently loaded packages
 public override UAReturn ShowLoadedPackages()
 {
     UAReturn result = new UAReturn() { Success = false };
     object obj = rpm.GetCurrentlyLoadedPackages();
     if (obj != null)
     {
         result.SimpleTypeData = obj;
         result.Success = true;
     }
     return result;
 }
        public UAReturn LoadDataFrame(ServerDataSource dataSource, string dframename) //13Feb2014 
        {
            string commstr = string.Empty;
            UAReturn result = new UAReturn() { Success = false };

            result.CommandString = RCommandStrings.LoadDataframe(dataSource, dframename);
            commstr = result.CommandString;
            result = this.Evaluate(commstr);
            if (result.Data != null)
            {
                UAReturn result2 = RefreshNewDataset(dataSource);//26Mar2013 to avoid code redundancy.(code here was separated out to a function)
                result.Datasource = result2.Datasource;
                result.Success = result2.Success;
                result.Error = result2.Error;
                result.CommandString = commstr;//21Oct2013
            }
            return result;
        }
        //06Dec2013 for loading custom package
        public override UAReturn LoadLocalPackage(string package)
        {
            string command = string.Format("library({0})", package);

            UAReturn result = new UAReturn() { Success = false };
            //Load Package
            if (!dispatcher.IsLoaded(package))
            {
                result.Success = true;
                this.EvaluateNoReturn(command);
                result.CommandString = command;//  "Load Package";
            }
            return result;
        }
        public UAReturn RefreshDataset_old(ServerDataSource dataSource)//25Mar2013 refresh on new row added by compute
        {
            UAReturn result = new UAReturn() { Success = false };
            if (true)//dispatcher.GetErrorText().Contains(BSky.Statistics.R.RService.RCommandReturn.Success))
            {
                logService.WriteToLogLevel("GetColnames Start:", LogLevelEnum.Info);
                //Get matrix columns
                string subCommand = RCommandStrings.GetDataFrameColumnNames(dataSource);

                object colnames = dispatcher.EvaluateToObject(subCommand, false);
                string[] columnNames = null;//var columnNames = new string[] { "aaa", "bbb" };
                Type retType = colnames.GetType();
                if (retType.Name == "String[]")//for multicols
                {
                    columnNames = (String[])colnames;
                }
                else if (retType.Name == "String")//for single col
                {
                    columnNames = new string[1];
                    columnNames[0] = (String)colnames;
                }
                else
                {
                    return new UAReturn() { Success = false };
                }

                logService.WriteToLogLevel("GetColnames End", LogLevelEnum.Info);

                logService.WriteToLogLevel("Get Max factor start", LogLevelEnum.Info);
                //maximum factors allowed
                object maxf = (getMaxFactors(dataSource));


                int mxf;//sym.AsInteger()[0];
                bool parseSuccess = int.TryParse(maxf.ToString(), out mxf);
                dataSource.MaxFactors = parseSuccess ? mxf : 40; //Hardcoded Default max factor count   //int.Parse(maxf.ToString());
                logService.WriteToLogLevel("Get Max factor end", LogLevelEnum.Info);

                dataSource.Variables.Clear();
                int rowcount = GetRowCount(dataSource);//31Dec2014
                int columnindex = 1;
                foreach (object s in columnNames)
                {
                    logService.WriteToLogLevel("Get Col Prop start : " + s.ToString(), LogLevelEnum.Info);
                    object resobj = GetColProp(dataSource, s.ToString()).SimpleTypeData;
                    object[] cprops = (object[])resobj;
                    logService.WriteToLogLevel("Get Col Prop end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Set Col Prop start : " + s.ToString(), LogLevelEnum.Info);
                    DataSourceVariable var = new DataSourceVariable()
                    {
                        Name = s.ToString(),
                        Label = cprops[2].ToString(),
                        DataType = GetCovertedDataType(cprops[1].ToString()),
                        Measure = DataColumnMeasureEnum.Scale,
                        Width = 4,
                        Decimals = 0,
                        Columns = 8,
                        MissType = cprops[5].ToString(),
                        RowCount = rowcount //GetVectorLength(dataSource, s.ToString())
                        //factormapList = new List<FactorMap>()//17Apr2014
                    };
                    logService.WriteToLogLevel("Set Col Prop end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set Col factors start : " + s.ToString(), LogLevelEnum.Info);
                    //uadatasets$lst$ added by Anil in following two
                    bool isfactors = (bool)dispatcher.EvaluateToObject(string.Format("is.factor({0}[,{1}])", dataSource.Name, columnindex), false);//is.factor(uadatasets$lst${0}[,{1}])
                    if (isfactors)
                    {    //(DataColumnMeasureEnum)Enum.Parse(typeof(DataColumnMeasureEnum), GetMeasure(dataSource, s.ToString()));
                        bool isOrdered = (bool)dispatcher.EvaluateToObject(string.Format("is.ordered({0}[,{1}])", dataSource.Name, columnindex), false);//is.ordered(uadatasets$lst${0}[,{1}])
                        if (isOrdered)
                            var.Measure = DataColumnMeasureEnum.Ordinal;
                        else
                            var.Measure = DataColumnMeasureEnum.Nominal; // default is set in above para which will be overwritten in this line if its factor type
                        //reading all levels/factors
                        object tempO = (object)GetFactorValues(dataSource, s.ToString()).SimpleTypeData;
                        if (tempO != null)
                        {
                            if (tempO.GetType().Name.Equals("String[]"))//tempO.GetType().IsArray)
                            {
                                string[] vals = tempO as string[];
                                var.Values.AddRange(vals);//adding all values to list
                            }
                            else if (tempO.GetType().Name.Equals("String"))
                            {
                                string vals = tempO as string;
                                var.Values.Add(vals);//adding all values to list
                            }
                            else
                            {
                                //some other unexpected type was returned in tempO.
                                //can print an error message here.
                                string[] charfactors = (tempO as SymbolicExpression).AsCharacter().ToArray();
                                var.Values.AddRange(charfactors);//adding all values to list
                            }
                        }
                    }
                    logService.WriteToLogLevel("Get-Set Col factors end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set Col Missing start : " + s.ToString(), LogLevelEnum.Info);
                    if (!(var.MissType == "none"))
                    {
                        object tempObj = (object)GetMissingValues(dataSource, s.ToString()).SimpleTypeData;
                        if (tempObj != null)
                        {
                            double[] misval;
                            if (tempObj.GetType().Name.Equals("Double[]"))// (tempObj.GetType().IsArray)
                            {
                                misval = tempObj as double[];
                                foreach (double mv in misval)
                                    var.Missing.Add(mv.ToString());
                            }
                            else if (tempObj.GetType().Name.Equals("Double"))
                            {
                                double misvalue = (double)tempObj;
                                var.Missing.Add(misvalue.ToString());
                            }
                            else
                            {
                                //some other unexpected type was returned in tempO.
                                //can print an error message here.

                                var.Missing.Add("");//adding blank
                            }
                        }
                    }
                    else
                    {
                        string misval = "none";
                        var.Missing.Add(misval);
                    }
                    logService.WriteToLogLevel("Get-Set Col Missing end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set others start : " + s.ToString(), LogLevelEnum.Info);
                    if (dataSource.Extension == "rdata")// if filetype is RDATA.
                    {
                        if (cprops[9].ToString() != "-2146826288")
                            var.Width = Int32.Parse(cprops[9].ToString());

                        if (cprops[10].ToString() != "-2146826288")
                            var.Decimals = Int32.Parse(cprops[10].ToString());

                        if (cprops[11].ToString() != "-2146826288")
                            var.Columns = UInt32.Parse(cprops[11].ToString());
                    }
                    try
                    {
                        ////////// Alignment  ////////////
                        if (cprops[6].ToString() == "-2146826288") cprops[6] = "Left";
                        DataColumnAlignmentEnum alignVal = (DataColumnAlignmentEnum)Enum.Parse(typeof(DataColumnAlignmentEnum), cprops[6].ToString());
                        if (Enum.IsDefined(typeof(DataColumnAlignmentEnum), alignVal))
                            var.Alignment = alignVal;
                        else
                            var.Alignment = DataColumnAlignmentEnum.Left;

                        var.Role = DataColumnRole.Input;// Role is not used, I guess, so 'if' is commented above
                    }
                    catch (ArgumentException)
                    {
                        //Console.WriteLine("Not a member of the enumeration.");
                        logService.WriteToLogLevel("Not a member of enum(Alignment) ", LogLevelEnum.Error);
                    }
                    logService.WriteToLogLevel("Get-Set others end : " + s.ToString(), LogLevelEnum.Info);

                    dataSource.Variables.Add(var);
                    columnindex++;
                    dataSource.RowCount = Math.Max(dataSource.RowCount, dataSource.Variables.Last().RowCount);
                }

                result.Datasource = dataSource;
                result.Success = true;

                this.DataSources.Add(dataSource);
            }
            return result;
        }
 //06Dec2013 for loading package from list
 public override UAReturn LoadPackageFromList(string[] packagenames)
 {
     
     UAReturn result = new UAReturn() { Success = false };
     result = rpm.LoadMultiplePackages(packagenames, true);
     return result;
 }
        public override UAReturn DataSourceReadRows(ServerDataSource dataSource, int start, int end)
        {
            UAReturn result = new UAReturn();
            start++; end++;

            List<object> data = new List<object>();
            for (int i = start; i < end; i++)
            {
                data.Add(dispatcher.EvaluateToObject(RCommandStrings.GetDataFrameRowValues(dataSource, i), false));
            }
            return result;
        }
 //06Dec2013 for unloading custom package
 public override UAReturn UnloadPackages(string[] packagenames)
 {
     
     UAReturn result = new UAReturn() { Success = false };
     result = rpm.UnLoadMultiPackage(packagenames);
     return result;
 }
 public override UAReturn DataSourceReadRow(ServerDataSource dataSource, int row)//23Jan2014 Read a Row at once
 {
     UAReturn result = new UAReturn();
     //R is now 0 Based
     row++;
     try
     {
         string commnd = RCommandStrings.GetDataFrameRowValues(dataSource, row);
         //result.Data = dispatcher.EvaluateToXml(commnd);
         result.SimpleTypeData = dispatcher.GetRow(commnd);//DAtaset[index,]
     }
     catch (Exception ex)
     {
         logService.WriteToLogLevel("Error in row : " + row + " " + ex.Message, LogLevelEnum.Error);
     }
     return result;
 }
 //06Dec2013 for uninstalling custom package
 public override UAReturn UninstallPackages(string[] packagenames)
 {
    
     UAReturn result = new UAReturn() { Success = false };
     result = rpm.UninstallMultiPakckage(packagenames);
     return result;
 }
        public UAReturn UAOneSample(ServerDataSource dataSource, List<string> vars, double mu, double confidenceLevel, int missing)
        {
            UAReturn result = new UAReturn();

            result.CommandString = string.Format(PrototypeOneSample, toRCollection(vars), mu, confidenceLevel, dataSource.FileName, missing);

            result.Data = EvaluateToObjectXml(result.CommandString);

            result.Success = true;

            return result;
        }
        public UAReturn OpenDataset(ServerDataSource dataSource, string sheetname)
        {
            string commstr = string.Empty;
            UAReturn result = new UAReturn() { Success = false };
            result.CommandString = RCommandStrings.LoadDataSource(dataSource, sheetname);
            commstr = result.CommandString;

            //07Jul2015 if file type is not supported commstr will be empty(may be null)
            //No need to process further as file type is not supported
            if (commstr == null || commstr.Trim().Length == 0) 
            {                               
                logService.WriteToLogLevel("Unable to open file: " , LogLevelEnum.Error);
                result.Datasource = null;
                result.Success = false;
                result.CommandString = commstr;//21Oct2013
                result.Error = "Error opening file: File format not supported (or corrupt file or duplicate column names).";
                return result;
            }

            result = this.Evaluate(commstr);//Execute command, if supported file type is passed.

            if (result.Data == null)//this checks finds if R was able to successfully open the dataset.
            {
                logService.WriteToLogLevel("Unable to open file: " + commstr, LogLevelEnum.Error);
                result.Datasource = null;
                result.Success = false;
                result.CommandString = commstr;//21Oct2013
                return result;
            }
            else if (result.Data != null)//07Jul2015
            {
                OutputHelper.AnalyticsData.Result = result;
                string[,] errwarn = OutputHelper.GetBSkyErrorsWarning(1, "normal"); //for getting errors and warning from BSkyReturnStruct.
                if (errwarn != null)
                {
                    string[] RErrors = new string[errwarn.GetLength(0)];
                    for (int i = 0; i < errwarn.GetLength(0); i++)
                    {
                        RErrors[i] = errwarn[i, 2];
                    }
                    result.Error = string.Join(". ", RErrors);
                }
            }

            //07Jul2015 IF Error occurred the nno need to do further processing. Push this error message to top layers so that
            // it can be dispalyed in UI (outpuwindow or message box)
            if(result!=null && result.Error!=null && result.Error.Trim().Length>0 && 
                (result.Error.Trim().Contains("R Err Msg : ") || result.Error.Trim().ToLower().Contains("error")) )
            {
                return result; //Return from here. No further processing (like RefreshDataset).
            }


            logService.WriteToLogLevel("Before RefreshDataset:", LogLevelEnum.Info);
            UAReturn result2 = RefreshDataset(dataSource);//26Mar2013 to avoid code redundancy.(code here was separated out to a function)
            logService.WriteToLogLevel("After RefreshDataset:", LogLevelEnum.Info);

            result.Datasource = result2.Datasource;
            result.Success = result2.Success;
            result.Error = result2.Error;
            result.CommandString = commstr;//21Oct2013
            return result;
        }
        public override UAReturn Execute(ServerCommand Command)
        {

            _journal.WriteLine(Command.CommandSyntax);

            UAReturn result = new UAReturn();
            result.Success = true;
            result.Data = dispatcher.EvaluateToXml(Command.CommandSyntax);

            return result;
        }
        private UAReturn Evaluate(string commandString)
        {
            _journal.WriteLine(commandString);
            //08Jun2013 return dispatcher.EvaluateToString(commandString); //returns string

            //08jun2013
            UAReturn result = new UAReturn();
            result.Success = true;
            result.Data = dispatcher.EvaluateToXml(commandString);
            return result;
        }
        private UAReturn LoadPackage()
        {
            UAReturn result = new UAReturn() { Success = false };

            foreach (string package in RPackages)
            {
                if (isNewPackage) UnloadPackage(package);
                //Load Package
                if (!dispatcher.IsLoaded(package))
                {
                    string parentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace('\\', '/') + "/R Packages";

                    this.EvaluateNoReturn("library(tools)");

                    string command = string.Format("write_PACKAGES('{0}')", parentDir);
                    this.EvaluateNoReturn(command);
                    this.EvaluateNoReturn(string.Format("install.packages('{0}', repos=NULL, contriburl='file:///{1}')", package, parentDir));

                    result.Success = true;
                    this.EvaluateNoReturn(string.Format("library({0})", package));
                }

            }


            return result;
        }
 public void JustLogCommandDoNotExecute()//16Aug2016
 {
     Debug.Assert(this.Validate());
     _result = this.Dispatcher.DontExecuteJustLogCommand(this.CommandSyntax);
 }