예제 #1
0
        public JObject ToJson()
        {
            var json = new JObject
            {
                ["ToolName"]             = ToolName,
                ["ToolVersion"]          = ToolVersion,
                ["ExecutionType"]        = ExecutionType.ToString(),
                ["LciDirectory"]         = LciDirectory,
                ["OutputPath"]           = OutputPath,
                ["ExitCode"]             = ExitCode,
                ["LciFilesFound"]        = new JArray(LciFiles),
                ["EnglishAssemblyCount"] = EnglishAssemblies.Count,
                ["EnglishAssemblies"]    = new JArray(EnglishAssemblies.Select(m => m.ToJson())),
                ["Results"] = new JArray(Results.Select(r => r.ToJson()))
            };

            switch (ExecutionType)
            {
            case ExecutionType.Vsix:
                json["VsixPath"]           = VsixPath;
                json["VsixExtractionPath"] = VsixExtractionPath;
                break;

            case ExecutionType.Artifacts:
                json["ArtifactsPath"] = ArtifactsPath;
                break;

            case ExecutionType.Files:
                json["InputFiles"] = new JArray(InputFiles);
                break;
            }

            return(json);
        }
예제 #2
0
 void IPersistable.Save(SettingsStorage storage)
 {
     storage.SetValue("DataType", DataType.GetTypeName(false));
     storage.SetValue("ExecutionType", ExecutionType.ToString());
     storage.SetValue("Fields", _fields.Select(f => f.Save()).ToArray());
     storage.SetValue("Settings", _settings.Save());
 }
예제 #3
0
        static void Main(string[] args)
        {
            try
            {
                log.Debug("Sabre Flight Search Handler Started.");

                if (args.Length < 1)
                {
                    throw new Exception("Event Handler must received an argument which is execution type.");
                }

                executionType = (ExecutionType)Enum.Parse(typeof(ExecutionType), args[0].ToString(), true);
                log.Debug("Execution Type: " + executionType.ToString());

                if (executionType == ExecutionType.FlightSearch)
                {
                    List <FlightSearchCondition> flightSearchConditions = db.FlightSearchConditions.Where(x => x.IsActive && DateTime.Now > x.NextRunDate).ToList();
                    foreach (FlightSearchCondition f in flightSearchConditions)
                    {
                        ProcessFlightConditions(f);
                    }

                    int batchPerRun = 10;
                    int.TryParse(Core.GetAppSettingValueEnhanced("BatchPerRun").ToString(), out batchPerRun);

                    List <FlightSearchBatch> flightSearchBatchs = db.FlightSearchBatches.Where(x => x.IsActive).Take(batchPerRun).ToList();
                    foreach (FlightSearchBatch f in flightSearchBatchs)
                    {
                        SabreFlightSearch(f);
                    }
                }
                else if (executionType == ExecutionType.GenerateReport)
                {
                    if (args.Length != 2)
                    {
                        log.Debug("GenerateReport execution type must have 2nd parameter which is Batch ID");
                    }
                    else
                    {
                        int batchid = 0;
                        int.TryParse(args[1], out batchid);

                        FlightSearchBatch batch = db.FlightSearchBatches.Where(x => x.BatchID == batchid).FirstOrDefault();
                        GenerateReport(batch);
                    }
                }

                log.Debug("Sabre Flight Search Handler Process Completed.");
            }
            catch (Exception ex)
            {
                SendErrorMail(ex.ToString());
                log.Error("Unable to complete the Sabre Flight Search Handler process.", ex);
            }
        }
예제 #4
0
        private List <MethodInfo> GetExecutionMethods(Type testType, ExecutionType executionType)
        {
            List <MethodInfo> methods = new List <MethodInfo>();

            Type executionAttribute = null;

            switch (executionType)
            {
            case ExecutionType.PreHost:
                executionAttribute = typeof(VsIdePreHostExecutionMethod);
                break;

            case ExecutionType.PostHost:
                executionAttribute = typeof(VsIdePostHostExecutionMethod);
                break;

            default:
                throw new ArgumentException("Unknown Execution Type.");
            }

            foreach (var m in testType.GetMethods())
            {
                bool hasCustomAttribute = m.GetCustomAttributes(executionAttribute, true).Length >= 1;

                if (hasCustomAttribute &&
                    !m.IsAbstract &&
                    m.IsStatic &&
                    m.GetParameters().Length == 0)
                {
                    methods.Add(m);
                }
                else if (hasCustomAttribute)
                {
                    HostProcessErrorHandler(
                        String.Format("Method {0} is attributed with {1} but cannot be run Pre/Post Host. "
                                      + "Methods must be Static and have no parameters."
                                      , m.ToString()
                                      , executionType.ToString())
                        , TestOutcome.Warning
                        , false);
                }
            }

            return(methods);
        }
예제 #5
0
        static void Main(string[] args)
        {
            try
            {
                log.Debug("Email Queue Handler Started.");

                if (args.Length != 1)
                {
                    throw new Exception("Event Handler must received an argument which is execution type.");
                }

                executionType = (ExecutionType)Enum.Parse(typeof(ExecutionType), args[0].ToString(), true);
                log.Debug("Execution Type: " + executionType.ToString());

                //dbADO.SetConnection(ConfigurationManager.ConnectionStrings["CorpBookingADO"].ConnectionString);

                //Code for Testing
                //[email protected]
                //CommonServiceController.InsertEmailQueue("", "*****@*****.**", "*****@*****.**", "*****@*****.**", "",
                //    "Testing", Core.getMailTemplate("temporarypassword", null), null, true);
                //byte[] bytes1 = System.IO.File.ReadAllBytes(@"C:\WLAN_1_Driver.log");
                //byte[] bytes2 = System.IO.File.ReadAllBytes(@"C:\mydll\capicom.zip");
                //List<Attachment> a = new List<Attachment>();
                //a.Add(new Attachment(new MemoryStream(bytes1), "1.log"));
                //a.Add(new Attachment(new MemoryStream(bytes2), "2.zip"));
                //CommonServiceController.InsertEmailQueue("", "*****@*****.**", "*****@*****.**", "*****@*****.**", "",
                //    "This is a testing email Testing", Core.getMailTemplate("temporarypassword", null), a, true);

                if (executionType == ExecutionType.ProcessEmailQueue)
                {
                    ProcessEmailQueue();
                }

                log.Debug("Email Queue Handler Process Completed.");
            }
            catch (Exception ex)
            {
                SendErrorMail(ex.ToString());
                log.Error("Unable to complete the Email Queue Handler process.", ex);
            }
        }
예제 #6
0
        static void Main(string[] args)
        {
            try
            {
                log.Debug("Email Handler Started.");

                var emailLists = db.EmailMarketingQueues;
                foreach (var list in emailLists)
                {
                    ExecutionType executionType = ExecutionType.undefined;
                    Enum.TryParse(list.FunctionType, out executionType);

                    log.Debug("Execution Type: " + executionType.ToString() + "Email: " + list.Recipient.ToString());

                    if (executionType == ExecutionType.MemberActivate)
                    {
                        EmailReminderHandler.Functions.ActivationReminderEmail.Send(list);
                    }
                    else if (executionType == ExecutionType.CrossSales)
                    {
                        EmailReminderHandler.Functions.CrossSaleEmail.Send(list);
                    }
                    else if (executionType == ExecutionType.TravelCreditExpire)
                    {
                        EmailReminderHandler.Functions.TravelCreditExpiredEmail.Send(list);
                    }
                    else if (executionType == ExecutionType.CrossSalesIns)
                    {
                        EmailReminderHandler.Functions.CrossSalesInsuranceEmail.Send(list);
                    }
                }
                log.Debug("Email Handler Process Completed.");
            }
            catch (Exception ex)
            {
                SendErrorMail(ex.ToString());
                log.Error("Unable to complete the Reminder Handler process.", ex);
            }
        }
예제 #7
0
        /// <summary>
        /// allows to prepare the execution environment by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            // check parameters
            var errorString = CheckParameters();

            if (!string.IsNullOrEmpty(errorString))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", errorString, MessageImg.MsgHighImportance, "Progress execution", "Couldn't start execution", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // create a unique temporary folder
            _localTempDir = Path.Combine(Config.FolderTemp, "exec_" + DateTime.Now.ToString("HHmmssfff") + "_" + Path.GetRandomFileName());
            if (!Utils.CreateDirectory(_localTempDir))
            {
                return(false);
            }

            // move .ini file into the execution directory
            if (File.Exists(ProEnv.IniPath))
            {
                _tempInifilePath = Path.Combine(_localTempDir, "base.ini");

                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding    = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex       = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches     = regex.Match(fileContent);
                if (matches.Success)
                {
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                }
                Utils.FileWriteAllText(_tempInifilePath, fileContent, encoding);
            }

            // set common info on the execution
            _processStartDir = _localTempDir;
            _logPath         = Path.Combine(_localTempDir, "run.log");
            _dbLogPath       = Path.Combine(_localTempDir, "db.ko");
            _notifPath       = Path.Combine(_localTempDir, "postExecution.notif");
            _propath         = (_localTempDir + "," + string.Join(",", ProEnv.GetProPathDirList)).Trim().Trim(',') + "\r\n";
            _propathFilePath = Path.Combine(_localTempDir, "progress.propath");
            Utils.FileWriteAllText(_propathFilePath, _propath, Encoding.Default);

            // Set info
            if (!SetExecutionInfo())
            {
                return(false);
            }

            SetPreprocessedVar("ExecutionType", ExecutionType.ToString().ToUpper().PreProcQuoter());
            SetPreprocessedVar("LogPath", _logPath.PreProcQuoter());
            SetPreprocessedVar("PropathFilePath", _propathFilePath.PreProcQuoter());
            SetPreprocessedVar("DbConnectString", ProEnv.ConnectionString.PreProcQuoter());
            SetPreprocessedVar("DbLogPath", _dbLogPath.PreProcQuoter());
            SetPreprocessedVar("DbConnectionMandatory", NeedDatabaseConnection.ToString());
            SetPreprocessedVar("NotificationOutputPath", _notifPath.PreProcQuoter());
            SetPreprocessedVar("PreExecutionProgram", ProEnv.PreExecutionProgram.Trim().PreProcQuoter());
            SetPreprocessedVar("PostExecutionProgram", ProEnv.PostExecutionProgram.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseExtractCandoTblType", ProEnv.DatabaseExtractCandoTblType.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseExtractCandoTblName", ProEnv.DatabaseExtractCandoTblName.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseAliasList", ProEnv.DatabaseAliasList.Trim().Trim(';').PreProcQuoter());

            // prepare the .p runner
            _runnerPath = Path.Combine(_localTempDir, "run_" + DateTime.Now.ToString("HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();

            foreach (var @var in _preprocessedVars)
            {
                runnerProgram.AppendLine("&SCOPED-DEFINE " + @var.Key + " " + @var.Value);
            }
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(_runnerPath, runnerProgram.ToString(), Encoding.Default);

            // no batch mode option?
            _useBatchMode = !Config.Instance.NeverUseProwinInBatchMode && !NoBatch && CanUseBatchMode();

            // Parameters
            _exeParameters = new StringBuilder();
            if (_useBatchMode)
            {
                _exeParameters.Append(" -b");
            }
            else
            {
                // we suppress the splashscreen
                if (ProEnv.CanProwinUseNoSplash)
                {
                    _exeParameters.Append(" -nosplash");
                }
                else
                {
                    MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProEnv.ProwinExePath) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProEnv.ProwinExePath) ?? "", "splashscreen-3p-disabled.bmp"));
                }
            }
            _exeParameters.Append(" -p " + _runnerPath.Quoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
            {
                _exeParameters.Append(" " + ProEnv.CmdLineParameters.Trim());
            }
            AppendProgressParameters(_exeParameters);

            // start the process
            try {
                StartProcess();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e);
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new Prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occurred :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Progress execution", "Can't start a Prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + _exeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + _localTempDir + "'>" + _localTempDir + "</a>");

            return(true);
        }
