Exemplo n.º 1
0
        private ContentResult RejectResult(string reason)
        {
            string xmlString = @"<Response><Reject /></Response>";

            Logging.AddErrorLog($"{nameof(RejectResult)}: {reason} {xmlString}");
            return(this.Content(xmlString, "text/xml"));
        }
Exemplo n.º 2
0
        public static List <BackupProfile> GetAll()
        {
            List <BackupProfile> items = new List <BackupProfile>();

            string backupProfilesFolder = Settings.Current.BackupProfilesFolder;

            CraftSynth.BuildingBlocks.IO.FileSystem.CreateFolderIfItDoesNotExist(backupProfilesFolder);

            string[] fileNames = Directory.GetFiles(backupProfilesFolder, "*.bp");
            foreach (string fileName in fileNames)
            {
                try
                {
                    string        filePath      = Path.Combine(backupProfilesFolder, fileName);
                    string        name          = Path.GetFileNameWithoutExtension(fileName).ToLower();
                    BackupProfile backupProfile = new BackupProfile();
                    backupProfile.Name = name;
                    items.Add(backupProfile);
                }
                catch (Exception exception)
                {
                    Logging.AddErrorLog("ExtensionMacro: Adding of backup profile '" + fileName + "' failed : " + exception.Message);
                    Common.Logging.AddExceptionLog(exception);
                }
            }



            return(items);
        }
Exemplo n.º 3
0
        public static void DumpHeaders(string usedRequestUrl, Dictionary <string, string> dict, string signature, bool Error = true)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append($"UsedRequestUrl={usedRequestUrl}\r\n");
            sb.Append($"Signature={signature}\r\n");
            string requestUrl = Manager.CurrentRequestUrl;

            sb.Append($"RequestUrl={requestUrl}\r\n");
            HttpRequest request = Manager.CurrentRequest;

            foreach (string key in request.Headers.Keys)
            {
                sb.Append($"{key}={request.Headers[key]}\r\n");
            }
            foreach (string key in dict.Keys)
            {
                sb.Append($"dict[{key}]={dict[key]}\r\n");
            }
            if (Error)
            {
                Logging.AddErrorLog(sb.ToString());
            }
            else
            {
                Logging.AddLog(sb.ToString());
            }
        }
Exemplo n.º 4
0
        public static List <Macro> GetNamesAndFilePaths()
        {
            List <Macro> items = new List <Macro>();

            string macrosFolder = Settings.Current.MacrosDataFolder;

            CraftSynth.BuildingBlocks.IO.FileSystem.CreateFolderIfItDoesNotExist(macrosFolder);

            string[] fileNames = Directory.GetFiles(macrosFolder, "*.mcr");
            foreach (string fileName in fileNames)
            {
                try
                {
                    string filePath = Path.Combine(macrosFolder, fileName);
                    string name     = Path.GetFileNameWithoutExtension(fileName).ToLower();
                    Macro  macro    = new Macro();
                    macro.name     = name;
                    macro.filePath = filePath;
                    items.Add(macro);
                }
                catch (Exception exception)
                {
                    Logging.AddErrorLog("ExtensionMacro: Adding of macro '" + fileName + "' failed : " + exception.Message);
                    Common.Logging.AddExceptionLog(exception);
                }
            }
            return(items);
        }
Exemplo n.º 5
0
 private async Task SearchPageAsync(SearchWords searchWords, PageDefinition page)
 {
     if (!searchWords.WantPage(page))
     {
         return;
     }
     if (await searchWords.SetUrlAsync(page.Url, page.PageSecurity, page.Title, page.Description, page.Created, page.Updated, page.IsAuthorized_View_Anonymous(), page.IsAuthorized_View_AnyUser()))
     {
         searchWords.AddKeywords(page.Keywords);
         foreach (var m in page.ModuleDefinitions)
         {
             Guid             modGuid = m.ModuleGuid;
             ModuleDefinition mod     = null;
             try {
                 mod = await ModuleDefinition.LoadAsync(m.ModuleGuid);
             } catch (Exception ex) {
                 Logging.AddErrorLog("An error occurred retrieving module {0} in page {1}", m.ModuleGuid, page.Url, ex);
             }
             if (mod != null)
             {
                 SearchModule(searchWords, mod);
             }
         }
         await searchWords.SaveAsync();
     }
 }
Exemplo n.º 6
0
        //[STAThreadAttribute]
        public static void Main()
        {
            Logging.AddActionLog("Starting Enso+ ...");

            //IsFirstRun = !File.Exists(Settings.FilePath);

            //Not working
            //Application.ThreadException += new ThreadExceptionEventHandler(BuildingBlocks.Exceptions.EnterpriseLibrary.ExceptionHandler.Application_ThreadException);
            Application.ThreadException += Application_ThreadException;

            try
            {
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Count() >= 2)
                {
                    MessageBox.Show("Enso+ is already running.");
                }
                else
                {
                    //Logging.AddActionLog("Starting EnsoPlus.Guard in not running already ...");
                    string ensoPlusGuardExeFilePath = Path.Combine(CraftSynth.BuildingBlocks.Common.Misc.ApplicationRootFolderPath, "EnsoPlus.Guard.exe");
                    CraftSynth.BuildingBlocks.WindowsNT.Misc.OpenFile(ensoPlusGuardExeFilePath);

                    Helper.PreDeleteLogs();

                    if (Settings.Current.firstRun ||
                        !File.Exists(Path.Combine(Common.Helper.GetEnsoPlusWorkingFolder(), "Version.txt")))
                    {
                        Common.HandlerForPreviousVersions.OfferImportingOfSettingsFromPreviousVersion();
                    }

                    if (Settings.Current.firstRun)
                    {
                        Settings.Current.firstRun = false;
                        Settings.Current.Save();
                    }

                    extensionPlus = new EnsoPlus();
                    var mergedCommands = extensionPlus.GetMergedCommands();
                    cornerLauncher = new CornerLauncher(mergedCommands, OnClose);
                    // extensionPlus.OnCommand( mergedCommands[mergedCommands.Keys.Single(k=>k=="open")].sourceCommands[0], string.Empty);
                    ParameterInput.Init();

                    Logging.AddActionLog(string.Format("Started Enso+ {0}", CraftSynth.BuildingBlocks.Common.Misc.version ?? string.Empty));
                    MessagesHandler.Display("Welcome to Enso+");

                    var f = new FormMain();
                    f.Visible = false;
                    f.Width   = 0;
                    f.Height  = 0;
                    Application.Run(f);
                }
            }
            catch (Exception exception)
            {
                Logging.AddErrorLog("Server: Starting failed: " + exception.Message);
                Common.Logging.AddExceptionLog(exception);
            }
        }
Exemplo n.º 7
0
        public static void SaveAllTabs(bool saveInOneFile, Extension.IEnsoService service, string caption, string shortcutsFolder, string commandProviderNameForLog)
        {
            string clipboardText = CraftSynth.BuildingBlocks.IO.Clipboard.GetTextFromClipboard();

            clipboardText = clipboardText.Trim();
            if (string.IsNullOrEmpty(clipboardText))
            {
                MessagesHandler.Display("Error: Clipboard empty.", saveAllTabsUserManual);
            }
            else
            {
                Entities.WorkItems.Shortcuts shortcuts = null;
                try
                {
                    shortcuts = new Entities.WorkItems.Shortcuts(caption, clipboardText);
                    if (shortcuts.shortcuts.Count == 0)
                    {
                        throw new ApplicationException("No urls in clipboard.");
                    }
                }
                catch (Exception)
                {
                    MessagesHandler.Display("Error: Invalid text format in clipboard.", saveAllTabsUserManual);
                    Logging.AddErrorLog(commandProviderNameForLog + ": Error: Invalid text format in clipboard");
                }

                if (shortcuts != null && shortcuts.shortcuts.Count > 0)
                {
                    if (string.IsNullOrEmpty(shortcutsFolder))
                    {
                        shortcutsFolder = Settings.Current.EnsoLearnAsOpenCommandsFolder;
                    }
                    CraftSynth.BuildingBlocks.IO.FileSystem.CreateFolderIfItDoesNotExist(shortcutsFolder);

                    if (saveInOneFile)
                    {
                        shortcuts.Save(shortcutsFolder);
                        SuggestionsCache.DropCache(typeof(WorkItemsProviders.Shortcuts.ShortcutsLists));
                        Logging.AddActionLog(string.Format(commandProviderNameForLog + ": {0} tabs saved in '{1}'.", shortcuts.shortcuts.Count, Path.Combine(shortcutsFolder, caption)));
                        MessagesHandler.Display(string.Format("{0} tabs saved in one shortcut {1}.", shortcuts.shortcuts.Count, caption));
                    }
                    else
                    {
                        shortcuts.SaveAsSeparateShortcuts(shortcutsFolder);
                        Logging.AddActionLog(string.Format(commandProviderNameForLog + ": {0} tabs saved as separate files in '{1}'.", shortcuts.shortcuts.Count, shortcutsFolder));
                        MessagesHandler.Display(string.Format("{0} shortcuts saved in category {1}.", shortcuts.shortcuts.Count, caption));
                    }
                }
            }
        }
        private async Task <ExtUserInfo> GetUserInfo(LoginConfigData config)
        {
            ExtUserInfo info = new ExtUserInfo();

            SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>));
            ExternalLoginInfo loginInfo = await _signinManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logging.AddErrorLog("AuthenticationManager.GetExternalLoginInfoAsync() returned null");
                throw new Error(this.__ResStr("noExtLogin", "No external login has been processed"));
            }
            info.LoginInfo            = loginInfo;
            info.Email                = loginInfo.Principal.FindFirstValue(ClaimTypes.Email);
            info.Name                 = loginInfo.Principal.FindFirstValue(ClaimTypes.Name);
            info.LoginProvider        = loginInfo.LoginProvider;
            info.LoginProviderDisplay = loginInfo.ProviderDisplayName;

            // Check whether this is an invited user
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                List <DataProviderFilterInfo> filters = null;
                switch (config.RegistrationType)
                {
                default:
                case RegistrationTypeEnum.NameAndEmail:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name,
                    });
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email,
                    });
                    break;

                case RegistrationTypeEnum.EmailOnly:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email,
                    });
                    break;

                case RegistrationTypeEnum.NameOnly:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name,
                    });
                    break;
                }
                info.ExistingUser = await dataProvider.GetItemAsync(filters);
            }
            return(info);
        }
Exemplo n.º 9
0
        public async Task SendSMSAsync(string toNumber, string text, string FromNumber)
        {
            TwilioData config = await TwilioConfigDataProvider.GetConfigAsync();

            string accountSid = config.TestMode ? config.TestAccountSid : config.LiveAccountSid;
            string authToken  = config.TestMode ? config.TestAuthToken : config.LiveAuthToken;
            string fromNumber = config.TestMode ? config.TestSMSNumber : config.LiveSMSNumber;

            if (!string.IsNullOrWhiteSpace(FromNumber))
            {
                fromNumber = FromNumber;
            }
            fromNumber = PhoneNumberNationalAttribute.GetE164(fromNumber);
            if (fromNumber == null)
            {
                throw new InternalError($"Invalid fromNumber {fromNumber} - {nameof(SendSMSAsync)}");
            }
            toNumber = PhoneNumberNationalAttribute.GetE164(toNumber);
            if (toNumber == null)
            {
                throw new InternalError($"Invalid toNumber {toNumber} - {nameof(SendSMSAsync)}");
            }
            string callbackUrl = null;

            if (config.DeliveryReceipts)
            {
                callbackUrl = YetaWFManager.Manager.CurrentSite.MakeUrl(
                    Utility.UrlFor(typeof(TwilioResponseController), nameof(TwilioResponseController.Response), new { ValidateToNumber = toNumber }),
                    PagePageSecurity: config.UseHttps?YetaWF.Core.Pages.PageDefinition.PageSecurityType.httpsOnly: YetaWF.Core.Pages.PageDefinition.PageSecurityType.httpOnly
                    );
            }

            TwilioClient.Init(accountSid, authToken);
            MessageResource m = MessageResource.Create(
                from: fromNumber, // From number, must be an SMS-enabled Twilio number
                to: toNumber,
                body: text,
                statusCallback: callbackUrl != null ? new Uri(callbackUrl) : null
                );

            if (m.ErrorCode != null)
            {
                Logging.AddErrorLog("TwilioProcessor SendSMS failed: {0} {1} - {2} - {3}", fromNumber, toNumber, m.ErrorCode, m.ErrorMessage);
            }
            else
            {
                Logging.AddLog("TwilioProcessor SendSMS queued: {0} {1}", fromNumber, toNumber);
            }
        }