예제 #8
0
        public JsonNetResult Tags()
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            List <string> tags = null;
            TagsListJson  tagsListObjectJson = null;

            string localCacheKey = accountNameKey + ":tags";


            #region (Plan A) Get json from local cache

            try
            {
                tagsListObjectJson = (TagsListJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (tagsListObjectJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        tagsListObjectJson = JsonConvert.DeserializeObject <TagsListJson>(redisApiValue);
                        executionType      = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (tagsListObjectJson == null)
                {
                    #region (Plan C) Get data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":tags";
                        string hashMainField = "list";

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                tags          = JsonConvert.DeserializeObject <List <String> >(redisValue);
                                executionType = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (tags == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationTagsServiceClient = new ApplicationTagsService.ApplicationTagsServiceClient();

                        try
                        {
                            applicationTagsServiceClient.Open();

                            tags = applicationTagsServiceClient.GetTags(accountNameKey, Common.SharedClientKey).ToList();

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationTagsServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationTagsServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (tagsListObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, tagsListObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (tags != null)
                {
                    //Transform into JSON and cache BOTH locally AND into redis
                    tagsListObjectJson       = new TagsListJson();
                    tagsListObjectJson.tags  = tags;
                    tagsListObjectJson.count = tags.Count;

                    HttpRuntime.Cache.Insert(localCacheKey, tagsListObjectJson, null, DateTime.Now.AddMinutes(Common.TagsListCacheTimeInMinutes), TimeSpan.Zero);

                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(tagsListObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            //Add execution data
            stopWatch.Stop();
            tagsListObjectJson.executionType = executionType.ToString();
            tagsListObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = tagsListObjectJson;

            return(jsonNetResult);
        }
예제 #9
0
        protected void ExecuteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                // Check if each validator is valid
                bool valid = true;
                if (userOption == Option.Insert || userOption == Option.Update)
                {
                    foreach (BaseValidator validator in validators)
                    {
                        validator.Validate();
                        if (!validator.IsValid)
                        {
                            valid = false;
                            break;
                        }
                    }
                }
                // If not, don't execute the function
                if (!valid)
                {
                    return;
                }
                HttpResponseMessage response = null;

                switch (userOption)
                {
                case Option.Search:
                    response = Search();
                    break;

                case Option.Update:
                    response = Update();
                    break;

                case Option.Delete:
                    response = Delete();
                    break;

                default:
                    response = Insert();
                    break;
                }
                switch (userOption)
                {
                case Option.Search:
                    if (response.IsSuccessStatusCode)
                    {
                        Session["display_data"] = response.Content.ReadAsStringAsync().Result;
                        Session["display_type"] = current_type.ToString();
                        Response.Redirect("~/SearchResults.aspx", false);
                        break;
                    }
                    else
                    {
                        AlertBox(response.Content.ReadAsStringAsync().Result);
                        break;
                    }
                    break;

                default:
                    string content = "";
                    if (response.IsSuccessStatusCode)
                    {
                        content = "Success!";
                    }
                    else
                    {
                        content = response.Content.ReadAsStringAsync().Result;
                        content = content.Replace("\"", "").Replace("\'", "");
                    }

                    AlertBox(content);
                    break;
                }
            }
            catch (Exception exc)
            {
                AlertBox("Error:" + exc.Message);
            }
        }
예제 #10
0
        public JsonNetResult GetProductProperties(string type, string filter = null)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            List <PropertyModel> properties     = null;
            PropertiesResultJson propertiesJson = null;

            string           localCacheKey    = accountNameKey + ":properties:all";
            PropertyListType propertyListType = PropertyListType.All;

            if (!String.IsNullOrEmpty(type))
            {
                if (type == "listings" || type == "listing" || type == "list")
                {
                    localCacheKey    = accountNameKey + ":properties:listings";
                    propertyListType = PropertyListType.Listings;
                }
                else if (type == "details" || type == "detail")
                {
                    localCacheKey    = accountNameKey + ":properties:details";
                    propertyListType = PropertyListType.Details;
                }
                else if (type == "featured" || type == "feature")
                {
                    if (filter == "listingsOnly")
                    {
                        localCacheKey    = accountNameKey + ":properties:featured:listingsOnly";
                        propertyListType = PropertyListType.Featured;
                    }
                    else
                    {
                        localCacheKey    = accountNameKey + ":properties:featured";
                        propertyListType = PropertyListType.Featured;
                    }
                }
            }

            #region (Plan A) Get json from local cache

            try
            {
                propertiesJson = (PropertiesResultJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (propertiesJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        propertiesJson = JsonConvert.DeserializeObject <PropertiesResultJson>(redisApiValue);
                        executionType  = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (propertiesJson == null)
                {
                    #region (Plan C) Get property data from Redis Cache or WCF and Rebuild

                    properties = DataAccess.Properties.GetProperties(accountNameKey, propertyListType, out executionType);

                    #endregion
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (propertiesJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, propertiesJson, null, DateTime.Now.AddMinutes(Common.PropertiesCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (properties != null)
                {
                    //Transform properties into JSON and cache BOTH locally AND into redis
                    propertiesJson = Transforms.Json.PropertyTransforms.Properties(accountNameKey, properties, filter);
                    HttpRuntime.Cache.Insert(localCacheKey, propertiesJson, null, DateTime.Now.AddMinutes(Common.PropertiesCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(propertiesJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            //Add execution data
            stopWatch.Stop();
            propertiesJson.executionType = executionType.ToString();
            propertiesJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = propertiesJson;

            return(jsonNetResult);
        }
예제 #11
0
        public JsonNetResult GetAccount()
        {
            AccountDetailsJson accountDetailsJson = null;

            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            string localCacheKey = accountNameKey + ":accountDetails";

            #region (Plan A) Get json from local cache

            try
            {
                accountDetailsJson = (AccountDetailsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (accountDetailsJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        accountDetailsJson = JsonConvert.DeserializeObject <AccountDetailsJson>(redisApiValue);
                        executionType      = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (accountDetailsJson == null)
                {
                    #region (Plan C) Create Account Object, Get Settings & Images

                    var account = Common.GetAccountObject(accountNameKey);

                    accountDetailsJson         = new AccountDetailsJson();
                    accountDetailsJson.account = new AccountJson();
                    accountDetailsJson.account.contactSettings = new ContactSettingsJson();
                    accountDetailsJson.account.contactSettings.contactDetails = new ContactDetailsJson();
                    accountDetailsJson.account.salesSettings  = new SalesSettingsJson();
                    accountDetailsJson.account.accountName    = account.AccountName;
                    accountDetailsJson.account.accountNameKey = account.AccountNameKey;


                    //accountDetailsJson.account.paymentPlan = account.PaymentPlan;
                    accountDetailsJson.account.paymentPlan = account.PaymentPlan.PaymentPlanName;
                    //accountDetailsJson.account.paymentPlanFrequency = account.PaymentPlan.;


                    #region  Get Account Settings Document

                    AccountSettingsDocumentModel settingsDocument = DataAccess.AccountSettings.GetAccountSettings(accountNameKey);

                    #endregion

                    #region Build Sales Settings

                    if (settingsDocument.SalesSettings != null)
                    {
                        accountDetailsJson.account.salesSettings.useSalesLeads = settingsDocument.SalesSettings.UseSalesLeads;

                        if (accountDetailsJson.account.salesSettings.useSalesLeads == true)
                        {
                            accountDetailsJson.account.salesSettings.buttonCopy       = settingsDocument.SalesSettings.ButtonCopy;
                            accountDetailsJson.account.salesSettings.leadsDescription = settingsDocument.SalesSettings.DescriptionCopy;
                        }
                    }

                    #endregion

                    //Build Theme Object (removed)
                    //accountDetailsJson.account.themeSettings = new ThemeSettingsJson();
                    //accountDetailsJson.account.themeSettings.name = settingsDocument.Theme;

                    //ToDo: Pull theme info from Redis or WCF
                    #region Get Themes

                    //List<ThemeModel> themes = null;

                    #region From Redis

                    /*
                     * IDatabase platformCache = CoreServices.RedisConnectionMultiplexers.PlatformManager_Multiplexer.GetDatabase();
                     * string themesHashMainKey = "themes";
                     * string themesHashMainField = "list";
                     *
                     * try
                     * {
                     *  var themesRedis = platformCache.HashGet(themesHashMainKey, themesHashMainField);
                     *
                     *  if (themesRedis.HasValue)
                     *  {
                     *      themes = JsonConvert.DeserializeObject<List<ThemeModel>>(themesRedis);
                     *  }
                     * }
                     * catch
                     * {
                     *
                     * }
                     */
                    #endregion

                    #region From WCF

                    /*
                     * if(themes == null)
                     * {
                     *  var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();
                     *
                     *  try
                     *  {
                     *      accountManagementServiceClient.Open();
                     *
                     *      themes = accountManagementServiceClient.GetThemes().ToList();
                     *
                     *      WCFManager.CloseConnection(accountManagementServiceClient);
                     *
                     *  }
                     *  catch (Exception e)
                     *  {
                     #region Manage Exception
                     *
                     *      string exceptionMessage = e.Message.ToString();
                     *
                     *      var currentMethod = System.Reflection.MethodBase.GetCurrentMethod();
                     *      string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;
                     *
                     *      // Abort the connection & manage the exception
                     *      WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);
                     *
                     #endregion
                     *  }
                     * }
                     */
                    #endregion

                    #endregion

                    #region Build Theme

                    /*
                     * foreach(ThemeModel theme in themes)
                     * {
                     *  if(theme.Name == accountDetailsJson.account.themeSettings.name)
                     *  {
                     *      accountDetailsJson.account.themeSettings.font = theme.Font;
                     *
                     *      accountDetailsJson.account.themeSettings.colors.background = theme.Colors.Background;
                     *      accountDetailsJson.account.themeSettings.colors.backgroundGradientBottom = theme.Colors.BackgroundGradientBottom;
                     *      accountDetailsJson.account.themeSettings.colors.backgroundGradientTop = theme.Colors.BackgroundGradianetTop;
                     *      accountDetailsJson.account.themeSettings.colors.foreground = theme.Colors.Foreground;
                     *      accountDetailsJson.account.themeSettings.colors.highlight = theme.Colors.Highlight;
                     *      accountDetailsJson.account.themeSettings.colors.overlay = theme.Colors.Overlay;
                     *      accountDetailsJson.account.themeSettings.colors.shadow = theme.Colors.Shadow;
                     *      accountDetailsJson.account.themeSettings.colors.trim = theme.Colors.Trim;
                     *
                     *  }
                     * }
                     */
                    #endregion

                    accountDetailsJson.account.customDomain = settingsDocument.CustomDomain;


                    #region Build Sort Settings (removed)

                    /*
                     *
                     * if (settingsDocument.SortSettings != null)
                     * {
                     *  accountDetailsJson.account.sortSettings = new SortSettingsJson();
                     *
                     *  accountDetailsJson.account.sortSettings.truncatedList = new SortJson {
                     *      name = settingsDocument.SortSettings.TruncatedListing.Name,
                     *      value = settingsDocument.SortSettings.TruncatedListing.Value,
                     *  };
                     *
                     *  accountDetailsJson.account.sortSettings.mixedList = new SortJson
                     *  {
                     *      name = settingsDocument.SortSettings.MixedListing.Name,
                     *      value = settingsDocument.SortSettings.MixedListing.Value,
                     *  };
                     *
                     *  accountDetailsJson.account.sortSettings.fullList = new SortJson
                     *  {
                     *      name = settingsDocument.SortSettings.FullListing.Name,
                     *      value = settingsDocument.SortSettings.FullListing.Value,
                     *  };
                     * }*/

                    #endregion

                    #region Build Contact Settings & Info

                    if (settingsDocument.ContactSettings != null)
                    {
                        accountDetailsJson.account.contactSettings.showPhoneNumber = settingsDocument.ContactSettings.ShowPhoneNumber;
                        accountDetailsJson.account.contactSettings.showAddress     = settingsDocument.ContactSettings.ShowAddress;
                        accountDetailsJson.account.contactSettings.showEmail       = settingsDocument.ContactSettings.ShowEmail;

                        if (settingsDocument.ContactSettings.ContactInfo != null)
                        {
                            accountDetailsJson.account.contactSettings.contactDetails.phoneNumber = settingsDocument.ContactSettings.ContactInfo.PhoneNumber;
                            accountDetailsJson.account.contactSettings.contactDetails.email       = settingsDocument.ContactSettings.ContactInfo.Email;

                            accountDetailsJson.account.contactSettings.contactDetails.address1 = settingsDocument.ContactSettings.ContactInfo.Address1;
                            accountDetailsJson.account.contactSettings.contactDetails.address2 = settingsDocument.ContactSettings.ContactInfo.Address2;
                            accountDetailsJson.account.contactSettings.contactDetails.city     = settingsDocument.ContactSettings.ContactInfo.City;

                            accountDetailsJson.account.contactSettings.contactDetails.state      = settingsDocument.ContactSettings.ContactInfo.State;
                            accountDetailsJson.account.contactSettings.contactDetails.postalCode = settingsDocument.ContactSettings.ContactInfo.PostalCode;
                        }
                    }

                    #endregion

                    //Get Images:
                    accountDetailsJson.account.images = Dynamics.Images.BuildDynamicImagesListForJson(accountNameKey, "account", account.AccountID.ToString(), false);

                    #endregion

                    #region Cache into redisAPI layer

                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(accountDetailsJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }

                    #endregion
                }

                #region Cache locally

                HttpRuntime.Cache.Insert(localCacheKey, accountDetailsJson, null, DateTime.Now.AddMinutes(Common.AccountSettingsCacheTimeInMinutes), TimeSpan.Zero);

                #endregion
            }



            //Add execution data
            stopWatch.Stop();
            accountDetailsJson.executionType = executionType.ToString();
            accountDetailsJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = accountDetailsJson;

            return(jsonNetResult);
        }
 public override void Print()
 {
     CustomConsole.PrintRow(_id.ToString(), _tradedate.ToShortDateString(), _currencypair.ToString(),
                            _notional.ToString(), _premium.ToString(), _spot.ToString(), _strike.ToString(), _direction.ToString(),
                            _type.ToString(), _executiontype.ToString(), _withdrawdate.ToShortDateString(), _settlementdate.ToShortDateString());
 }
예제 #13
0
파일: ProMisc.cs 프로젝트: devjerome/3P
        /// <summary>
        /// Called to run/compile/check/prolint the current program
        /// </summary>
        public static void StartProgressExec(ExecutionType executionType)
        {
            CurrentOperation currentOperation;

            if (!Enum.TryParse(executionType.ToString(), true, out currentOperation))
            {
                currentOperation = CurrentOperation.Run;
            }

            // process already running?
            if (Plug.CurrentFileObject.CurrentOperation >= CurrentOperation.Prolint)
            {
                UserCommunication.NotifyUnique("KillExistingProcess", "This file is already being compiled, run or lint-ed.<br>Please wait the end of the previous action,<br>or click the link below to interrupt the previous action :<br><a href='#'>Click to kill the associated prowin process</a>", MessageImg.MsgRip, currentOperation.GetAttribute <CurrentOperationAttr>().Name, "Already being compiled/run", args => {
                    KillCurrentProcess();
                    StartProgressExec(executionType);
                    args.Handled = true;
                }, 5);
                return;
            }
            if (!Abl.IsCurrentProgressFile)
            {
                UserCommunication.Notify("Can only compile and run progress files!", MessageImg.MsgWarning, "Invalid file type", "Progress files only", 10);
                return;
            }
            if (string.IsNullOrEmpty(Plug.CurrentFilePath) || !File.Exists(Plug.CurrentFilePath))
            {
                UserCommunication.Notify("Couldn't find the following file :<br>" + Plug.CurrentFilePath, MessageImg.MsgError, "Execution error", "File not found", 10);
                return;
            }
            if (!Config.Instance.CompileKnownExtension.Split(',').Contains(Path.GetExtension(Plug.CurrentFilePath)))
            {
                UserCommunication.Notify("Sorry, the file extension " + Path.GetExtension(Plug.CurrentFilePath).ProQuoter() + " isn't a valid extension for this action!<br><i>You can change the list of valid extensions in the settings window</i>", MessageImg.MsgWarning, "Invalid file extension", "Not an executable", 10);
                return;
            }

            // update function prototypes
            ProGenerateCode.UpdateFunctionPrototypesIfNeeded(true);

            // prolint? check that the StartProlint.p program is created, or do it
            if (executionType == ExecutionType.Prolint)
            {
                if (!File.Exists(Config.FileStartProlint))
                {
                    if (!Utils.FileWriteAllBytes(Config.FileStartProlint, DataResources.StartProlint))
                    {
                        return;
                    }
                }
            }

            // launch the compile process for the current file
            Plug.CurrentFileObject.ProgressExecution = new ProExecution {
                ListToCompile = new List <FileToCompile> {
                    new FileToCompile(Plug.CurrentFilePath)
                },
                OnExecutionEnd = OnSingleExecutionEnd,
                OnExecutionOk  = OnSingleExecutionOk
            };
            if (!Plug.CurrentFileObject.ProgressExecution.Do(executionType))
            {
                return;
            }

            // change file object current operation, set flag
            Plug.CurrentFileObject.CurrentOperation |= currentOperation;
            FilesInfo.UpdateFileStatus();

            // clear current errors (updates the current file info)
            FilesInfo.ClearAllErrors(Plug.CurrentFilePath, true);
        }
 public string Format(ExecutionType obj)
 => obj.ToString().ToHyphenSeparatedWords();
예제 #15
0
파일: ProExecution.cs 프로젝트: jcaillon/3P
        /// <summary>
        /// allows to prepare the execution environnement by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Do(ExecutionType executionType)
        {
            if (ListToCompile == null)
                ListToCompile = new List<FileToCompile>();

            ExecutionType = executionType;

            // check prowin32.exe
            if (!File.Exists(ProEnv.ProwinPath)) {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The file path to Prowin.exe is incorrect : <div class='ToolTipcodeSnippet'>" + ProEnv.ProwinPath + "</div>You must provide a valid path before executing this action<br><i>You can change this path in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return false;
            }

            // check compilation dir
            if (executionType == ExecutionType.Compile && !ProEnv.CompileLocally && (!Path.IsPathRooted(ProEnv.BaseCompilationPath))) {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The path for the compilation base directory is incorrect : <div class='ToolTipcodeSnippet'>" + (string.IsNullOrEmpty(ProEnv.BaseCompilationPath) ? "it's empty!" : ProEnv.BaseCompilationPath) + "</div>You must provide a valid path before executing this action :<br><br><i>1. Either change the compilation directory<br>2. Or toggle the option to compile next to the source file!<br><br>The options are configurable in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return false;
            }

            // create a unique temporary folder
            LocalTempDir = Path.Combine(Config.FolderTemp, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
            if (!Utils.CreateDirectory(LocalTempDir))
                return false;

            // for each file of the list
            var filesListPath = Path.Combine(LocalTempDir, "files.list");
            StringBuilder filesListcontent = new StringBuilder();
            var count = 1;
            foreach (var fileToCompile in ListToCompile) {

                if (!File.Exists(fileToCompile.InputPath)) {
                    UserCommunication.Notify("Couldn't find the following file :<br>" + fileToCompile.InputPath, MessageImg.MsgError, "Execution error", "File not found", 10);
                    return false;
                }

                // if current file and the file has unsaved modif, we copy the content to a temp file, otherwise we just use the input path (also use the input path for .cls files!)
                if (fileToCompile.InputPath.Equals(Plug.CurrentFilePath) &&
                    (Npp.GetModify || (fileToCompile.BaseFileName ?? "").StartsWith("_")) &&
                    !Path.GetExtension(fileToCompile.InputPath).Equals(".cls")) {
                    fileToCompile.CompInputPath = Path.Combine(LocalTempDir, "tmp_" + DateTime.Now.ToString("yyMMdd_HHmmssfff_") + count + Path.GetExtension(fileToCompile.InputPath));
                    Utils.FileWriteAllText(fileToCompile.CompInputPath, Npp.Text, Encoding.Default);
                } else {
                    fileToCompile.CompInputPath = fileToCompile.InputPath;
                }

                if (executionType != ExecutionType.Compile)
                    continue;

                // we set where the *.lst and *.r files will be generated by the COMPILE command
                var baseFileName = Path.GetFileNameWithoutExtension(fileToCompile.CompInputPath);
                var lastDeployment = ProEnv.Deployer.GetTargetDirsNeededForFile(fileToCompile.InputPath, 0).Last();

                // for *.cls files, as many *.r files are generated, we need to compile in a temp directory
                // we need to know which *.r files were generated for each input file
                // so each file gets his own sub tempDir
                if ((lastDeployment.DeployType != DeployType.Move) ||
                    Config.Instance.CompileForceUseOfTemp ||
                    Path.GetExtension(fileToCompile.InputPath).Equals(".cls")
                    ) {

                    var subTempDir = Path.Combine(LocalTempDir, count.ToString());

                    // if the deployment dir is not on the same disk as the temp folder, we create a temp dir
                    // as close to the final deployment as possible (= in the deployment base dir!)
                    if (lastDeployment.DeployType != DeployType.Ftp && !string.IsNullOrEmpty(DistantRootTempDir) && DistantRootTempDir.Length > 2 && !DistantRootTempDir.Substring(0, 2).EqualsCi(LocalTempDir.Substring(0, 2))) {

                        if (Utils.CreateDirectory(DistantRootTempDir, FileAttributes.Hidden))
                            DistantTempDir = Path.Combine(DistantRootTempDir, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
                        else
                            DistantTempDir = LocalTempDir;

                        subTempDir = Path.Combine(DistantTempDir, count.ToString());
                    }

                    if (!Utils.CreateDirectory(subTempDir))
                        return false;

                    fileToCompile.CompOutputDir = subTempDir;
                    fileToCompile.CompOutputLst = Path.Combine(subTempDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR = Path.Combine(subTempDir, baseFileName + ".r");

                } else {

                    // if we want to move the r-code somewhere during the deployment, then we will compile the r-code
                    // directly there, because it's faster than generating it in a temp folder and moving it afterward
                    fileToCompile.CompOutputDir = lastDeployment.TargetDir;
                    if (!Utils.CreateDirectory(fileToCompile.CompOutputDir))
                        return false;

                    fileToCompile.CompOutputLst = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".r");
                }

                // feed files list
                filesListcontent.AppendLine(fileToCompile.CompInputPath.ProQuoter() + " " + fileToCompile.CompOutputDir.ProQuoter() + " " + fileToCompile.CompOutputLst.ProQuoter());

                count++;
            }
            Utils.FileWriteAllText(filesListPath, filesListcontent.ToString(), Encoding.Default);

            // when running a procedure, check that a .r is not hiding the program, if that's the case we warn the user
            if (executionType == ExecutionType.Run && !_dontWarnAboutRCode && ListToCompile.Count >= 1) {
                if (File.Exists(Path.ChangeExtension(ListToCompile.First().InputPath, ".r"))) {
                    UserCommunication.NotifyUnique("rcodehide", "Friendly warning, an <b>r-code</b> <i>(i.e. *.r file)</i> is hiding the current program<br>If you modified it since the last compilation you might not have the expected behavior...<br><br><i>" + "stop".ToHtmlLink("Click here to not show this message again for this session") + "</i>", MessageImg.MsgWarning, "Execution warning", "An Rcode hides the program", args => {
                        _dontWarnAboutRCode = true;
                        UserCommunication.CloseUniqueNotif("rcodehide");
                    }, 5);
                }
            }

            // Move ini file into the execution dir
            var baseIniPath = "";
            if (File.Exists(ProEnv.IniPath)) {
                baseIniPath = Path.Combine(LocalTempDir, "base.ini");
                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches = regex.Match(fileContent);
                if (matches.Success)
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                Utils.FileWriteAllText(baseIniPath, fileContent, encoding);
            }

            // Move pf file into the execution dir
            var basePfPath = "";
            if (File.Exists(ProEnv.GetPfPath())) {
                basePfPath = Path.Combine(LocalTempDir, "base.pf");
                File.Copy(ProEnv.GetPfPath(), basePfPath);
            }

            // set common info on the execution
            LogPath = Path.Combine(LocalTempDir, "run.log");
            ProcessStartDir = executionType == ExecutionType.Run ? Path.GetDirectoryName(ListToCompile.First().InputPath) ?? LocalTempDir : LocalTempDir;
            ProgressWin32 = ProEnv.ProwinPath;
            if (executionType == ExecutionType.Database)
                ExtractDbOutputPath = Path.Combine(LocalTempDir, ExtractDbOutputPath);
            ProgressionFilePath = Path.Combine(LocalTempDir, "compile.progression");
            DatabaseConnectionLog = Path.Combine(LocalTempDir, "db.ko");
            NotificationOutputPath = Path.Combine(LocalTempDir, "postExecution.notif");
            var propathToUse = string.Join(",", ProEnv.GetProPathDirList);
            string fileToExecute = "";

            if (executionType == ExecutionType.Appbuilder) {
                fileToExecute = ListToCompile.First().InputPath;

            } else if (executionType == ExecutionType.Database) {

                // for database extraction, we need to copy the DumpDatabase program
                fileToExecute = "db_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                if (!Utils.FileWriteAllBytes(Path.Combine(LocalTempDir, fileToExecute), DataResources.DumpDatabase))
                    return false;

            } else if (executionType == ExecutionType.Prolint) {

                // prolint, we need to copy the StartProlint program
                fileToExecute = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                ProlintOutputPath = Path.Combine(LocalTempDir, "prolint.log");
                StringBuilder prolintProgram = new StringBuilder();
                prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + ListToCompile.First().CompInputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + ProlintOutputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.FileStartProlint.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + ListToCompile.First().InputPath.ProQuoter());
                var filename = Path.GetFileName(Plug.CurrentFilePath);
                if (FileTag.Contains(filename)) {
                    var fileInfo = FileTag.GetLastFileTag(filename);
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.ProQuoter());
                }
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileStartProlint);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileStartProlint, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);

            } else if (executionType == ExecutionType.DeploymentHook) {

                fileToExecute = "hook_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                StringBuilder hookProc = new StringBuilder();
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationName " + ProEnv.Name.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationSuffix " + ProEnv.Suffix.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE StepNumber " + DeploymentStep);
                hookProc.AppendLine("&SCOPED-DEFINE SourceDirectory " + DeploymentSourcePath.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE DeploymentDirectory " + ProEnv.BaseCompilationPath.ProQuoter());
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileDeploymentHook);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileDeploymentHook, encoding).Replace(@"/*<inserted_3P_values>*/", hookProc.ToString()), encoding);

            } else if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader) {
                // need to init datadigger?
                if (!File.Exists(Path.Combine(Config.FolderDataDigger, "DataDigger.p"))) {
                    if (!Utils.FileWriteAllBytes(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), DataResources.DataDigger))
                        return false;
                    if (!Utils.ExtractAll(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), Config.FolderDataDigger))
                        return false;
                }
                // add the datadigger folder to the propath
                propathToUse = Config.FolderDataDigger + "," + propathToUse;

            } else {

                if (ListToCompile.Count == 1)
                    fileToExecute = ListToCompile.First().CompInputPath;
            }

            // prepare the .p runner
            var runnerPath = Path.Combine(LocalTempDir, "run_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();
            runnerProgram.AppendLine("&SCOPED-DEFINE ExecutionType " + executionType.ToString().ToUpper().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ToExecute " + fileToExecute.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE LogFile " + LogPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtractDbOutputPath " + ExtractDbOutputPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE propathToUse " + (LocalTempDir + "," + propathToUse).ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtraPf " + ProEnv.ExtraPf.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE BasePfPath " + basePfPath.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileWithLst " + ProEnv.CompileWithListing);
            runnerProgram.AppendLine("&SCOPED-DEFINE ToCompileListFile " + filesListPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CreateFileIfConnectFails " + DatabaseConnectionLog.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileProgressionFile " + ProgressionFilePath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE DbConnectionMandatory " + NeedDatabaseConnection);
            runnerProgram.AppendLine("&SCOPED-DEFINE NotificationOutputPath " + NotificationOutputPath.ProQuoter());
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(runnerPath, runnerProgram.ToString(), Encoding.Default);

            // preferably, we use the batch mode because it's faster than the client mode
            var batchMode = (executionType == ExecutionType.CheckSyntax || executionType == ExecutionType.Compile || executionType == ExecutionType.Database);

            // no batch mode option?
            batchMode = batchMode && !Config.Instance.NeverUseProwinInBatchMode;

            // multiple compilation, we don't want to show all those Prowin in the task bar...
            batchMode = batchMode && !NoBatch;

            // Parameters
            StringBuilder Params = new StringBuilder();

            if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
                Params.Append(" -s 10000 -d dmy -E -rereadnolock -h 255 -Bt 4000 -tmpbsize 8");
            if (executionType != ExecutionType.Run)
                Params.Append(" -T " + LocalTempDir.Trim('\\').ProQuoter());
            if (!string.IsNullOrEmpty(baseIniPath))
                Params.Append(" -ini " + baseIniPath.ProQuoter());
            if (batchMode)
                Params.Append(" -b");
            Params.Append(" -p " + runnerPath.ProQuoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
                Params.Append(" " + ProEnv.CmdLineParameters.Trim());
            ExeParameters = Params.ToString();

            // we supress the splashscreen
            if (!batchMode)
                MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen-3p-disabled.bmp"));

            // Start a process
            var pInfo = new ProcessStartInfo {
                FileName = ProEnv.ProwinPath,
                Arguments = ExeParameters,
                WorkingDirectory = ProcessStartDir
            };
            if (batchMode) {
                pInfo.WindowStyle = ProcessWindowStyle.Hidden;
                pInfo.CreateNoWindow = true;
            }
            Process = new Process {
                StartInfo = pInfo,
                EnableRaisingEvents = true
            };
            Process.Exited += ProcessOnExited;
            try {
                Process.Start();
            } catch (Exception e) {
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occured :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Execution error", "Can't start a prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + ExeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + TempDir + "'>" + TempDir + "</a>");

            return true;
        }
예제 #16
0
        private List<MethodInfo> GetExecutionMethods(Type testType, ExecutionType executionType)
        {
            List<MethodInfo> methods = new List<MethodInfo>();

            Type executionAttribute = null;

            switch (executionType)
            {
                case ExecutionType.PreHost:
                    executionAttribute = typeof(VsIdePreHostExecutionMethod);
                    break;
                case ExecutionType.PostHost:
                    executionAttribute = typeof(VsIdePostHostExecutionMethod);
                    break;
                default:
                    throw new ArgumentException("Unknow Execution Type.");
            }

            foreach (var m in testType.GetMethods())
            {
                bool hasCustomAttribute = m.GetCustomAttributes(executionAttribute, true).Length >= 1;
                
                if (hasCustomAttribute
                    && !m.IsAbstract
                    && m.IsStatic
                    && m.GetParameters().Length == 0)
                {
                    methods.Add(m);
                }
                else if (hasCustomAttribute)
                {
                    HostProcessErrorHandler(
                        String.Format("Method {0} is attributed with {1} but cannot be run Pre/Post Host. "
                                    + "Methods must be Static and have no parameters."
                                    , m.ToString()
                                    , executionType.ToString())
                        , TestOutcome.Warning
                        , false);
                }
            }

            return methods;
        }
예제 #17
0
        private void SetData_ExecuteCode(object sender, EventArgs e)
        {
            string approversName = string.Empty;

            var approvers = GetApprovers(this.ApprovalData);
            approversName = String.Join(",", approvers.ToArray());
            Approvers = approvers.Select(p => new TaskInfo()
               {
               Approver = p,
               MessageTitle = this.ApprovalData.MessageTitle,
               Message = this.ApprovalData.Message,
               MailEnable = this.ApprovalData.EnableEmail,
               TaskContentType = this.ApprovalData.TaskContenType,
               TaskTitle = this.ApprovalData.TaskTitle,
               AppendTitle = this.ApprovalData.AppendTitle,
               TaskInstruction = this.ApprovalData.TaskInstruction,
               DueDate = this.ApprovalData.DueDate,
               TaskDuration = this.ApprovalData.DurationPerTask,
               UpdatedProperties = this.ApprovalData.UpdatedProperties,
               TaskEvents = this.ApprovalData.TaskEvents,
               }).ToList();
            MultiTaskReplicator_ExecutionType = (ExecutionType)Enum.Parse(typeof(ExecutionType), this.ApprovalData.TaskSequenceType);
            workflowProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.WorkflowComment, "Begin approval level: " + ApprovalData.LevelName , MultiTaskReplicator_ExecutionType.ToString());
            workflowProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.WorkflowComment, "Tasks was created and sent to : " + approversName, string.Empty);
        }
예제 #18
0
        public JsonNetResult BrowseByPropertyNameValue(string searchFieldName, string searchFieldValue, string orderBy = "dateCreated desc", int skip = 0, int take = 50, int top = 50, bool includeHidden = false)
        {
            //Alows you to use take and top interchangelbly
            if (top != take && top != 50)
            {
                take = top;
            }


            //We limit TAKEs on the api to 200 for performance purposes
            if (take > 120)
            {
                take = 120;
            }


            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            //CategoryModel category = null;
            SearchResultsJson searchResultsJson = null;
            SearchResults     searchResults     = null;

            string localCacheKey = accountNameKey + ":browse:propertyname:" + searchFieldName + ":propertyvalue:" + searchFieldValue + ":skip:" + skip + ":take:" + take + ":public";

            if (includeHidden == true)
            {
                localCacheKey = accountNameKey + ":browse:propertyname:" + searchFieldName + ":propertyvalue:" + searchFieldValue + ":skip:" + skip + ":take:" + take + ":private";
            }

            #region (Plan A) Get json from local cache

            try
            {
                searchResultsJson = (SearchResultsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (searchResultsJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        searchResultsJson = JsonConvert.DeserializeObject <SearchResultsJson>(redisApiValue);
                        executionType     = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }

                #endregion

                if (searchResultsJson == null)
                {
                    #region (Plan C) Get Public json from search index

                    var account = Common.GetAccountObject(accountNameKey);

                    //ToDo:
                    //Determine propertyType and build filter accordingly. Reject Paragraphs, Etc...

                    string filter = String.Empty;

                    if (searchFieldName == "categoryName" || searchFieldName == "categoryNameKey" ||
                        searchFieldName == "subcategoryName" || searchFieldName == "subcategoryNameKey" ||
                        searchFieldName == "subsubcategoryName" || searchFieldName == "subsubcategoryNameKey" ||
                        searchFieldName == "subsubsubcategoryName" || searchFieldName == "subsubsubcategoryNameKey" ||
                        searchFieldName == "locationPath"
                        )
                    {
                        //If this is from one of our standard properties we use a simple EQ filter:
                        filter = "(" + searchFieldName + " eq '" + searchFieldValue + "')";
                    }
                    else if (searchFieldName == "tags" || searchFieldName == "tag")
                    {
                        //If this is from tags we use a collections EQ filter:
                        filter = "(tags/any(s: s eq '" + searchFieldValue + "'))";
                    }
                    else
                    {
                        #region Check if this is a CUSTOM type: and build filter accordingly. Reject Paragraphs, Etc..

                        var propertyType = DataAccess.Properties.GetPropertyType(accountNameKey, searchFieldName);

                        if (!String.IsNullOrEmpty(propertyType))
                        {
                            if (propertyType == "string" || propertyType == "number")
                            {
                                filter = "(" + searchFieldName + " eq '" + searchFieldValue + "')";
                            }
                            else if (propertyType == "predefined" || propertyType == "swatch")
                            {
                                filter = "(" + searchFieldName + "/any(s: s eq '" + searchFieldValue + "'))";
                            }

                            //(fabric any(s: s eq Red Wool ))
                        }
                        else
                        {
                            return(null);
                        }

                        #endregion
                    }

                    searchResults = DataAccess.Search.SearchProducts(account, null, filter, orderBy, skip, take, false, null, includeHidden);

                    #endregion

                    #region Transform into json object, add images

                    //Transform into JSON and cache onto Secondary Cache Layer:
                    searchResultsJson = Transforms.Json.SearchTransforms.ProductResults(searchResults);

                    #endregion

                    try
                    {
                        //Cache on Secondary Cache:
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(searchResultsJson), When.Always, CommandFlags.FireAndForget);
                        executionType = ExecutionType.searchIndex;
                    }
                    catch
                    {
                    }
                }

                //Cache Locally
                HttpRuntime.Cache.Insert(localCacheKey, searchResultsJson, null, DateTime.Now.AddMinutes(Common.SearchResultsCacheTimeInMinutes), TimeSpan.Zero);
            }

            //Add execution data
            stopWatch.Stop();
            searchResultsJson.executionType = executionType.ToString();
            searchResultsJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = searchResultsJson;

            return(jsonNetResult);
        }
예제 #19
0
        /// <summary>
        /// allows to prepare the execution environnement by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Do(ExecutionType executionType)
        {
            if (ListToCompile == null)
            {
                ListToCompile = new List <FileToCompile>();
            }

            ExecutionType = executionType;

            // check prowin32.exe
            if (!File.Exists(ProEnv.ProwinPath))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The file path to Prowin.exe is incorrect : <div class='ToolTipcodeSnippet'>" + ProEnv.ProwinPath + "</div>You must provide a valid path before executing this action<br><i>You can change this path in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // check compilation dir
            if (executionType == ExecutionType.Compile && !ProEnv.CompileLocally && (!Path.IsPathRooted(ProEnv.BaseCompilationPath)))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The path for the compilation base directory is incorrect : <div class='ToolTipcodeSnippet'>" + (string.IsNullOrEmpty(ProEnv.BaseCompilationPath) ? "it's empty!" : ProEnv.BaseCompilationPath) + "</div>You must provide a valid path before executing this action :<br><br><i>1. Either change the compilation directory<br>2. Or toggle the option to compile next to the source file!<br><br>The options are configurable in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // create a unique temporary folder
            LocalTempDir = Path.Combine(Config.FolderTemp, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
            if (!Utils.CreateDirectory(LocalTempDir))
            {
                return(false);
            }

            // for each file of the list
            var           filesListPath    = Path.Combine(LocalTempDir, "files.list");
            StringBuilder filesListcontent = new StringBuilder();
            var           count            = 1;

            foreach (var fileToCompile in ListToCompile)
            {
                if (!File.Exists(fileToCompile.InputPath))
                {
                    UserCommunication.Notify("Couldn't find the following file :<br>" + fileToCompile.InputPath, MessageImg.MsgError, "Execution error", "File not found", 10);
                    return(false);
                }

                // if current file and the file has unsaved modif, we copy the content to a temp file, otherwise we just use the input path (also use the input path for .cls files!)
                if (fileToCompile.InputPath.Equals(Plug.CurrentFilePath) &&
                    (Npp.GetModify || (fileToCompile.BaseFileName ?? "").StartsWith("_")) &&
                    !Path.GetExtension(fileToCompile.InputPath).Equals(".cls"))
                {
                    fileToCompile.CompInputPath = Path.Combine(LocalTempDir, "tmp_" + DateTime.Now.ToString("yyMMdd_HHmmssfff_") + count + Path.GetExtension(fileToCompile.InputPath));
                    Utils.FileWriteAllText(fileToCompile.CompInputPath, Npp.Text, Encoding.Default);
                }
                else
                {
                    fileToCompile.CompInputPath = fileToCompile.InputPath;
                }

                if (executionType != ExecutionType.Compile)
                {
                    continue;
                }

                // we set where the *.lst and *.r files will be generated by the COMPILE command
                var baseFileName   = Path.GetFileNameWithoutExtension(fileToCompile.CompInputPath);
                var lastDeployment = ProEnv.Deployer.GetTargetDirsNeededForFile(fileToCompile.InputPath, 0).Last();

                // for *.cls files, as many *.r files are generated, we need to compile in a temp directory
                // we need to know which *.r files were generated for each input file
                // so each file gets his own sub tempDir
                if ((lastDeployment.DeployType != DeployType.Move) ||
                    Config.Instance.CompileForceUseOfTemp ||
                    Path.GetExtension(fileToCompile.InputPath).Equals(".cls")
                    )
                {
                    var subTempDir = Path.Combine(LocalTempDir, count.ToString());

                    // if the deployment dir is not on the same disk as the temp folder, we create a temp dir
                    // as close to the final deployment as possible (= in the deployment base dir!)
                    if (lastDeployment.DeployType != DeployType.Ftp && !string.IsNullOrEmpty(DistantRootTempDir) && DistantRootTempDir.Length > 2 && !DistantRootTempDir.Substring(0, 2).EqualsCi(LocalTempDir.Substring(0, 2)))
                    {
                        if (Utils.CreateDirectory(DistantRootTempDir, FileAttributes.Hidden))
                        {
                            DistantTempDir = Path.Combine(DistantRootTempDir, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
                        }
                        else
                        {
                            DistantTempDir = LocalTempDir;
                        }

                        subTempDir = Path.Combine(DistantTempDir, count.ToString());
                    }

                    if (!Utils.CreateDirectory(subTempDir))
                    {
                        return(false);
                    }

                    fileToCompile.CompOutputDir = subTempDir;
                    fileToCompile.CompOutputLst = Path.Combine(subTempDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR   = Path.Combine(subTempDir, baseFileName + ".r");
                }
                else
                {
                    // if we want to move the r-code somewhere during the deployment, then we will compile the r-code
                    // directly there, because it's faster than generating it in a temp folder and moving it afterward
                    fileToCompile.CompOutputDir = lastDeployment.TargetDir;
                    if (!Utils.CreateDirectory(fileToCompile.CompOutputDir))
                    {
                        return(false);
                    }

                    fileToCompile.CompOutputLst = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR   = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".r");
                }

                // feed files list
                filesListcontent.AppendLine(fileToCompile.CompInputPath.ProQuoter() + " " + fileToCompile.CompOutputDir.ProQuoter() + " " + fileToCompile.CompOutputLst.ProQuoter());

                count++;
            }
            Utils.FileWriteAllText(filesListPath, filesListcontent.ToString(), Encoding.Default);

            // when running a procedure, check that a .r is not hiding the program, if that's the case we warn the user
            if (executionType == ExecutionType.Run && !_dontWarnAboutRCode && ListToCompile.Count >= 1)
            {
                if (File.Exists(Path.ChangeExtension(ListToCompile.First().InputPath, ".r")))
                {
                    UserCommunication.NotifyUnique("rcodehide", "Friendly warning, an <b>r-code</b> <i>(i.e. *.r file)</i> is hiding the current program<br>If you modified it since the last compilation you might not have the expected behavior...<br><br><i>" + "stop".ToHtmlLink("Click here to not show this message again for this session") + "</i>", MessageImg.MsgWarning, "Execution warning", "An Rcode hides the program", args => {
                        _dontWarnAboutRCode = true;
                        UserCommunication.CloseUniqueNotif("rcodehide");
                    }, 5);
                }
            }

            // Move ini file into the execution dir
            var baseIniPath = "";

            if (File.Exists(ProEnv.IniPath))
            {
                baseIniPath = Path.Combine(LocalTempDir, "base.ini");
                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding    = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex       = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches     = regex.Match(fileContent);
                if (matches.Success)
                {
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                }
                Utils.FileWriteAllText(baseIniPath, fileContent, encoding);
            }

            // Move pf file into the execution dir
            var basePfPath = "";

            if (File.Exists(ProEnv.GetPfPath()))
            {
                basePfPath = Path.Combine(LocalTempDir, "base.pf");
                File.Copy(ProEnv.GetPfPath(), basePfPath);
            }

            // set common info on the execution
            LogPath         = Path.Combine(LocalTempDir, "run.log");
            ProcessStartDir = executionType == ExecutionType.Run ? Path.GetDirectoryName(ListToCompile.First().InputPath) ?? LocalTempDir : LocalTempDir;
            ProgressWin32   = ProEnv.ProwinPath;
            if (executionType == ExecutionType.Database)
            {
                ExtractDbOutputPath = Path.Combine(LocalTempDir, ExtractDbOutputPath);
            }
            ProgressionFilePath    = Path.Combine(LocalTempDir, "compile.progression");
            DatabaseConnectionLog  = Path.Combine(LocalTempDir, "db.ko");
            NotificationOutputPath = Path.Combine(LocalTempDir, "postExecution.notif");
            var    propathToUse  = string.Join(",", ProEnv.GetProPathDirList);
            string fileToExecute = "";


            if (executionType == ExecutionType.Appbuilder)
            {
                fileToExecute = ListToCompile.First().InputPath;
            }
            else if (executionType == ExecutionType.Database)
            {
                // for database extraction, we need to copy the DumpDatabase program
                fileToExecute = "db_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                if (!Utils.FileWriteAllBytes(Path.Combine(LocalTempDir, fileToExecute), DataResources.DumpDatabase))
                {
                    return(false);
                }
            }
            else if (executionType == ExecutionType.Prolint)
            {
                // prolint, we need to copy the StartProlint program
                fileToExecute     = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                ProlintOutputPath = Path.Combine(LocalTempDir, "prolint.log");
                StringBuilder prolintProgram = new StringBuilder();
                prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + ListToCompile.First().CompInputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + ProlintOutputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.FileStartProlint.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + ListToCompile.First().InputPath.ProQuoter());
                var filename = Path.GetFileName(Plug.CurrentFilePath);
                if (FileTag.Contains(filename))
                {
                    var fileInfo = FileTag.GetLastFileTag(filename);
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.ProQuoter());
                }
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileStartProlint);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileStartProlint, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);
            }
            else if (executionType == ExecutionType.DeploymentHook)
            {
                fileToExecute = "hook_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                StringBuilder hookProc = new StringBuilder();
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationName " + ProEnv.Name.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationSuffix " + ProEnv.Suffix.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE StepNumber " + DeploymentStep);
                hookProc.AppendLine("&SCOPED-DEFINE SourceDirectory " + DeploymentSourcePath.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE DeploymentDirectory " + ProEnv.BaseCompilationPath.ProQuoter());
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileDeploymentHook);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileDeploymentHook, encoding).Replace(@"/*<inserted_3P_values>*/", hookProc.ToString()), encoding);
            }
            else if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
            {
                // need to init datadigger?
                if (!File.Exists(Path.Combine(Config.FolderDataDigger, "DataDigger.p")))
                {
                    if (!Utils.FileWriteAllBytes(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), DataResources.DataDigger))
                    {
                        return(false);
                    }
                    if (!Utils.ExtractAll(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), Config.FolderDataDigger))
                    {
                        return(false);
                    }
                }
                // add the datadigger folder to the propath
                propathToUse = Config.FolderDataDigger + "," + propathToUse;
            }
            else
            {
                if (ListToCompile.Count == 1)
                {
                    fileToExecute = ListToCompile.First().CompInputPath;
                }
            }

            // prepare the .p runner
            var           runnerPath    = Path.Combine(LocalTempDir, "run_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();

            runnerProgram.AppendLine("&SCOPED-DEFINE ExecutionType " + executionType.ToString().ToUpper().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ToExecute " + fileToExecute.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE LogFile " + LogPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtractDbOutputPath " + ExtractDbOutputPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE propathToUse " + (LocalTempDir + "," + propathToUse).ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtraPf " + ProEnv.ExtraPf.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE BasePfPath " + basePfPath.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileWithLst " + ProEnv.CompileWithListing);
            runnerProgram.AppendLine("&SCOPED-DEFINE ToCompileListFile " + filesListPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CreateFileIfConnectFails " + DatabaseConnectionLog.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileProgressionFile " + ProgressionFilePath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE DbConnectionMandatory " + NeedDatabaseConnection);
            runnerProgram.AppendLine("&SCOPED-DEFINE NotificationOutputPath " + NotificationOutputPath.ProQuoter());
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(runnerPath, runnerProgram.ToString(), Encoding.Default);

            // preferably, we use the batch mode because it's faster than the client mode
            var batchMode = (executionType == ExecutionType.CheckSyntax || executionType == ExecutionType.Compile || executionType == ExecutionType.Database);

            // no batch mode option?
            batchMode = batchMode && !Config.Instance.NeverUseProwinInBatchMode;

            // multiple compilation, we don't want to show all those Prowin in the task bar...
            batchMode = batchMode && !NoBatch;

            // Parameters
            StringBuilder Params = new StringBuilder();

            if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
            {
                Params.Append(" -s 10000 -d dmy -E -rereadnolock -h 255 -Bt 4000 -tmpbsize 8");
            }
            if (executionType != ExecutionType.Run)
            {
                Params.Append(" -T " + LocalTempDir.Trim('\\').ProQuoter());
            }
            if (!string.IsNullOrEmpty(baseIniPath))
            {
                Params.Append(" -ini " + baseIniPath.ProQuoter());
            }
            if (batchMode)
            {
                Params.Append(" -b");
            }
            Params.Append(" -p " + runnerPath.ProQuoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
            {
                Params.Append(" " + ProEnv.CmdLineParameters.Trim());
            }
            ExeParameters = Params.ToString();

            // we supress the splashscreen
            if (!batchMode)
            {
                MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen-3p-disabled.bmp"));
            }

            // Start a process
            var pInfo = new ProcessStartInfo {
                FileName         = ProEnv.ProwinPath,
                Arguments        = ExeParameters,
                WorkingDirectory = ProcessStartDir
            };

            if (batchMode)
            {
                pInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                pInfo.CreateNoWindow = true;
            }
            Process = new Process {
                StartInfo           = pInfo,
                EnableRaisingEvents = true
            };
            Process.Exited += ProcessOnExited;
            try {
                Process.Start();
            } catch (Exception e) {
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occured :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Execution error", "Can't start a prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + ExeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + TempDir + "'>" + TempDir + "</a>");

            return(true);
        }
예제 #20
0
 public override string ToString() => ExecutionType.ToString()
 + (ExecutionType == ExecutionType.Parallel ? " Threads = " + ParallelThreads : null);
예제 #21
0
        public JsonNetResult ProductFacets(bool includeHidden = false)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            AccountManagementService.Account account = Common.GetAccountObject(accountNameKey);

            string localCacheKey = accountNameKey + ":product:search:facets:includeHidden:" + includeHidden;


            List <ProductSearchFacet>     facets     = null;
            List <ProductSearchFacetJson> facetsJson = null;

            if (account == null)
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            else
            {
                #region (Plan A) Get data from local cache

                try
                {
                    facetsJson = (List <ProductSearchFacetJson>)HttpRuntime.Cache[localCacheKey];
                }
                catch (Exception e)
                {
                    var error = e.Message;
                    //TODO: Log: error message for local cache call
                }

                #endregion

                if (facetsJson == null)
                {
                    #region (Plan B) Get Public json from second layer of Redis Cache

                    IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                    string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                    string hashApiKey   = accountNameKey + ":apicache";
                    string hashApiField = pathAndQuery;

                    try
                    {
                        var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                        if (redisApiValue.HasValue)
                        {
                            facetsJson    = JsonConvert.DeserializeObject <List <ProductSearchFacetJson> >(redisApiValue);
                            executionType = ExecutionType.redis_secondary;
                        }
                    }
                    catch
                    {
                    }

                    #endregion

                    if (facetsJson == null)
                    {
                        #region (Plan C) Get data from Redis Cache

                        try
                        {
                            //Attempt to get facets from the Redis Cache

                            string hashKey   = accountNameKey + ":search";
                            string hashField = "facets:products:visible";

                            if (includeHidden)
                            {
                                hashField = "facets:products";
                            }

                            try
                            {
                                var redisValue = cache.HashGet(hashKey, hashField);

                                if (redisValue.HasValue)
                                {
                                    facets        = JsonConvert.DeserializeObject <List <ProductSearchFacet> >(redisValue);
                                    executionType = ExecutionType.redis_main;
                                }
                            }
                            catch
                            {
                            }
                        }
                        catch (Exception e)
                        {
                            var error = e.Message;
                            //Log error message for Redis call
                        }

                        #endregion

                        if (facets == null)
                        {
                            #region (Plan D) Get data from WCF

                            var applicationSearchServiceClient = new ApplicationSearchService.ApplicationSearchServiceClient();

                            try
                            {
                                applicationSearchServiceClient.Open();
                                facets = applicationSearchServiceClient.GetProductFacets(accountNameKey, includeHidden, Common.SharedClientKey).ToList();

                                //Close the connection
                                WCFManager.CloseConnection(applicationSearchServiceClient);

                                executionType = ExecutionType.wcf;
                            }
                            catch (Exception e)
                            {
                                #region Manage Exception

                                string exceptionMessage = e.Message.ToString();

                                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                                // Abort the connection & manage the exception
                                WCFManager.CloseConnection(applicationSearchServiceClient, exceptionMessage, currentMethodString);

                                #endregion
                            }

                            #endregion
                        }
                    }

                    #region  Transform into json object, & cache locally or locally and redisAPI layer

                    if (facetsJson != null)
                    {
                        //Just cache locally (we got json from the api redis layer)
                        HttpRuntime.Cache.Insert(localCacheKey, facetsJson, null, DateTime.Now.AddMinutes(Common.SearchFacetsCacheTimeInMinutes), TimeSpan.Zero);
                    }
                    else if (facets != null)
                    {
                        //Transform categories into JSON and cache BOTH locally AND into redis
                        facetsJson = Transforms.Json.SearchTransforms.ProductFacets(facets);
                        HttpRuntime.Cache.Insert(localCacheKey, facetsJson, null, DateTime.Now.AddMinutes(Common.SearchFacetsCacheTimeInMinutes), TimeSpan.Zero);

                        try
                        {
                            cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(facetsJson), When.Always, CommandFlags.FireAndForget);
                        }
                        catch
                        {
                        }
                    }

                    #endregion
                }
            }



            //Create results object
            ProductSearchFacetsJson facetsJsonResult = new ProductSearchFacetsJson();
            facetsJsonResult.facets = facetsJson;

            //Add execution data
            stopWatch.Stop();
            facetsJsonResult.executionType = executionType.ToString();
            facetsJsonResult.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = facetsJsonResult;

            return(jsonNetResult);
        }
예제 #22
0
        /// <summary>
        /// Called to run/compile/check/prolint the current program
        /// </summary>
        public static void StartProgressExec(ExecutionType executionType, Action <ProExecutionHandleCompilation> execSetter = null)
        {
            CurrentOperation currentOperation;

            if (!Enum.TryParse(executionType.ToString(), true, out currentOperation))
            {
                currentOperation = CurrentOperation.Run;
            }

            // process already running?
            if (OpenedFilesInfo.CurrentOpenedFileInfo.CurrentOperation >= CurrentOperation.Prolint)
            {
                UserCommunication.NotifyUnique("KillExistingProcess", "This file is already being compiled, run or lint-ed.<br>Please wait the end of the previous action,<br>or click the link below to interrupt the previous action :<br><a href='#'>Click to kill the associated prowin process</a>", MessageImg.MsgRip, currentOperation.GetAttribute <CurrentOperationAttr>().Name, "Already being compiled/run", args => {
                    KillCurrentProcess();
                    StartProgressExec(executionType);
                    args.Handled = true;
                }, 5);
                return;
            }
            if (!Npp.CurrentFileInfo.IsProgress)
            {
                UserCommunication.Notify("Can only compile and run progress files!", MessageImg.MsgWarning, "Invalid file type", "Progress files only", 10);
                return;
            }
            if (string.IsNullOrEmpty(Npp.CurrentFileInfo.Path) || !File.Exists(Npp.CurrentFileInfo.Path))
            {
                UserCommunication.Notify("Couldn't find the following file :<br>" + Npp.CurrentFileInfo.Path, MessageImg.MsgError, "Execution error", "File not found", 10);
                return;
            }
            if (!Npp.CurrentFileInfo.IsCompilable)
            {
                UserCommunication.Notify("Sorry, the file extension " + Path.GetExtension(Npp.CurrentFileInfo.Path).Quoter() + " isn't a valid extension for this action!<br><i>You can change the list of valid extensions in the settings window</i>", MessageImg.MsgWarning, "Invalid file extension", "Not an executable", 10);
                return;
            }

            // when running a procedure, check that a .r is not hiding the program, if that's the case we warn the user
            if (executionType == ExecutionType.Run && !_dontWarnAboutRCode)
            {
                if (File.Exists(Path.ChangeExtension(Npp.CurrentFileInfo.Path, ".r")))
                {
                    UserCommunication.NotifyUnique("rcodehide", "Friendly warning, an <b>r-code</b> <i>(i.e. *.r file)</i> is hiding the current program<br>If you modified it since the last compilation you might not have the expected behavior...<br><br><i>" + "stop".ToHtmlLink("Click here to not show this message again for this session") + "</i>", MessageImg.MsgWarning, "Progress execution", "An Rcode hides the program", args => {
                        _dontWarnAboutRCode = true;
                        UserCommunication.CloseUniqueNotif("rcodehide");
                    }, 5);
                }
            }

            // update function prototypes
            ProGenerateCode.Factory.UpdateFunctionPrototypesIfNeeded(true);

            // launch the compile process for the current file
            OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution       = (ProExecutionHandleCompilation)ProExecution.Factory(executionType);
            OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.Files = new List <FileToCompile> {
                new FileToCompile(Npp.CurrentFileInfo.Path)
            };
            OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.OnExecutionEnd += OnSingleExecutionEnd;
            if (execSetter != null)
            {
                execSetter(OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution);
                OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.OnCompilationOk += OnGenerateDebugFileOk;
            }
            else
            {
                OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.OnCompilationOk += OnSingleExecutionOk;
            }
            if (!OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.Start())
            {
                return;
            }

            // change file object current operation, set flag
            OpenedFilesInfo.CurrentOpenedFileInfo.CurrentOperation |= currentOperation;
            OpenedFilesInfo.UpdateFileStatus();

            // clear current errors (updates the current file info)
            OpenedFilesInfo.ClearAllErrors(Npp.CurrentFileInfo.Path, true);
        }
예제 #23
0
        internal JsonNetResult GetProductDetail(string idProperty, string idValue)
        {
            ProductDetailJson productDetailsJson = null;

            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            string localCacheKey = accountNameKey + ":product:" + idProperty + ":" + idValue;


            #region (Plan A) Get json from local cache

            try
            {
                productDetailsJson = (ProductDetailJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (productDetailsJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        productDetailsJson = JsonConvert.DeserializeObject <ProductDetailJson>(redisApiValue);
                        executionType      = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (productDetailsJson == null)
                {
                    #region (Plan C) Get document from Search (No longer: DocumentDB)

                    productDetailsJson = new ProductDetailJson();

                    productDetailsJson.item = DataAccess.Product.GetProductDetail(accountNameKey, idProperty, idValue);

                    #region include parent objects

                    /*
                     * object categoryObject = null;
                     * object subcategoryObject = null;
                     * object subsubcategoryObject = null;
                     * object subsubsubcategoryObject = null;
                     *
                     * productDetailsJson.product.TryGetValue("categoryNameKey", out categoryObject);
                     * productDetailsJson.product.TryGetValue("subcategoryNameKey", out subcategoryObject);
                     * productDetailsJson.product.TryGetValue("subsubcategoryNameKey", out subsubcategoryObject);
                     * productDetailsJson.product.TryGetValue("subsubsubcategoryNameKey", out subsubsubcategoryObject);
                     */

                    if (productDetailsJson.item["categoryNameKey"] != null)
                    {
                        productDetailsJson.category = new CategorizationParentItemJson
                        {
                            name               = productDetailsJson.item["categoryName"].ToString(),
                            nameKey            = productDetailsJson.item["categoryNameKey"].ToString(),
                            fullyQualifiedName = productDetailsJson.item["categoryNameKey"].ToString()
                        };
                    }

                    if (productDetailsJson.item["subcategoryNameKey"] != null)
                    {
                        productDetailsJson.subcategory = new CategorizationParentItemJson
                        {
                            name               = productDetailsJson.item["subcategoryName"].ToString(),
                            nameKey            = productDetailsJson.item["subcategoryNameKey"].ToString(),
                            fullyQualifiedName = productDetailsJson.item["categoryNameKey"].ToString() + "/" + productDetailsJson.item["subcategoryNameKey"].ToString()
                        };
                    }


                    if (productDetailsJson.item["subsubcategoryNameKey"] != null)
                    {
                        productDetailsJson.subsubcategory = new CategorizationParentItemJson
                        {
                            name               = productDetailsJson.item["subsubcategoryName"].ToString(),
                            nameKey            = productDetailsJson.item["subsubcategoryNameKey"].ToString(),
                            fullyQualifiedName = productDetailsJson.item["categoryNameKey"].ToString() + "/" + productDetailsJson.item["subcategoryNameKey"].ToString() + "/" + productDetailsJson.item["subsubcategoryNameKey"].ToString()
                        };
                    }

                    if (productDetailsJson.item["subsubsubcategoryNameKey"] != null)
                    {
                        productDetailsJson.subsubsubcategory = new CategorizationParentItemJson
                        {
                            name               = productDetailsJson.item["subsubsubcategoryName"].ToString(),
                            nameKey            = productDetailsJson.item["subsubsubcategoryNameKey"].ToString(),
                            fullyQualifiedName = productDetailsJson.item["categoryNameKey"].ToString() + "/" + productDetailsJson.item["subcategoryNameKey"].ToString() + "/" + productDetailsJson.item["subsubcategoryNameKey"].ToString() + "/" + productDetailsJson.item["subsubsubcategoryNameKey"].ToString()
                        };
                    }

                    #endregion

                    executionType = ExecutionType.searchIndex;

                    #endregion

                    #region Cache into redisAPI layer

                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(productDetailsJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }

                    #endregion
                }

                #region Cache locally

                HttpRuntime.Cache.Insert(localCacheKey, productDetailsJson, null, DateTime.Now.AddMinutes(Common.ProductCacheTimeInMinutes), TimeSpan.Zero);

                #endregion
            }

            //Add execution data
            stopWatch.Stop();
            productDetailsJson.executionType = executionType.ToString();
            productDetailsJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = productDetailsJson;

            return(jsonNetResult);

            ///Switch to using DocumentDB ----
            ///

            /*
             *
             * //CategoryModel category = null;
             * SearchResults searchResultsObjectJson = null;
             *
             * string localCacheKey = accountNameKey + ":product:" + propertyValue;
             *
             #region (Plan A) Get json from local cache
             *
             * try
             * {
             *  searchResultsObjectJson = (SearchResults)HttpRuntime.Cache[localCacheKey];
             * }
             * catch (Exception e)
             * {
             *  var error = e.Message;
             *  //TODO: Log: error message for local cache call
             * }
             *
             #endregion
             *
             * if (searchResultsObjectJson == null)
             * {
             #region (Plan B) Get Public json from search index
             *
             *  var account = Common.GetAccountObject(accountNameKey);
             *
             *  string filter = "(" + propertyName + " eq '" + propertyValue + "')";
             *
             *  var searchResults = DataAccess.Products.Search(account, null, filter, "relevance", 0, 50, false, null, true);
             *
             #endregion
             *
             #region Transform into json object, add images & cache locally
             *
             *
             *  //Transform categories into JSON and cache locally
             *  searchResultsObjectJson = searchResults;
             *  //searchResultsObjectJson = Transforms.Json.CategorizationTransforms.Category(accountNameKey, category);
             *  HttpRuntime.Cache.Insert(localCacheKey, searchResultsObjectJson, null, DateTime.Now.AddMinutes(Common.SearchResultsCacheTimeInMinutes), TimeSpan.Zero);
             *
             *
             #endregion
             *
             *  executionType = ExecutionType.searchIndex;
             * }
             *
             * //Add execution data
             * stopWatch.Stop();
             * //searchResultsObjectJson.executionType = executionType.ToString();
             * //searchResultsObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";
             *
             * JsonNetResult jsonNetResult = new JsonNetResult();
             * jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
             * jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
             * jsonNetResult.Data = searchResultsObjectJson;
             *
             * return jsonNetResult;*/
        }
예제 #24
0
파일: ProMisc.cs 프로젝트: jcaillon/3P
        /// <summary>
        /// Called to run/compile/check/prolint the current program
        /// </summary>
        public static void StartProgressExec(ExecutionType executionType)
        {
            CurrentOperation currentOperation;
            if (!Enum.TryParse(executionType.ToString(), true, out currentOperation))
                currentOperation = CurrentOperation.Run;

            // process already running?
            if (Plug.CurrentFileObject.CurrentOperation >= CurrentOperation.Prolint) {
                UserCommunication.NotifyUnique("KillExistingProcess", "This file is already being compiled, run or lint-ed.<br>Please wait the end of the previous action,<br>or click the link below to interrupt the previous action :<br><a href='#'>Click to kill the associated prowin process</a>", MessageImg.MsgRip, currentOperation.GetAttribute<CurrentOperationAttr>().Name, "Already being compiled/run", args => {
                    KillCurrentProcess();
                    StartProgressExec(executionType);
                    args.Handled = true;
                }, 5);
                return;
            }
            if (!Abl.IsCurrentProgressFile) {
                UserCommunication.Notify("Can only compile and run progress files!", MessageImg.MsgWarning, "Invalid file type", "Progress files only", 10);
                return;
            }
            if (string.IsNullOrEmpty(Plug.CurrentFilePath) || !File.Exists(Plug.CurrentFilePath)) {
                UserCommunication.Notify("Couldn't find the following file :<br>" + Plug.CurrentFilePath, MessageImg.MsgError, "Execution error", "File not found", 10);
                return;
            }
            if (!Config.Instance.CompileKnownExtension.Split(',').Contains(Path.GetExtension(Plug.CurrentFilePath))) {
                UserCommunication.Notify("Sorry, the file extension " + Path.GetExtension(Plug.CurrentFilePath).ProQuoter() + " isn't a valid extension for this action!<br><i>You can change the list of valid extensions in the settings window</i>", MessageImg.MsgWarning, "Invalid file extension", "Not an executable", 10);
                return;
            }

            // update function prototypes
            ProGenerateCode.UpdateFunctionPrototypesIfNeeded(true);

            // prolint? check that the StartProlint.p program is created, or do it
            if (executionType == ExecutionType.Prolint) {
                if (!File.Exists(Config.FileStartProlint))
                    if (!Utils.FileWriteAllBytes(Config.FileStartProlint, DataResources.StartProlint))
                        return;
            }

            // launch the compile process for the current file
            Plug.CurrentFileObject.ProgressExecution = new ProExecution {
                ListToCompile = new List<FileToCompile> {
                    new FileToCompile(Plug.CurrentFilePath)
                },
                OnExecutionEnd = OnSingleExecutionEnd,
                OnExecutionOk = OnSingleExecutionOk
            };
            if (!Plug.CurrentFileObject.ProgressExecution.Do(executionType))
                return;

            // change file object current operation, set flag
            Plug.CurrentFileObject.CurrentOperation |= currentOperation;
            FilesInfo.UpdateFileStatus();

            // clear current errors (updates the current file info)
            FilesInfo.ClearAllErrors(Plug.CurrentFilePath, true);
        }
        public JsonNetResult Subsubcategory(string categoryNameKey, string subcategoryNameKey, string subsubcategoryNameKey, bool includeHidden = false, bool includeItems = false)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            SubsubcategoryModel       subsubcategory = null;
            SubsubcategoryDetailsJson subsubcategoryDetailsObjectJson = null;

            string localCacheKey = accountNameKey + ":subsubcategory:" + categoryNameKey + ":" + subcategoryNameKey + ":" + subsubcategoryNameKey + ":includeHidden:" + includeHidden + "includeProducts:" + includeItems;


            #region (Plan A) Get json from local cache

            try
            {
                subsubcategoryDetailsObjectJson = (SubsubcategoryDetailsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (subsubcategoryDetailsObjectJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        subsubcategoryDetailsObjectJson = JsonConvert.DeserializeObject <SubsubcategoryDetailsJson>(redisApiValue);
                        executionType = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (subsubcategoryDetailsObjectJson == null)
                {
                    #region (Plan C) Get category data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":categories";
                        string hashMainField = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + ":public";

                        if (includeHidden == true)
                        {
                            hashMainField = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + ":private";
                        }

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                subsubcategory = JsonConvert.DeserializeObject <ApplicationCategorizationService.SubsubcategoryModel>(redisValue);
                                executionType  = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (subsubcategory == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationCategorizationServiceClient = new ApplicationCategorizationService.ApplicationCategorizationServiceClient();

                        try
                        {
                            applicationCategorizationServiceClient.Open();

                            subsubcategory = applicationCategorizationServiceClient.GetSubsubcategoryByNames(accountNameKey, categoryNameKey, subcategoryNameKey, subsubcategoryNameKey, includeHidden, Common.SharedClientKey);

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationCategorizationServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationCategorizationServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (subsubcategoryDetailsObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, subsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (subsubcategory != null)
                {
                    //Transform categories into JSON and cache BOTH locally AND into redis
                    subsubcategoryDetailsObjectJson = Transforms.Json.CategorizationTransforms.Subsubcategory(accountNameKey, subsubcategory, includeItems, includeHidden);
                    HttpRuntime.Cache.Insert(localCacheKey, subsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(subsubcategoryDetailsObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            if (subsubcategoryDetailsObjectJson == null)
            {
                //return empty
                return(new JsonNetResult());
            }

            //Add execution data
            stopWatch.Stop();
            subsubcategoryDetailsObjectJson.executionType = executionType.ToString();
            subsubcategoryDetailsObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = subsubcategoryDetailsObjectJson;

            return(jsonNetResult);
        }
예제 #26
0
        public JsonNetResult Products(string query = "", string filter = null, string orderBy = "relevance", int skip = 0, int take = 50, int top = 50, string locationSort = null, bool includeHidden = false)
        {
            //Alows you to use take and top interchangelbly
            if (top != take && top != 50)
            {
                take = top;
            }

            //We limit TAKEs on the api to 200 for performance purposes
            if (take > 120)
            {
                take = 120;
            }

            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            //CategoryModel category = null;
            SearchResultsJson searchResultsJson = null;
            SearchResults     searchResults     = null;

            string localCacheKey = accountNameKey + ":search:query:" + query + ":filter:" + filter + ":orderby:" + orderBy + ":skip:" + skip + ":take:" + take + ":locationSort:" + locationSort + ":hidden:" + includeHidden;


            #region (Plan A) Get json from local cache

            try
            {
                searchResultsJson = (SearchResultsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (searchResultsJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        searchResultsJson = JsonConvert.DeserializeObject <SearchResultsJson>(redisApiValue);
                        executionType     = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }

                #endregion

                if (searchResultsJson == null)
                {
                    #region (Plan C) Get Public json from search index

                    var account = Common.GetAccountObject(accountNameKey);

                    bool locationSortBool = false;
                    if (locationSort != null)
                    {
                        locationSortBool = true; //geo.distance(foundation, geography'POINT(-118.77975709999998 34.0259216)')
                    }

                    searchResults = DataAccess.Search.SearchProducts(account, query, filter, orderBy, skip, take, locationSortBool, locationSort, includeHidden);

                    #endregion

                    #region Transform into json object, add images

                    //Transform into JSON and cache onto Secondary Cache Layer:
                    searchResultsJson = Transforms.Json.SearchTransforms.ProductResults(searchResults);

                    #endregion

                    try
                    {
                        //Cache on Secondary Cache:
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(searchResultsJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }

                    executionType = ExecutionType.searchIndex;
                }

                //Cache Locally
                HttpRuntime.Cache.Insert(localCacheKey, searchResultsJson, null, DateTime.Now.AddMinutes(Common.SearchResultsCacheTimeInMinutes), TimeSpan.Zero);
            }

            //Add execution data
            stopWatch.Stop();
            searchResultsJson.executionType = executionType.ToString();
            searchResultsJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = searchResultsJson;

            return(jsonNetResult);
        }