Exemplo n.º 10
0
        private IWorkItem PostProcessSelectedSuggestion(IWorkItem selectedSuggestion)
        {
            IWorkItem postProcessedSelectedSuggestion = null;

            try
            {
                postProcessedSelectedSuggestion = selectedSuggestion.GetProvider().GetParameterFromSelectedSuggestion(selectedSuggestion);
            }
            catch (Exception exception)
            {
                MessagesHandler.Display("Selected suggestion postprocess failed", exception.Message);
                Logging.AddErrorLog("Selected suggestion postprocess failed: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                Common.Logging.AddExceptionLog(exception);
                postProcessedSelectedSuggestion = null;
            }
            return(postProcessedSelectedSuggestion);
        }
Exemplo n.º 11
0
 public new ActionResult Response(string ValidateToNumber, string To, string From, string MessageSid, string MessageStatus, string ErrorCode)
 {
     if (ValidateToNumber != To)
     {
         Logging.AddErrorLog("Response from Twilio: Invalid (to number doesn't match) - {0}", Manager.CurrentRequestUrl);
     }
     else
     {
         if (ErrorCode != "0")
         {
             Logging.AddErrorLog("Response from Twilio: {0} {1} {2} {3} {4} {5}", From, To, ErrorCode, MessageStatus, MessageSid, Manager.CurrentRequestUrl);
         }
         else
         {
             Logging.AddLog("Response from Twilio: {0} {1} {2} {3} {4} {5}", From, To, ErrorCode, MessageStatus, MessageSid, Manager.CurrentRequestUrl);
         }
     }
     return(new EmptyResult());
 }
Exemplo n.º 12
0
 private void ExecuteCommandCandidate(Command bestCandidateForUsedCommand)
 {
     try
     {
         if (bestCandidateForUsedCommand.Name != "repeat")
         {
             WorkItemsProviders.CommandsHistory.CommandsHistory.Add(bestCandidateForUsedCommand);
         }
         bestCandidateForUsedCommand.Execute(service);
     }
     catch (Exception exception)
     {
         MessagesHandler.Display("Command execution failed", exception.Message);
         Logging.AddErrorLog("Command execution failed: " + exception.Message +
                             ((exception.InnerException != null)? ":" + exception.InnerException.Message + ((exception.InnerException.InnerException != null)? ":" + exception.InnerException.InnerException.Message: ""): "")
                             );
         Common.Logging.AddExceptionLog(exception);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Builds the current site from the zip files in the Data folder
        /// </summary>
        /// <param name="includeNonSiteSpecifics"></param>
        public async Task BuildSiteUsingDataAsync(bool includeNonSiteSpecifics, List <Package> installedPackages = null)
        {
            Manager.ImportChunksNonSiteSpecifics = includeNonSiteSpecifics;
            List <string> files = await FileSystem.FileSystemProvider.GetFilesAsync(Path.Combine(TemplateFolder, DataFolderName), "*.zip");

            foreach (string file in files)
            {
                if (installedPackages == null || (from p in installedPackages where file.Contains($"{p.Name}.") select p).Any())
                {
                    List <string> errorList = new List <string>();
                    Logging.AddLog("Restoring {0}", file);
                    if (!await Package.ImportDataAsync(file, errorList))
                    {
                        Logging.AddErrorLog($"Error restoring {file} - {errorList.First()}");
                        //throw new Error(errorList.First());
                    }
                }
            }
            Manager.ImportChunksNonSiteSpecifics = false;
            await Resource.ResourceAccess.ShutTheBackDoorAsync();
        }
Exemplo n.º 14
0
        private Dictionary <string, IWorkItem> GetAvailableSuggestions(Command bestCandidateForUsedCommand)
        {
            MessagesHandler.Display("Retrieving suggestions. Please wait...");
            Dictionary <string, IWorkItem> suggestions = new Dictionary <string, IWorkItem>();

            foreach (Type supportedParameterTypeProvider in bestCandidateForUsedCommand.supportedParameterTypeProviders)
            {
                try
                {
                    Application.DoEvents();
                    IWorkItemsProvider ptp = Assembly.GetExecutingAssembly().CreateInstance(supportedParameterTypeProvider.FullName) as IWorkItemsProvider;
                    foreach (KeyValuePair <string, IWorkItem> kv in SuggestionsCache.Get(ptp))
                    {
                        IWorkItem existingWorkItemWithSameName = null;
                        if (suggestions.TryGetValue(kv.Key, out existingWorkItemWithSameName))
                        {
                            string message = string.Format("Can't add item '{0}' from provider '{1}' because item with same name allready loaded from provider {2}.",
                                                           kv.Key,
                                                           kv.Value.GetProvider().GetType().Name,
                                                           existingWorkItemWithSameName.GetProvider().GetType().Name);
                            Logging.AddErrorLog(message);
                            //MessagesHandler.Display(message);
                        }
                        else
                        {
                            suggestions.Add(kv.Key, kv.Value);
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessagesHandler.Display("Error occured while retriving suggestions", exception.Message);
                    Logging.AddErrorLog("Error occured while retriving suggestions: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                    Common.Logging.AddExceptionLog(exception);
                }
            }
            MessagesHandler.HideAllMessages();
            return(suggestions);
        }
Exemplo n.º 15
0
        public static List <Contact> GetContacts()
        {
            List <Contact> contacts = new List <Contact>();

            try
            {
                string contactsFilePath = Settings.Current.CallerE61ContactsFilePath;
                CraftSynth.BuildingBlocks.IO.FileSystem.CreateFileIfItDoesNotExist(contactsFilePath);
                if (!File.Exists(contactsFilePath))
                {
                    throw new ApplicationException("File not found:" + contactsFilePath);
                }


                string[] lines = File.ReadAllLines(contactsFilePath);

                Entry entry = new Entry();
                foreach (string line in lines)
                {
                    if (string.IsNullOrEmpty(line))
                    {
                        if (entry != null)
                        {
                            foreach (var detailKey in entry.details.Keys)
                            {
                                if (entry.caption.EndsWith(", "))
                                {
                                    entry.caption = entry.caption.Remove(entry.caption.LastIndexOf(", "));
                                }
                                string caption = string.Format("{0} ({1}:{2})", entry.caption, detailKey, entry.details[detailKey]);
                                contacts.Add(new Contact(caption, entry.details[detailKey]));
                            }
                        }
                        entry = new Entry();
                    }
                    else
                    {
                        string[] lineSides = line.Split(':');
                        lineSides[0] = lineSides[0].Trim();
                        lineSides[1] = lineSides[1].Trim();
                        if (!string.IsNullOrEmpty(lineSides[0]) && !string.IsNullOrEmpty(lineSides[1]))
                        {
                            if (lineSides[0].Contains("phone") ||
                                lineSides[0].Contains("mobile") ||
                                lineSides[0].Contains("email")
                                )
                            {
                                entry.details.Add(lineSides[0], lineSides[1]);
                            }
                            else
                            {
                                entry.caption += string.Format("{0}, ", lineSides[1]);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logging.AddErrorLog("ExtensionCaller: SourceNokiaE61.GetContacts failed : " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                Common.Logging.AddExceptionLog(exception);
            }

            return(contacts);
        }
Exemplo n.º 16
0
        public async Task ResolveUserAsync()
        {
            if (!Manager.HaveCurrentRequest)
            {
                throw new InternalError("No httpRequest");
            }

            // check whether we have a logged on user
#if MVC6
            if (SiteDefinition.INITIAL_INSTALL || !Manager.CurrentContext.User.Identity.IsAuthenticated)
#else
            if (SiteDefinition.INITIAL_INSTALL || !Manager.CurrentRequest.IsAuthenticated)
#endif
            {
                return;// no user logged in
            }
            // get user info and save in Manager
            string userName = Manager.CurrentContext.User.Identity.Name;
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                if (!await userDP.IsInstalledAsync())
                {
                    Logging.AddErrorLog("UserDefinitionDataProvider not installed");
                    return;
                }
                UserDefinition user = await userDP.GetItemAsync(userName);

                if (user == null)
                {
                    Logging.AddErrorLog("Authenticated user {0} doesn't exist", userName);
#if DEBUG
                    //throw new InternalError("Authenticated user doesn't exist");
#endif
                    return;
                }
                // Check whether user needs to set up two-step authentication
                // External login providers don't require local two-step authentication (should be offered by external login provider)
                // If any of the user's roles require two-step authentication and the user has not enabled two-step authentication providers,
                // set marker so we can redirect the user
                if (Manager.Need2FAState == null)
                {
                    Manager.Need2FAState = false;
                    using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                        if (!await logInfoDP.IsExternalUserAsync(user.UserId))
                        {
                            // not an external login, so check if we need two-step auth
                            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                            if (config.TwoStepAuth != null && user.RolesList != null)
                            {
                                foreach (Role role in config.TwoStepAuth)
                                {
                                    if (role.RoleId == Resource.ResourceAccess.GetUserRoleId() || user.RolesList.Contains(new Role {
                                        RoleId = role.RoleId
                                    }, new RoleComparer()))
                                    {
                                        if ((await user.GetEnabledAndAvailableTwoStepAuthenticationsAsync()).Count == 0)
                                        {
                                            Manager.Need2FAState = true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                // Check whether the user needs to change the password
                Manager.NeedNewPassword = user.NeedsNewPassword;

                // user good to go
                Manager.UserName   = user.UserName;
                Manager.UserEmail  = user.Email;
                Manager.UserId     = user.UserId;
                Manager.UserObject = user;
                await UserSettings.UserSettingsAccess.ResolveUserAsync();

                Manager.UserRoles = (from l in user.RolesList select l.RoleId).ToList();

                int superuserRole = Resource.ResourceAccess.GetSuperuserRoleId();
                if (user.RolesList.Contains(new Role {
                    RoleId = superuserRole
                }, new RoleComparer()))
                {
                    Manager.SetSuperUserRole(true);
                }
            }
        }
Exemplo n.º 17
0
        private async Task <ActionResult> RunEntryAsync(IVRConfig ivrConfig, ScriptData script, string called, string extension, ScriptEntry entry, int errCount)
        {
            string extensionName   = null;
            string extensionSpaced = null;

            if (!string.IsNullOrWhiteSpace(extension))
            {
                extensionSpaced = Spaced(extension);
                Extension e = script.FindExtension(extension);
                if (e != null)
                {
                    extensionName = e.Name;
                }
            }
            string digits;

            TryGetForm("Digits", out digits);

            string actionUrl = Utility.UrlFor(typeof(CallController), nameof(Process));

#if DEBUG
            actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.Any);
#else
            actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.httpsOnly);
#endif

            string token = DateTime.UtcNow.Ticks.ToString();
            string encryptedToken;
            RSACrypto.Encrypt(ivrConfig.PublicKey, token, out encryptedToken);

            object parms = new {
                Url             = actionUrl,
                Caller          = GetForm("Caller"),
                CallerSpaced    = Spaced(GetForm("Caller").TruncateStart("+1")),
                CallerCity      = GetForm("CallerCity"),
                CallerCountry   = GetForm("CallerCountry"),
                Digits          = digits,
                Extension       = extension,
                ExtensionSpaced = extensionSpaced,
                ExtensionName   = extensionName,
                ErrCount        = errCount,
                ErrCountPlus1   = errCount + 1,
                Token           = encryptedToken,
                Voice           = ivrConfig.Voice,
                VoiceInternal   = ivrConfig.VoiceInternal,
            };

            string    text = entry.Text;
            Variables vars = new Variables(Manager, parms)
            {
                EncodingType = Variables.EncodingTypeEnum.XML
            };

            Extension ext = script.FindExtension(digits);
            if (ext != null)
            {
                text = RepeatableNumbers(ext, text);
            }

            if (text.Contains("RECORDVOICEMAIL"))
            {
                text = text.Replace("RECORDVOICEMAIL", "");
                VoiceMailData voiceMail;
                using (VoiceMailDataProvider voiceMailDP = new VoiceMailDataProvider()) {
                    voiceMail = new VoiceMailData {
                        Caller        = GetForm("Caller").Truncate(Globals.MaxPhoneNumber),
                        CallerCity    = GetForm("CallerCity").Truncate(VoiceMailData.MaxCity),
                        CallerState   = GetForm("CallerState").Truncate(VoiceMailData.MaxState),
                        CallerZip     = GetForm("CallerZip").Truncate(VoiceMailData.MaxZip),
                        CallerCountry = GetForm("CallerCountry").Truncate(VoiceMailData.MaxCountry),
                        CallSid       = GetForm("CallSid"),
                        RecordingSid  = GetForm("RecordingSid"),
                        Duration      = ConvertToInt(GetForm("RecordingDuration")),
                        To            = called,
                        Extension     = extension,
                        RecordingUrl  = GetForm("RecordingUrl").Truncate(Globals.MaxUrl)
                    };
                    if (!await voiceMailDP.AddItemAsync(voiceMail))
                    {
                        Logging.AddErrorLog($"Couldn't record voice mail status for call from {GetForm("Caller")}");
                    }
                }
                if (!string.IsNullOrWhiteSpace(extension))
                {
                    ext = script.FindExtension(extension);
                    if (ext != null)
                    {
                        DisplayVoiceMailModule dispMod = (DisplayVoiceMailModule)await ModuleDefinition.LoadAsync(ModuleDefinition.GetPermanentGuid(typeof(DisplayVoiceMailModule)));

                        ModuleAction displayAction = await dispMod.GetAction_DisplayAsync(null, voiceMail.Id);

                        if (displayAction != null)
                        {
                            string viewUrl = displayAction.GetCompleteUrl();
                            foreach (ExtensionNumber extNumber in ext.Numbers)
                            {
                                if (extNumber.SendSMSVoiceMail)
                                {
                                    SendSMS sendSMS = new SendSMS();
                                    await sendSMS.SendMessageAsync(extNumber.Number,
                                                                   this.__ResStr("voiceSMS", "A voice mail was received for extension {0} ({1}) from {2}, {3}, {4}, {5} {6} - {7}",
                                                                                 extension, GetForm("To"), GetForm("Caller"), GetForm("CallerCity"), GetForm("CallerState"), GetForm("CallerZip"), GetForm("CallerCountry"),
                                                                                 viewUrl),
                                                                   ThrowError : false);
                                }
                            }
                        }
                    }
                }
            }

            text = vars.ReplaceVariables(text);
            Logging.AddLog($"{nameof(RunEntryAsync)}: {text}");
            return(Content(text, "text/xml"));
        }
Exemplo n.º 18
0
        private async Task <List <Package> > InstallPackagesAsync(List <string> wantedPackages)
        {
            Logging.AddLog("Installing packages");

            // get all packages that are available
            List <Package> allPackages = Package.GetAvailablePackages();
            // get packages to install, limit to wanted packages
            List <Package> remPackages = allPackages.ToList();

            if (wantedPackages != null)
            {
                remPackages = (from p in remPackages where wantedPackages.Contains(p.Name) select p).ToList();
            }
            // add all required dependencies from packages even if they were not initially wanted
            foreach (Package remPackage in remPackages.ToList())
            {
                AddDependencies(remPackages, remPackage);
            }

            // order all available packages by service level
            remPackages = (from p in remPackages orderby(int) p.ServiceLevel select p).ToList();

            // keep track of installed packages
            List <Package> installedPackages = new List <Package>();
            List <Package> remainingPackages = (from p in remPackages select p).ToList();

            // check each package and install it if all dependencies are available
            for ( ; remPackages.Count() > installedPackages.Count();)
            {
                int count = 0;

                foreach (Package package in remPackages)
                {
                    List <string> errorList = new List <string>();

                    if (!installedPackages.Contains(package))
                    {
                        Logging.AddLog("Installing package {0}", package.Name);
                        if (ArePackageDependenciesInstalled(package, installedPackages))
                        {
                            if (!await package.InstallModelsAsync(errorList))
                            {
                                ScriptBuilder sb = new ScriptBuilder();
                                sb.Append(this.__ResStr("cantInstallPackage", "Can't install package {0}:(+nl)"), package.Name);
                                sb.Append(errorList, LeadingNL: true);
                                throw new Error(sb.ToString());
                            }
                            ++count;
                            installedPackages.Add(package);
                            remainingPackages.Remove(package);
                        }
                    }
                }
                if (count == 0)   // we didn't install any additional packages
                {
                    Logging.AddErrorLog("Not all packages could be installed");
                    foreach (Package package in remainingPackages)
                    {
                        List <string> reqPackages = package.GetRequiredPackages();
                        Logging.AddErrorLog($"Package {package.Name} not installed - Requires {string.Join(", ", reqPackages)}");
                        foreach (string dep in reqPackages)
                        {
                            if (!(from p in installedPackages where p.Name == dep select p).Any())
                            {
                                Logging.AddErrorLog($"  Package dependency {dep} not installed and is required by {package.Name}");
                            }
                        }
                    }
                    throw new InternalError("Not all packages could be installed");
                }
            }
            return(installedPackages);
        }
Exemplo n.º 19
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                throw new Error(this.__ResStr("extErr", "The external login provider reported this error: {0}", remoteError));
            }

            SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>));
            ExternalLoginInfo loginInfo = await _signinManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logging.AddErrorLog("AuthenticationManager.GetExternalLoginInfoAsync() returned null");
                return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
            }
            using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                List <LoginConfigDataProvider.LoginProviderDescription> loginProviders = await logConfigDP.GetActiveExternalLoginProvidersAsync();

                if ((from l in loginProviders where l.InternalName == loginInfo.LoginProvider select l).FirstOrDefault() == null)
                {
                    Logging.AddErrorLog("Callback from external login provider {0} which is not active", loginInfo.LoginProvider);
                    return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
                }
            }

            // get our registration defaults
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            // Sign in the user with this external login provider if the user already has a login
            UserDefinition user = await Managers.GetUserManager().FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);

            if (user == null)
            {
                // If the user does not have an account, then prompt the user to create an account
                // we will go to a page where the user can set up a local account
                Manager.OriginList = new List <Origin>();
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    Manager.OriginList.Add(new Origin()
                    {
                        Url = returnUrl
                    });                                                      // where to go after setup
                }
                Manager.OriginList.Add(new Origin()
                {
                    Url = Helper.GetSafeReturnUrl(Manager.CurrentSite.ExternalAccountSetupUrl)
                });                                                                                                                  // setup
                return(Redirect(Manager.ReturnToUrl));
            }

            if (string.IsNullOrWhiteSpace(returnUrl) && Manager.HaveReturnToUrl)
            {
                returnUrl = Manager.ReturnToUrl;
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Manager.CurrentSite.PostLoginUrl;
            }
            returnUrl = Helper.GetSafeReturnUrl(returnUrl);

            // determine what to do based on account status
            if (user.UserStatus == UserStatusEnum.Approved)
            {
                await LoginModuleController.UserLoginAsync(user);

                Logging.AddLog("User {0} - logged on", user.UserName);
                returnUrl = QueryHelper.AddRando(returnUrl); // to defeat client-side caching
                return(Redirect(returnUrl));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - rejected user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.RejectedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been rejected by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.RejectedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - suspended user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.SuspendedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been suspended by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.SuspendedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet validated", user.UserName);
                if (string.IsNullOrWhiteSpace(config.VerificationPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Once received, please use the information in the email to complete the registration."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.VerificationPendingUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet approved", user.UserName);
                if (string.IsNullOrWhiteSpace(config.ApprovalPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notApproved", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.ApprovalPendingUrl)));
            }
            else
            {
                await LoginModuleController.UserLogoffAsync();

                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
Exemplo n.º 20
0
        public void ExecuteCommand(Extension.IEnsoService service, Command command)
        {
            Logging.AddActionLog(string.Format("FileManager: Executing command '{0}' ...", command.Name));

            if (command.Name == "copy to" || command.Name == "move to")
            {
                string selectedPath = service.GetUnicodeSelection();
                if (string.IsNullOrEmpty(selectedPath))
                {
                    selectedPath = service.GetFileSelection()[0];
                }

                if (string.IsNullOrEmpty(selectedPath))
                {
                    MessagesHandler.Display("Nothing is selected therefore no destination path.");
                    Logging.AddErrorLog("FileManager: Nothing is selected therefore no destination path.");
                }
                else
                {
                    try
                    {
                        string destinationPath = Path.Combine(command.parametersOnExecute[0].GetValueAsText(), Path.GetFileName(selectedPath));

                        if (command.Name == "copy to")
                        {
                            Logging.AddActionLog(string.Format("FileManager: Copying '{0}' to {1} ...", selectedPath, command.parametersOnExecute[0].GetValueAsText()));
                            CraftSynth.BuildingBlocks.IO.FileSystem.CopyFileOrFolder(selectedPath, command.parametersOnExecute[0].GetValueAsText());
                            if (CraftSynth.BuildingBlocks.IO.FileSystem.FileOrFolderExist(destinationPath))
                            {
                                Logging.AddActionLog("FileManager: Copied.");
                                MessagesHandler.Display("Copied.");
                            }
                            else
                            {
                                string errorMessage = string.Format("Destination file/folder '{0}' does not exist after copy operation.", destinationPath);
                                Logging.AddErrorLog(string.Format("FileManager: {0}", errorMessage));
                                MessagesHandler.Display(errorMessage);
                            }
                        }
                        else
                        if (command.Name == "move to")
                        {
                            Logging.AddActionLog(string.Format("FileManager: Moving '{0}' to {1} ...", selectedPath, command.parametersOnExecute[0].GetValueAsText()));
                            CraftSynth.BuildingBlocks.IO.FileSystem.MoveFileOrFolder(selectedPath, command.parametersOnExecute[0].GetValueAsText());
                            if (CraftSynth.BuildingBlocks.IO.FileSystem.FileOrFolderDoesNotExist(destinationPath))
                            {
                                string errorMessage = string.Format("Destination file/folder '{0}' does not exist after move operation.", destinationPath);
                                Logging.AddErrorLog(string.Format("FileManager: {0}", errorMessage));
                                MessagesHandler.Display(errorMessage);
                            }
                            else if (CraftSynth.BuildingBlocks.IO.FileSystem.FileOrFolderExist(selectedPath))
                            {
                                string errorMessage = string.Format("Destination file/folder '{0}' still exist after move operation.", destinationPath);
                                Logging.AddErrorLog(string.Format("FileManager: {0}", errorMessage));
                                MessagesHandler.Display(errorMessage);
                            }
                            else
                            {
                                Logging.AddActionLog("FileManager: Moved.");
                                MessagesHandler.Display("Moved.");
                            }
                        }
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        Logging.AddErrorLog(string.Format("FileManager: File not found: {0}", command.parametersOnExecute[1].GetValueAsText()));
                        MessagesHandler.Display("File not found.", command.parametersOnExecute[1].GetValueAsText());
                    }
                    catch (System.IO.DirectoryNotFoundException)
                    {
                        Logging.AddErrorLog(string.Format("FileManager: Folder not found: {0}", command.parametersOnExecute[1].GetValueAsText()));
                        MessagesHandler.Display("Folder not found.", command.parametersOnExecute[1].GetValueAsText());
                    }
                    catch (Exception exception)
                    {
                        Logging.AddErrorLog(string.Format("FileManager: {0}", exception.Message));
                        MessagesHandler.Display(exception.Message);
                    }
                }
            }
            else
            if (command.Name == "empty")
            {
                string path = command.parametersOnExecute[0].GetValueAsText();
                Logging.AddActionLog(string.Format("FileManager: Emptying '{0}' ...", path));

                bool isFolder = true;
                if (File.Exists(path) && !Directory.Exists(path))
                {
                    isFolder = false;
                }
                else
                if (!File.Exists(path) && Directory.Exists(path))
                {
                    isFolder = true;
                }

                try
                {
                    Logging.AddActionLog(string.Format("FileManager:   Deleting '{0}' ...", path));
                    CraftSynth.BuildingBlocks.IO.FileSystem.DeleteFileOrFolder(path, false);

                    if (!isFolder)
                    {
                        Logging.AddActionLog(string.Format("FileManager:   Creating '{0}' ...", path));
                        File.Create(path);
                    }
                    else
                    {
                        Logging.AddActionLog(string.Format("FileManager:   Creating '{0}' ...", path));
                        Directory.CreateDirectory(path);
                    }

                    Logging.AddActionLog("FileManager: Contents deleted.");
                    MessagesHandler.Display("Contents deleted.");
                }
                catch (System.IO.FileNotFoundException)
                {
                    Logging.AddErrorLog(string.Format("FileManager: File not found: {0}", command.parametersOnExecute[1].GetValueAsText()));
                    MessagesHandler.Display("File not found.", command.parametersOnExecute[1].GetValueAsText());
                }
                catch (System.IO.DirectoryNotFoundException)
                {
                    Logging.AddErrorLog(string.Format("FileManager: Folder not found: {0}", command.parametersOnExecute[1].GetValueAsText()));
                    MessagesHandler.Display("Folder not found.", command.parametersOnExecute[1].GetValueAsText());
                }
                catch (Exception exception)
                {
                    //if operation failed but item is empty report success
                    if (!isFolder && File.Exists(path))
                    {
                        FileInfo fileInfo = new FileInfo(path);
                        if (fileInfo.Length == 0)
                        {
                            exception = null;
                        }
                    }
                    else if (Directory.Exists(path))
                    {
                        if (CraftSynth.BuildingBlocks.IO.FileSystem.GetFilePaths(path).Count == 0 && CraftSynth.BuildingBlocks.IO.FileSystem.GetFolderPaths(path).Count == 0)
                        {
                            exception = null;
                        }
                    }

                    if (exception == null)
                    {
                        Logging.AddActionLog("FileManager: Contents deleted.");
                        MessagesHandler.Display("Contents deleted.");
                    }
                    else
                    {
                        Logging.AddErrorLog(string.Format("FileManager: {0}", exception.Message));
                        MessagesHandler.Display(exception.Message);
                    }
                }
            }
            else
            if ((command.Name == "save" && command.Postfix == "[what] to") ||
                (command.Name == "save" && command.Postfix == "[what] and copy its file path"))
            {
                ParameterizedThreadStart ts = new ParameterizedThreadStart(ProcessCommand);
                clipboardHost = new Thread(ts);
                clipboardHost.SetApartmentState(ApartmentState.STA);
                KeyValuePair <IEnsoService, Command> parameters = new KeyValuePair <IEnsoService, Command>(service, command);
                clipboardHost.Start(parameters);
                clipboardHost.Join();
            }
            else
            if (command.Name == "copy file content as text")
            {
                string filePath = command.parametersOnExecute[0].GetValueAsText();
                string content  = File.ReadAllText(filePath);
                if (string.Empty == (content.Trim()))
                {
                    MessagesHandler.Display(string.Format("File is empty.", filePath));
                }
                else
                {
                    CraftSynth.BuildingBlocks.IO.Clipboard.SetTextToClipboard(content);

                    //content = BuildingBlocks.DataAccess.Clipboard.Helper.GetTextFromClipboard();
                    string message = content.Substring(0, (content.Length <= 200) ? content.Length : 200);
                    if (content.Length > 200)
                    {
                        message = message + "...";
                    }

                    try
                    {
                        MessagesHandler.Display(message, string.Format("{0} characters on clipboard", content.Length));
                    }
                    catch
                    {
                        MessagesHandler.Display(string.Format("Copied {0} characters.", content.Length));
                    }
                }
            }

            //    else
            //        if (command.Name == "command name" && command.Postfix == "postfix [item] [item2]")
            //        {
            //            MessagesHandler.Display( string.Format("Executing {0} ...", command.Name));

            //        }
            else
            {
                throw new ApplicationException(string.Format("FileManager: Command not found. Command: {0} {1}", command.Name, command.Postfix));
            }
        }
Exemplo n.º 21
0
        public void OnCommand(EnsoCommand ensoCommand, string postfix, IntPtr foregroundWindowForGrab)
        {
            Logging.AddDebugLog("OnCommand:" + ensoCommand.Name + " postfix:" + postfix + "------------------------------------------------------------------------------------------------");
            try
            {
                //SelectionListener.Listener.Current.IfOpenedPause();

                MergedCommand mergedCommand = this.mergedCommands[ensoCommand.Name];

                //if none of potentially chosen commands use selection skip expensive operations:
                //  this.service.GetFileSelection() and/or this.service.GetUnicodeSelection();
                bool skipGetUnicodeSelection = true;
                bool skipGetFileSelection    = true;
                foreach (var sourceCommand in mergedCommand.sourceCommands)
                {
                    if (sourceCommand.canUseTextSelectionForParameter)
                    {
                        skipGetUnicodeSelection = false;
                    }

                    if (sourceCommand.canUseFileSelectionForParameter)
                    {
                        skipGetFileSelection = false;
                    }

                    if (!skipGetUnicodeSelection && !skipGetFileSelection)
                    {
                        break;
                    }
                }
                Logging.AddDebugLog("OnCommand: skipGetUnicodeSelection=" + skipGetUnicodeSelection + " skipGetFilesSelection=" + skipGetFileSelection);

                //do we need file selection?
                if ((ensoCommand.Name == "topen" || ensoCommand.Name == "rtopen" || ensoCommand.Name == "empty"))
                {
                    try
                    {
                        if (CraftSynth.BuildingBlocks.WindowsNT.Misc.GetForegroundWindowCaption().Contains("Total Commander"))
                        {
                            skipGetFileSelection = true;
                        }
                    }
                    catch
                    {
                    }
                }

                //read selection
                ClipboardData selectedData = null;
                if (!skipGetUnicodeSelection || !skipGetFileSelection)
                {
                    selectedData = HandlerForSelection.Get(foregroundWindowForGrab);
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of HandlerForSelection.Get=" + (selectedData == null?"null":selectedData.AsUnicodeText).FirstXChars(100, "..."));

                //Get text selection if needed
                string selectedText = null;
                if (!skipGetUnicodeSelection && selectedData != null)
                {
                    selectedText = selectedData.AsUnicodeText;
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of selectedText=" + (selectedText ?? "null").FirstXChars(100, "..."));

                //Get file selection if needed
                string[] fileSelectionArray = null;
                if (!skipGetFileSelection &&
                    !skipGetUnicodeSelection && string.IsNullOrEmpty(selectedText) && selectedData != null)
                {
                    var ffl = selectedData.AsFileFolderList;
                    if (ffl == null)
                    {
                        fileSelectionArray = null;
                    }
                    else
                    {
                        fileSelectionArray = ffl.ToArray();
                    }
                    ;     //ex: this.service.GetFileSelection();
                }
                else
                {
                    fileSelectionArray = new string[] { };
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of fileSelectionArray=" + (fileSelectionArray == null? "null": Syntax.FileSelectionArrayToString(fileSelectionArray)).FirstXChars(100, "..."));

                if (fileSelectionArray != null && fileSelectionArray.Length > 0 && string.IsNullOrEmpty(selectedText))
                {
                    selectedText = Syntax.FileSelectionArrayToString(fileSelectionArray);
                }

                Command bestCandidateForUsedCommand = null;
                bool    bestCandidateForUsedCommandRequiresParameterInput = false;
                foreach (Command sourceCommand in mergedCommand.sourceCommands)
                {
                    Logging.AddDebugLog("OnCommand: Syntax.ExtractParameterValues...");
                    int           parameterCountInSyntax      = 0;
                    List <string> parametersFromInlineCommand = Syntax.ExtractParameterValues(sourceCommand.Postfix, postfix, (GetSelectionForCommand(selectedText, sourceCommand)), mergedCommand.sourceCommands.Count == 1, out parameterCountInSyntax);

                    Logging.AddDebugLog("OnCommand: parametersFromInlineCommand=" + (parametersFromInlineCommand == null?"null":parametersFromInlineCommand.ToCSV()));
                    if (parametersFromInlineCommand == null)
                    {
                        continue;
                    }

                    //replace jockers - should be refactored
                    Logging.AddDebugLog("OnCommand: replace jockers...");
                    int i = parametersFromInlineCommand.Count - 1;
                    while (i >= 0)
                    {
                        if (parametersFromInlineCommand[i] == Syntax.lastMessageInPostfix)
                        {
                            parametersFromInlineCommand[i] = MessagesHandler.GetLastFromHistory().Text;
                        }
                        else if (parametersFromInlineCommand[i] == Syntax.selectionInPostfix1 || parametersFromInlineCommand[i] == Syntax.selectionInPostfix2)
                        {
                            parametersFromInlineCommand.RemoveAt(i);
                        }
                        i--;
                    }
                    Logging.AddDebugLog("OnCommand: Determine best candidate...");

                    if ((GetSelectionForCommand(selectedText, sourceCommand) == string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax) ||
                        (parameterCountInSyntax == 0 && sourceCommand.Postfix == " ") ||
                        (GetSelectionForCommand(selectedText, sourceCommand) != string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax && GetSelectionForCommand(selectedText, sourceCommand).CompareTo(parametersFromInlineCommand[parametersFromInlineCommand.Count - 1]) == 0))
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = false;
                        Logging.AddDebugLog("OnCommand: bc=a");
                        break;
                    }
                    else if (GetSelectionForCommand(selectedText, sourceCommand) != string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax && GetSelectionForCommand(selectedText, sourceCommand).CompareTo(parametersFromInlineCommand[parametersFromInlineCommand.Count - 1]) != 0)
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = false;
                        Logging.AddDebugLog("OnCommand: bc=b");
                    }
                    else if (parametersFromInlineCommand.Count == (parameterCountInSyntax - 1))
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = true;
                        Logging.AddDebugLog("OnCommand: bc=c");
                    }
                }



                if (bestCandidateForUsedCommand == null)
                {
                    Logging.AddDebugLog("OnCommand: postfix Invalid!");
                    MessagesHandler.Display("Postfix invalid!", ensoCommand.Name + " " + ensoCommand.Postfix);
                }
                else
                {
                    Logging.AddDebugLog("OnCommand: bestCandidateForUsedCommand=" + bestCandidateForUsedCommand.Name);
                    Logging.AddDebugLog("OnCommand: replace 'last' parameter with last used parameter/WorkItem");
                    //replace 'last' parameter with last used parameter/WorkItem
                    int j = 0;
                    while (j < bestCandidateForUsedCommand.parametersOnExecute.Count)
                    {
                        Logging.AddDebugLog("OnCommand: first 100 chars of paramsOnExecute[" + j + "]=" + (bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText().FirstXChars(100, "...")));
                        if (bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText() == Syntax.lastParameterInPostfix)
                        {
                            bestCandidateForUsedCommand.parametersOnExecute[j] = WorkItemsProviders.CommandsHistory.CommandsHistory.GetLastWorkItem();
                            Logging.AddDebugLog("OnCommand: first 100 chars of paramsOnExecute[" + j + "]=" + bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText().FirstXChars(100, "..."));
                        }

                        j++;
                    }

                    if (bestCandidateForUsedCommand.parameterInputArguments.acceptOnlySuggested && !bestCandidateForUsedCommandRequiresParameterInput && bestCandidateForUsedCommand.parametersOnExecute.Count > 0)
                    {//user entered all parameters and command uses cloased parameter group
                        Logging.AddDebugLog("OnCommand: user entered all parameters and command uses cloased parameter group");
                        Dictionary <string, IWorkItem> suggestions = GetAvailableSuggestions(bestCandidateForUsedCommand);
                        IWorkItem selectedSuggestion = null;
                        if (suggestions.TryGetValue(bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1].GetCaption(), out selectedSuggestion))
                        {//user-entered parameter does not exist in group - add it to list
                            Logging.AddDebugLog("OnCommand: user-entered parameter does not exist in group - add it to list");
                            IWorkItem postProcessedSuggestion = PostProcessSelectedSuggestion(selectedSuggestion);
                            if (postProcessedSuggestion == null)
                            {//user probably canceled command - abort command
                                Logging.AddDebugLog("OnCommand: user probably canceled command - abort command");
                                return;
                            }
                            bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1] = postProcessedSuggestion;
                        }
                        else
                        {//user-entered parameter does not exist in group - plan input parameter box
                            Logging.AddDebugLog("OnCommand: user-entered parameter does not exist in group - plan input parameter box");
                            if (bestCandidateForUsedCommand.parameterInputArguments.acceptOnlySuggested)
                            {
                                bestCandidateForUsedCommand.parameterInputArguments.predefinedValue = string.Empty;
                            }
                            else
                            {
                                bestCandidateForUsedCommand.parameterInputArguments.predefinedValue = bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1].GetCaption();
                            }
                            bestCandidateForUsedCommand.parametersOnExecute.RemoveAt(bestCandidateForUsedCommand.parametersOnExecute.Count - 1);
                            bestCandidateForUsedCommandRequiresParameterInput = true;
                        }
                    }

                    if (!bestCandidateForUsedCommandRequiresParameterInput)
                    {
                        Logging.AddDebugLog("OnCommand: bestCandidateForUsedCommandRequiresParameterInput==false");
                        Logging.AddDebugLog("OnCommand: ExecuteCommandCandidate...");
                        ExecuteCommandCandidate(bestCandidateForUsedCommand);
                    }
                    else
                    {
                        Logging.AddDebugLog("OnCommand: ProcessingBeforeParameterInput...");
                        bool cancel = false;
                        bestCandidateForUsedCommand.provider.ProcessingBeforeParameterInput(bestCandidateForUsedCommand, ref cancel);
                        Logging.AddDebugLog("OnCommand: ProcessingBeforeParameterInput done. cancel=" + cancel);
                        if (cancel)
                        {
                            return;
                        }

                        Logging.AddDebugLog("OnCommand: GetAvailableSuggestions...");
                        Dictionary <string, IWorkItem> suggestions = GetAvailableSuggestions(bestCandidateForUsedCommand);

                        //prepare parameters to suggestions
                        bestCandidateForUsedCommand.parameterInputArguments.suggestions = new List <string>();
                        foreach (var suggestion in suggestions)
                        {
                            bestCandidateForUsedCommand.parameterInputArguments.suggestions.Add(suggestion.Key);
                        }

                        //execute dropbox
                        Logging.AddDebugLog("OnCommand: execute dropbox...");
                        try
                        {
                            PostParameterInputArguments contextData = new PostParameterInputArguments();
                            contextData.suggestions = suggestions;
                            contextData.bestCandidateForUsedCommand = bestCandidateForUsedCommand;
                            contextData.bestCandidateForUsedCommandRequiresParameterInput = bestCandidateForUsedCommandRequiresParameterInput;

                            ParameterInput.Display(bestCandidateForUsedCommand.parameterInputArguments, ParameterInput_OnClose, contextData, Screen.FromPoint(Cursor.Position));
                        }
                        catch (Exception exception)
                        {
                            MessagesHandler.Display("Error", exception.Message);
                            Logging.AddErrorLog("Parameter input failed: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                            Common.Logging.AddExceptionLog(exception);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logging.AddErrorLog("Command execution failed: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                Logging.AddExceptionLog(exception);
                throw exception;
            }
            //SelectionListener.Listener.Current.IfOpenedContinue();
        }
Exemplo n.º 22
0
        public static Shortcut ReadShortcutFile(string shortcutFilePath)
        {
            //File.AppendAllText("d:\\sss.txt", shortcutFilePath+"\r\n");
            Shortcut result = null;

            try
            {
                //if(
                //	Path.GetInvalidPathChars().Any(c=>Path.GetDirectoryName(shortcutFilePath).Contains(c)) ||
                //	Path.GetInvalidFileNameChars().Any(c=>Path.GetFileName(shortcutFilePath).Contains(c))
                //	)
                //{
                //	result = null;
                //}
                //else {
                if (Path.GetExtension(shortcutFilePath).EndsWith("lnk", StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        string target = null;

                        if (!CraftSynth.BuildingBlocks.WindowsNT.Misc.Is64BitOperatingSystem)
                        {                                //requires Interop.IWshRuntimeLibrary which can not run as x64!!
                            IWshRuntimeLibrary.WshShell     shell       = new IWshRuntimeLibrary.WshShell();
                            IWshRuntimeLibrary.IWshShortcut wshShortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutFilePath);
                            target = wshShortcut.TargetPath;

                            if (
                                //!shortcut.TargetPath.StartsWith("http", StringComparison.InvariantCultureIgnoreCase) &&
                                //!shortcut.TargetPath.StartsWith("ftp", StringComparison.InvariantCultureIgnoreCase)
                                !string.IsNullOrEmpty(target)                                         //make sure that target is on file system
                                )
                            {
                                Shortcut shortcut = new Shortcut();
                                shortcut.caption          = Path.GetFileNameWithoutExtension(shortcutFilePath);
                                shortcut.targetPath       = target;
                                shortcut.shortcutFilePath = shortcutFilePath;
                                result = shortcut;
                            }
                            else
                            {
                                Shortcut shortcut = new Shortcut();
                                shortcut.caption          = Path.GetFileNameWithoutExtension(shortcutFilePath);
                                shortcut.targetPath       = CraftSynth.BuildingBlocks.IO.FileSystem.GetTargetPathFromLnkManualy(shortcutFilePath);
                                shortcut.shortcutFilePath = shortcutFilePath;
                                result = shortcut;
                            }
                        }
                        else
                        {                                //run separate process as x86 and send it lnk filepath.
                            FormLnkFileReaderProxy.Initialize();
                            target = FormLnkFileReaderProxy.WaitForLnkTarget(shortcutFilePath);

                            if (!string.IsNullOrEmpty(target))
                            {
                                Shortcut shortcut = new Shortcut();
                                shortcut.caption          = Path.GetFileNameWithoutExtension(shortcutFilePath);
                                shortcut.targetPath       = target;
                                shortcut.shortcutFilePath = shortcutFilePath;
                                result = shortcut;
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        result = null;
                        Logging.AddErrorLog(string.Format("Error occured while reading shortcut '{0}': {1}", shortcutFilePath, exception.Message));
                        Common.Logging.AddExceptionLog(exception);
                    }
                }
                else if (Path.GetExtension(shortcutFilePath).EndsWith("url", StringComparison.InvariantCultureIgnoreCase))
                {
                    string targetPath = null;
                    try
                    {
                        string[] content = System.IO.File.ReadAllLines(shortcutFilePath);
                        targetPath = content.Single(l => l.ToUpper().StartsWith("URL=")).Split('=')[1].Trim();

                        Shortcut shortcut = new Shortcut();
                        shortcut.caption          = Path.GetFileNameWithoutExtension(shortcutFilePath);
                        shortcut.targetPath       = targetPath;
                        shortcut.shortcutFilePath = shortcutFilePath;
                        result = shortcut;
                    }
                    catch (Exception exception)
                    {
                        result = null;
                        Logging.AddErrorLog(string.Format("Error occured while reading shortcut '{0}': {1}", shortcutFilePath, exception.Message));
                        Common.Logging.AddExceptionLog(exception);
                    }
                }
                //}
            }
            catch (Exception exception) {
                result = null;
                Logging.AddErrorLog(string.Format("Error occured while reading shortcut '{0}': {1}", shortcutFilePath, exception.Message));
                Common.Logging.AddExceptionLog(exception);
            }
            return(result);
        }
Exemplo n.º 23
0
        public async Task SearchSiteAsync(bool slow)
        {
            SearchConfigData searchConfig = await SearchConfigDataProvider.GetConfigAsync();

            DateTime searchStarted = DateTime.UtcNow; // once we have all new keywords, delete all keywords that were added before this date/time

            using (SearchDataProvider searchDP = new SearchDataProvider()) {
                // Search all generated pages (unique modules or classes, like data providers)
                DynamicUrlsImpl dynamicUrls = new DynamicUrlsImpl();
                List <Type>     types       = dynamicUrls.GetDynamicUrlTypes();
                // search types that generate dynamic urls
                foreach (Type type in types)
                {
#if DEBUG
                    //                  if (type.Name != "FileDocumentDisplayModule") continue;//used for debugging
#endif
                    ISearchDynamicUrls iSearch = Activator.CreateInstance(type) as ISearchDynamicUrls;
                    if (iSearch != null)
                    {
                        try {
                            SearchWords searchWords = new SearchWords(searchConfig, searchDP, searchStarted);
                            await iSearch.KeywordsForDynamicUrlsAsync(searchWords);

                            if (slow)
                            {
                                Thread.Sleep(500);// delay a bit (slow can only be used by scheduler items)
                            }
                        } catch (Exception exc) {
                            Logging.AddErrorLog("KeywordsForDynamicUrls failed for {0}", type.FullName, exc);
                        }
                    }
                }

                // search all designed modules that have dynamic urls
                foreach (DesignedModule desMod in await DesignedModules.LoadDesignedModulesAsync())
                {
                    try {
                        ModuleDefinition mod = await ModuleDefinition.LoadAsync(desMod.ModuleGuid, AllowNone : true);

                        if (mod != null && types.Contains(mod.GetType()) && mod.WantSearch)
                        {
                            ISearchDynamicUrls iSearch = mod as ISearchDynamicUrls;
                            if (iSearch != null)
                            {
                                SearchWords searchWords = new SearchWords(searchConfig, searchDP, searchStarted);
                                await iSearch.KeywordsForDynamicUrlsAsync(searchWords);

                                if (slow)
                                {
                                    Thread.Sleep(500);// delay a bit (slow can only be used by scheduler items)
                                }
                            }
                        }
                    } catch (Exception exc) {
                        Logging.AddErrorLog("KeywordsForDynamicUrls failed for module {0}", desMod.ModuleGuid, exc);
                    }
                }

                // Search all designed pages and extract keywords
                List <Guid> pages = await PageDefinition.GetDesignedGuidsAsync();

                foreach (Guid pageGuid in pages)
                {
                    PageDefinition page = await PageDefinition.LoadAsync(pageGuid);

                    if (page != null)
                    {
                        SearchWords searchWords = new SearchWords(searchConfig, searchDP, searchStarted);
                        await SearchPageAsync(searchWords, page);

                        if (slow)
                        {
                            Thread.Sleep(500);// delay a bit (slow can only be used by scheduler items)
                        }
                    }
                }

                // Remove old keywords
                await searchDP.RemoveOldItemsAsync(searchStarted);
            }
        }
Exemplo n.º 24
0
        public void ExecuteCommand(Extension.IEnsoService service, Command command)
        {
            Logging.AddActionLog(string.Format("TOpener: Executing command '{0}' ...", command.Name));

            if (command.Name == "topen" || command.Name == "rtopen")
            {
                Logging.AddActionLog(string.Format("TOpener: Opening '{0}' in Total Commander ...", command.parametersOnExecute[0].GetValueAsText()));
                MessagesHandler.Display(string.Format("Opening {0} ...", command.parametersOnExecute[0].GetValueAsText()));

                if (IsPathSuitable(command.parametersOnExecute[0].GetValueAsText()))
                {
                    TotalCommanderPane pane = TotalCommanderPane.Left;
                    if (command.Name == "topen")
                    {
                        pane = TotalCommanderPane.Left;
                    }
                    else if (command.Name == "rtopen")
                    {
                        pane = TotalCommanderPane.Right;
                    }
                    OpenInTotalComander(command.parametersOnExecute[0].GetValueAsText(), pane);
                }
                else
                {//extract filepaths and try to open their parent folder
                    List <string> fileSelectionList = Syntax.FileSelectionFromString(command.parametersOnExecute[0].GetValueAsText());

                    if (fileSelectionList.Count == 0)
                    {
                        Logging.AddErrorLog(string.Format("TOpener: File/Folder '{0}' not found.", command.parametersOnExecute[0].GetValueAsText()));
                        MessagesHandler.Display("File/Folder not found.", command.parametersOnExecute[0].GetValueAsText());
                    }
                    else
                    {
                        string parentFolder = Directory.GetParent(fileSelectionList[0]).FullName;
                        if (IsPathSuitable(parentFolder))
                        {
                            TotalCommanderPane pane = TotalCommanderPane.Left;
                            if (command.Name == "topen")
                            {
                                pane = TotalCommanderPane.Left;
                            }
                            else if (command.Name == "rtopen")
                            {
                                pane = TotalCommanderPane.Right;
                            }
                            OpenInTotalComander(parentFolder, pane);
                        }
                        else
                        {
                            Logging.AddErrorLog(string.Format("TOpener: File/Folder '{0}' not found.", parentFolder));
                            MessagesHandler.Display("File/Folder not found.", parentFolder);
                        }

                        //foreach (string filePath in fileSelectionList)
                        //{
                        //    if (File.Exists(filePath) || Directory.Exists(filePath))
                        //    {
                        //        OpenInTotalComander(filePath);
                        //    }
                        //    else
                        //    {
                        //        MessagesHandler.Display( "File/Folder not found.", filePath);
                        //    }
                        //}
                    }
                }
            }
        }
Exemplo n.º 25
0
        private void ProcessCommand(Object o)
        {
            KeyValuePair <IEnsoService, Command> parameters = (KeyValuePair <IEnsoService, Command>)o;
            IEnsoService service = parameters.Key;
            Command      command = parameters.Value;

            if (command.parametersOnExecute[0] is ImageWorkItem)
            {
                string targetFilePath = null;
                try
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.DefaultExt = ".png";
                    saveFileDialog.Filter     = ".bmp|.bmp|.emf|.emf|.exif|.exif|.gif|.gif|.ico|.ico|.jpg|.jpg|.png|.png|.tif|.tif|.wmf|.wmf";
                    SetSaveFileDialogCommonOptions(saveFileDialog);

                    Thread bringToFrontAssistant = new Thread(BringToFront);
                    bringToFrontAssistant.Start(saveFileDialog.Title);

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        Settings.Current.FileManagerSaveToDefaultFolder = Path.GetDirectoryName(saveFileDialog.FileName);
                        targetFilePath = saveFileDialog.FileName;
                        string      targetExtension   = Path.GetExtension(targetFilePath);
                        ImageFormat targetImageFormat = ImageFormat.Png;
                        if (string.Compare(targetExtension, ".bmp", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Bmp;
                        }
                        else
                        if (string.Compare(targetExtension, ".emf", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Emf;
                        }
                        else
                        if (string.Compare(targetExtension, ".exif", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Exif;
                        }
                        else
                        if (string.Compare(targetExtension, ".gif", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Gif;
                        }
                        else
                        if (string.Compare(targetExtension, ".ico", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Icon;
                        }
                        else
                        if (string.Compare(targetExtension, ".jpg", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Jpeg;
                        }
                        else
                        if (string.Compare(targetExtension, ".png", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Png;
                        }
                        else
                        if (string.Compare(targetExtension, ".tif", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Tiff;
                        }
                        else
                        if (string.Compare(targetExtension, ".wmf", true) == 0)
                        {
                            targetImageFormat = ImageFormat.Wmf;
                        }

                        ImageWorkItem imageWorkItem = (ImageWorkItem)command.parametersOnExecute[0];
                        imageWorkItem.image.Save(targetFilePath, targetImageFormat);

                        Logging.AddActionLog(string.Format("FileManager: Image saved to '{0}'.", targetFilePath));
                        MessagesHandler.Display(string.Format("Saved.", command.Name));

                        if (command.Postfix == "[what] and copy its file path")
                        {
                            CraftSynth.BuildingBlocks.IO.Clipboard.SetTextToClipboard(targetFilePath);
                            Logging.AddActionLog(string.Format("ClipboardManager: file path '{0}' copied to clipboard.", targetFilePath));
                            MessagesHandler.Display("Image saved and its file path copied.");
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new ApplicationException(string.Format("FileManager: Failed to save image to '{0}'.", targetFilePath ?? "not set"), exception);
                }
            }
            else
            if ((command.parametersOnExecute[0] is Entities.StringWorkItem) ||
                (command.parametersOnExecute[0] is Entities.Shortcut) ||
                (command.parametersOnExecute[0] is Entities.Contact) ||
                (command.parametersOnExecute[0] is Entities.CallerHistoryItem) ||
                (command.parametersOnExecute[0] is Entities.MemorizedString))
            {
                string targetFilePath = null;
                try
                {
                    MessagesHandler.Display(command.parametersOnExecute[0].GetValueAsText());

                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.DefaultExt = ".txt";
                    saveFileDialog.Filter     = ".txt|.txt";
                    SetSaveFileDialogCommonOptions(saveFileDialog);

                    Thread bringToFrontAssistant = new Thread(BringToFront);
                    bringToFrontAssistant.Start(saveFileDialog.Title);

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        Settings.Current.FileManagerSaveToDefaultFolder = Path.GetDirectoryName(saveFileDialog.FileName);
                        targetFilePath = saveFileDialog.FileName;

                        File.WriteAllText(targetFilePath, command.parametersOnExecute[0].GetValueAsText());

                        Logging.AddActionLog(string.Format("FileManager: Text saved from work item to '{0}'.", targetFilePath));
                        MessagesHandler.Display(string.Format("Saved.", command.Name));

                        if (command.Postfix == "[what] and copy its file path")
                        {
                            CraftSynth.BuildingBlocks.IO.Clipboard.SetTextToClipboard(targetFilePath);
                            Logging.AddActionLog(string.Format("ClipboardManager: file path '{0}' copied to clipboard.", targetFilePath));
                            MessagesHandler.Display("Text saved and its file path copied.");
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new ApplicationException(string.Format("FileManager: Failed to save text from work item to '{0}'.", targetFilePath ?? "not set"), exception);
                }
            }
            else
            {
                Logging.AddErrorLog(string.Format("FileManager: Tried to save unsupported work item type."));
                MessagesHandler.Display("Can not save work item of this type.");
            }
        }
Exemplo n.º 26
0
        private void Execute()
        {
            // get a manager for the scheduler
            YetaWFManager.MakeInitialThreadInstance(null);

            // TODO: Scheduler logging should not start during startup processing. This timer postpones it (but is not a good solution)

            // Because initialization is called during application startup, we'll wait before we
            // check for any scheduler items that may be due (just so app start isn't all too slow).
            try {
                Thread.Sleep(defaultStartupTimeSpan);
            } catch (ThreadInterruptedException) {
                // thread was interrupted because there is work to be done
            }

            SchedulerLog = new SchedulerLogging();
            SchedulerLog.Init();
            SchedulerLog.LimitTo(YetaWFManager.Manager);

            YetaWFManager.Syncify(async() => {  // there is no point in running the scheduler async
                await Logging.RegisterLoggingAsync(SchedulerLog);
            });

            Logging.AddTraceLog("Scheduler task started");

            // mark all scheduled items that are supposed to be run at application startup
            try {
                YetaWFManager.Syncify(async() => {  // there is no point in running the scheduler async
                    await RunStartupItemsAsync();
                });
            } catch (Exception exc) {
                Logging.AddErrorLog("An error occurred running startup items", exc);
            }

            for (;;)
            {
                TimeSpan delayTime = defaultTimeSpanNoTask;
                if (SchedulerSupport.Enabled)
                {
                    try {
                        YetaWFManager.Syncify(async() => {  // there is no point in running the scheduler async
                            delayTime = await RunItemsAsync();
                        });
                    } catch (Exception exc) {
                        delayTime = defaultTimeSpanError;
                        Logging.AddErrorLog("An error occurred in the scheduling loop.", exc);
                    }
                    if (delayTime < new TimeSpan(0, 0, 5))// at a few seconds
                    {
                        delayTime = new TimeSpan(0, 0, 5);
                    }
                    else if (delayTime > new TimeSpan(1, 0, 0, 0)) // max. 1 day
                    {
                        delayTime = new TimeSpan(1, 0, 0, 0);
                    }
                }
                try {
                    schedulingThreadRunning = false;
                    Logging.AddLog($"Waiting {delayTime}");
                    Thread.Sleep(delayTime);
                } catch (ThreadInterruptedException) {
                    // thread was interrupted because there is work to be done
                } catch (ThreadAbortException) { }
                finally {
                    schedulingThreadRunning = true;
                }
            }

            // This never really ends so we don't need to unregister logging
            //log.Shutdown();
            //Logging.UnregisterLogging(log);
        }
Exemplo n.º 27
0
        private static void RdcOpenInNewThread(Command command)
        {
            Logging.AddActionLog(string.Format("RdcOpener: Opening '{0}' in RDC ...", command.parametersOnExecute[0].GetValueAsText().Trim().Split(' ')[0]));
            MessagesHandler.Display(string.Format("Connecting to {0} ...", command.parametersOnExecute[0].GetValueAsText().Trim().Split(' ')[0]));

            List <string> parts = command.parametersOnExecute[0].GetValueAsText().
                                  Trim().Replace("\\r", " ").Replace("\\n", " ").
                                  Replace(" /user:"******" ").Replace(" /User:"******" ").Replace(" /USER:"******" ").
                                  Replace(" /pass:"******" ").Replace(" /Pass:"******" ").Replace(" /PASS:"******" ").
                                  Split(' ').ToList();

            if (command.Name == "rdc-as-default-user" && parts.Count == 1)
            {
                //parts.RemoveAt(0);//as
                //parts.RemoveAt(0);//default
                //parts.RemoveAt(0);//user

                parts.Add(Settings.Current.RdcDefaultUsername);
                parts.Add(Settings.Current.RdcDefaultPassword);

                //final list should be ip,user1,pass1
            }

            if (parts.Count == 1)
            {        //example: 192.168.0.1:12
                Process rdcProcess = new Process();
                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/v {0}", parts[0]);
                rdcProcess.Start();
            }
            else if (parts.Count == 2)
            {        //example: 192.168.0.1:12 /user:mynet\Administrator
                Process rdcProcess = new Process();
                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/generic:TERMSRV/{0} /user:{1}", parts[0], parts[1]);
                rdcProcess.Start();

                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/v {0}", parts[0]);
                rdcProcess.Start();

                Thread.Sleep(10000);

                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/delete:TERMSRV/{0}", parts[0]);
                rdcProcess.Start();
            }
            else if (parts.Count == 3)
            {        //example: 192.168.0.1:12 /user:mynet\Administrator /pass:somepass1
                Process rdcProcess = new Process();
                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/generic:TERMSRV/{0} /user:{1} /pass:{2}", parts[0], parts[1], parts[2]);
                rdcProcess.Start();

                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/v {0}", parts[0]);
                rdcProcess.Start();

                Thread.Sleep(10000);

                rdcProcess.StartInfo.FileName  = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
                rdcProcess.StartInfo.Arguments = string.Format("/delete:TERMSRV/{0}", parts[0]);
                rdcProcess.Start();
            }
            else
            {
                Logging.AddErrorLog(string.Format("RdcOpener: Invalid 'IP username password': '******'.", command.parametersOnExecute[0].GetValueAsText()));
                MessagesHandler.Display("Syntax 'IP:port username password' not recognized. Port, username and password are optional.", command.parametersOnExecute[0].GetValueAsText());
            }
        }
Exemplo n.º 28
0
        private async Task RunItemAsync(SchedulerDataProvider schedDP, SchedulerItemData item)
        {
            long logId = DateTime.UtcNow.Ticks;

            SchedulerLog.SetCurrent(logId, 0, item.Name);

            item.IsRunning = true;
            item.RunTime   = new TimeSpan();
            item.Last      = DateTime.UtcNow;

            try {
                await schedDP.UpdateItemAsync(item);
            } catch (Exception exc) {
                Logging.AddErrorLog("Updating scheduler item {0} failed.", item.Name, exc);
            }

            StringBuilder errors  = new StringBuilder();
            DateTime?     nextRun = null;// called event handlers can return a next run time

            try {
                item.Errors = null;

                DateTime now = DateTime.UtcNow;
                {
                    string m = $"Scheduler event - running scheduler item '{item.Name}'.";
                    Logging.AddLog(m);
                    errors.AppendLine(m);
                }

                Type tp = null;
                try {
                    Assembly asm = Assemblies.Load(item.Event.ImplementingAssembly);
                    tp = asm.GetType(item.Event.ImplementingType);
                } catch (Exception exc) {
                    throw new InternalError("Scheduler item '{0}' could not be loaded (Type={1}, Assembly={2}) - {3}", item.Name, item.Event.ImplementingType, item.Event.ImplementingAssembly, ErrorHandling.FormatExceptionMessage(exc));
                }

                if (item.SiteSpecific)
                {
                    DataProviderGetRecords <SiteDefinition> info = await SiteDefinition.GetSitesAsync(0, 0, null, null);

                    foreach (SiteDefinition site in info.Data)
                    {
                        IScheduling schedEvt = null;
                        try {
                            schedEvt = (IScheduling)Activator.CreateInstance(tp);
                        } catch (Exception exc) {
                            string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}";
                            Logging.AddLog(m);
                            errors.AppendLine(m);
                        }

                        if (schedEvt != null)
                        {
                            YetaWFManager.MakeThreadInstance(site, null, true);// set up a manager for the site

                            SchedulerLog.LimitTo(YetaWFManager.Manager);
                            SchedulerLog.SetCurrent(logId, site.Identity, item.Name);

                            SchedulerItemBase itemBase = new SchedulerItemBase {
                                Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = true
                            };
                            try {
                                await schedEvt.RunItemAsync(itemBase);
                            } catch (Exception exc) {
                                string m = $"An error occurred in scheduler item '{site.Identity}: {item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}";
                                Logging.AddLog(m);
                                errors.AppendLine(m);
                            }

                            foreach (var s in itemBase.Log)
                            {
                                string m = $"{site.Identity}: {s}";
                                Logging.AddLog(m);
                                errors.AppendLine(m);
                            }
                            if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun))
                            {
                                nextRun = itemBase.NextRun;
                            }

                            YetaWFManager.RemoveThreadInstance();

                            YetaWFManager.MakeThreadInstance(null, null, true);// restore scheduler's manager
                            SchedulerLog.LimitTo(YetaWFManager.Manager);
                            SchedulerLog.SetCurrent();
                        }
                    }
                }
                else
                {
                    IScheduling schedEvt = null;
                    try {
                        schedEvt = (IScheduling)Activator.CreateInstance(tp);
                    } catch (Exception exc) {
                        string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}";
                        Logging.AddLog(m);
                        errors.AppendLine(m);
                    }

                    if (schedEvt != null)
                    {
                        SchedulerItemBase itemBase = new SchedulerItemBase {
                            Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = false
                        };
                        try {
                            await schedEvt.RunItemAsync(itemBase);
                        } catch (Exception exc) {
                            string m = $"An error occurred in scheduler item '{item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}";
                            Logging.AddLog(m);
                            errors.AppendLine(m);
                        }
                        foreach (var s in itemBase.Log)
                        {
                            Logging.AddLog(s);
                            errors.AppendLine(s);
                        }

                        if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun))
                        {
                            nextRun = itemBase.NextRun;
                        }
                    }
                }

                TimeSpan diff = DateTime.UtcNow - now;
                item.RunTime = diff;
                {
                    string m = $"Elapsed time for scheduler item '{item.Name}' was {diff} (hh:mm:ss.ms).";
                    Logging.AddLog(m);
                    errors.AppendLine(m);
                }
            } catch (Exception exc) {
                string m = $"Scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}";
                Logging.AddErrorLog(m);
                errors.AppendLine(m);
            }

            if (item.RunOnce)
            {
                item.Enabled = false;
            }

            item.IsRunning = false;

            item.SetNextRuntime();
            if (nextRun != null)
            {
                Logging.AddLog($"Next run at {nextRun} (UTC)");
                item.Next    = nextRun;
                item.Enabled = true;
            }
            item.Errors = errors.ToString();

            try {
                await schedDP.UpdateItemAsync(item);
            } catch (Exception exc) {
                string m = $"Updating scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}";
                Logging.AddErrorLog(m);
                errors.AppendLine(m);
            }

            SchedulerLog.SetCurrent();
        }
Exemplo n.º 29
0
        private async Task <ActionResult> CompleteLoginAsync(LoginModel model, LoginConfigData config, bool useTwoStep)
        {
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN);
            Manager.SessionSettings.SiteSettings.Save();
            model.Success = false;

            // make sure it's a valid user
            UserDefinition user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

            if (user == null)
            {
                Logging.AddErrorLog("User login failed: {0} - no such user", model.UserName);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }
            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                if (await logInfoDP.IsExternalUserAsync(user.UserId))
                {
                    throw new Error(this.__ResStr("extUser", "This account can only be accessed using an external login provider"));
                }
            }

            TwoStepAuth twoStep = new TwoStepAuth();// clear any two-step info we may have
            await twoStep.ClearTwoStepAutheticationAsync(user.UserId);

            if (config.MaxLoginFailures != 0 && user.LoginFailures >= config.MaxLoginFailures)
            {
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                if (user.UserStatus != UserStatusEnum.Suspended)
                {
                    user.UserStatus = UserStatusEnum.Suspended;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                return(PartialView(model));
            }

            UserDefinition foundUser = user;

            user = null;

            // Handle random super user password (only supported on Core)
            if (foundUser.UserId == SuperuserDefinitionDataProvider.SuperUserId && SuperuserDefinitionDataProvider.SuperuserAvailable && SuperuserDefinitionDataProvider.SuperUserPasswordRandom &&
                model.UserName == SuperuserDefinitionDataProvider.SuperUserName && model.Password == SuperuserDefinitionDataProvider.SuperUserPassword)
            {
                user = foundUser;
            }

            if (user == null)
            {
                user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

                if (string.IsNullOrWhiteSpace(model.Password) || !await Managers.GetUserManager().CheckPasswordAsync(user, model.Password))
                {
                    user = null;
                }
            }
            if (user == null)
            {
                foundUser.LoginFailures = foundUser.LoginFailures + 1;
                await Managers.GetUserManager().UpdateAsync(foundUser);

                Logging.AddErrorLog("User login failed: {0}, {1}, {2}", model.UserName, model.Password, model.VerificationCode);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }

            // if verification code valid, advance user to approved or needs approval
            if (user.UserStatus == UserStatusEnum.NeedValidation && model.VerificationCode == user.VerificationCode)
            {
                Logging.AddLog("User {0} validated ({1})", model.UserName, model.VerificationCode);

                if (config.ApproveNewUsers)
                {
                    user.UserStatus       = UserStatusEnum.NeedApproval;
                    user.LastActivityDate = DateTime.UtcNow;
                    user.LastActivityIP   = Manager.UserHostAddress;
                    await Managers.GetUserManager().UpdateAsync(user);

                    Emails emails = new Emails();
                    await emails.SendApprovalNeededAsync(user);

                    string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                    return(FormProcessed(model,
                                         this.__ResStr("notApproved", "You just verified your account. Now your account has to be approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                         NextPage: nextPage));
                }
                user.UserStatus = UserStatusEnum.Approved;
                // this is saved below, before we're logged in
            }

            // check what to do based on account status
            if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                if (model.ShowVerification)
                {
                    Logging.AddErrorLog("User {0} - invalid verification code({1})", model.UserName, model.VerificationCode);
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("invVerification", "The verification code is invalid. Please make sure to copy/paste it from the email to avoid any typos."));
                    user.LoginFailures = user.LoginFailures + 1;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                else
                {
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Please copy and enter the verification code here."));
                }
                model.ShowVerification       = true;
                model.ResendVerificationCode = await Module.GetAction_ResendVerificationEmailAsync(user.UserName);

                model.ShowCaptcha = false;
                return(PartialView(model));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                Logging.AddErrorLog("User {0} - not yet approved", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                return(FormProcessed(model,
                                     this.__ResStr("notApproved2", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                Logging.AddErrorLog("User {0} - rejected user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.RejectedUrl) ? Manager.CurrentSite.HomePageUrl : config.RejectedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountRejected", "Your account has been rejected by the site administrator."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                Logging.AddErrorLog("User {0} - suspended user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.SuspendedUrl) ? Manager.CurrentSite.HomePageUrl : config.SuspendedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountSuspended", "Your account has been suspended."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Approved)
            {
                string nextUrl = null;
                if (Manager.HaveReturnToUrl)
                {
                    nextUrl = Manager.ReturnToUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = Manager.CurrentSite.PostLoginUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = YetaWFManager.Manager.CurrentSite.HomePageUrl;
                }

                if (useTwoStep)
                {
                    ActionResult actionResult = await TwoStepAuthetication(user);

                    if (actionResult != null)
                    {
                        Manager.SessionSettings.SiteSettings.SetValue <int>(LoginTwoStepController.IDENTITY_TWOSTEP_USERID, user.UserId);// marker that user has entered correct name/password
                        Manager.SessionSettings.SiteSettings.SetValue <string>(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL, nextUrl);
                        Manager.SessionSettings.SiteSettings.SetValue <bool>(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN, model.CloseOnLogin);
                        Manager.SessionSettings.SiteSettings.Save();
                        return(actionResult);
                    }
                }
                await LoginModuleController.UserLoginAsync(user, model.RememberMe);

                model.Success = true;
                Logging.AddLog("User {0} - logged on", model.UserName);

                return(FormProcessed(model, OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }