예제 #1
0
        public IOmeterWrapper(String current_path_p, String io_meter_path_p, String config_file_path_p, DisplayMessage display_message_p)
        {
            // Store the passed in message handler.
            display_message += display_message_p;

            // Load the user specified settings.
            user_config_settings = new ConfigParser();
            if (!user_config_settings.LoadAppSettings(config_file_path_p))
                display_message(user_config_settings.GetConfigFileUseage());

            // Store the current application path.
            current_path = current_path_p;

            // Store the path to IOmeter.exe.
            io_meter_path = io_meter_path_p;

            // Store the worload exicution order.
            workload_order = user_config_settings.GetAppSetting("workload_run_order").Split(',');

            // Get the user's specified test runtime.
            test_duration_sec = user_config_settings.GetAppSetting("workload_duration_sec");

            // Setup results placeholder.
            workload_results = new List<Result>();

            // Store a handle to the running iomter process.
            command_to_execute = new Process();
        }
예제 #2
0
        static void Main(string[] args)
        {
            //Func<string, string> selector = str => str.ToUpper();

            //Func<int, string> test = t => (t * 2).ToString();

            //Predicate<Employee> premp = new Predicate<Employee>(findEmployee);
            //Employee employee = employees.Find(delegate(Employee x) { return x.Id == 2; });
            //Console.WriteLine(employee.Name);
            //Console.ReadLine();

            DisplayMessage dm = new DisplayMessage(Hello);
            dm("Hello delegate");
            GetMessage gm = new GetMessage(GoodBey);
            Console.WriteLine(gm(" delegate"));
            Console.ReadLine();
        }
예제 #3
0
	//private float Lifebar_distance_y=0;
	//private float Lifebar_back_distance_y=0;
	//--


	protected virtual void Start()
	{
		audioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
		displayMessage = GameObject.Find ("TurnManager").GetComponent<DisplayMessage> ();
		//Lifebar_distance_y = this.transform.position.y-Lifebar.transform.position.y;
		aux_d = Lifebar.GetComponent<Renderer>().bounds.size.x;//lifebar width
		initial_localscale = new Vector3 (Lifebar.transform.localScale.x,Lifebar.transform.localScale.y,Lifebar.transform.localScale.z);
		//--
		circleCollider = GetComponent<CircleCollider2D> ();
		rb2D = GetComponent<Rigidbody2D> ();
		inverseMoveTime = 1f / moveTime;
		moved = true;
		isAttacking = false;
		attackerDamage = 0;
		hasMoved = false;
		hasAttacked = false;
		isdead = false;
		stopped = true;
		selected = false;

		newAnimation = false;
		myDirection = directions [0];
		myPlayer = this.GetComponentInParent<Player> (); // gets the photon view of parent player class
		if (myPlayer == null) { // Player2 denotes enemy, still unused but can be changed later
			transform.gameObject.tag = "Player2";
			//transform.SetParent(GameObject.FindGameObjectWithTag("Player").transform);
			transform.SetParent(GameObject.FindGameObjectsWithTag("Player")[1].transform);
			myPlayer = this.GetComponentInParent<Player> ();
		}

		GameObject go = GameObject.FindGameObjectWithTag ("Canvas");
		actionMenu = (ActionMenu)go.transform.FindChild ("ActionMenu(Clone)").GetComponent<ActionMenu>();

		//healthValue = 50; //TODO read in health value by calculating from level
		startingHealth = healthValue;
	}
예제 #4
0
 private void OnDisplayMessage(string message)
 {
     DisplayMessage?.Invoke(this, new MessageEventArgs {
         Message = message
     });
 }
예제 #5
0
 /// <summary>
 /// 提示
 /// </summary>
 /// <param name="msg"></param>
 public void Alert(string msg)
 {
     DisplayMessage.ExecuteJs(string.Format("alert('{0}');", msg));
 }
 public void Show()
 {
     DisplayMessage.Show(_messageId, _owner, _args);
 }
예제 #7
0
 protected void lbAddBitcoinAddress_Click(object sender, EventArgs e)
 {
     DisplayMessage.ShowAlertModal("ShowBitcoinAddressModal()", Page);
 }
예제 #8
0
 private static void SetOperationToDisplayMessage(this string msgOperation, string langCode, DisplayMessage displayMessage, bool forceUpdate = false)
 {
     if (Enum.IsDefined(typeof(MessageOperationTypeEnum), msgOperation.Trim()))
     {
         if (!Operations.ContainsKey(langCode) || !Operations[langCode].ContainsKey(LookupEnums.MsgOperationType))
         {
             GetOperations(langCode, LookupEnums.MsgOperationType);
         }
         var operation = Operations[langCode][LookupEnums.MsgOperationType].FirstOrDefault(e => e.SysRefName.Equals(msgOperation.Trim()));
         displayMessage.Operations.Add(operation);
     }
 }
        public static void DoExport(iTunesLibrary library, BackgroundWorker bgw, DoWorkEventArgs bgwArgs, DisplayMessage dm)
        {
            List <Track> trackList = BuildLibraryTrackList(library, dm, bgw, bgwArgs);

            if (bgw.CancellationPending == true)
            {
                bgwArgs.Cancel = true;
                dm(new OutputMessage("Operation was canceled before export had begun.", MessageSeverity.Debug));
                return;
            }

            if (trackList.Count == 0)
            {
                dm(new OutputMessage("No tracks could be found in this iTunes library!", MessageSeverity.Error));
            }

            List <string> directoryList         = GetDirectoryList(trackList).OrderBy(d => d).ToList();
            int           directoryListSize     = directoryList.Count;
            int           currentDirectoryIndex = 0;

            bgw.ReportProgress(0);
            dm(new OutputMessage("Starting export...", MessageSeverity.Always));

            foreach (string directory in directoryList)
            {
                double percentComplete    = Math.Floor(((double)currentDirectoryIndex / (double)directoryListSize) * 100.0);
                int    intPercentComplete = (int)percentComplete;
                bgw.ReportProgress(intPercentComplete);
                currentDirectoryIndex++;

                if (bgw.CancellationPending == true)
                {
                    bgwArgs.Cancel = true;
                    dm(new OutputMessage("Operation was canceled in the middle of the export.", MessageSeverity.Debug));
                    return;
                }

                try
                {
                    OutputMessage outputMessage = ExportDirectoryArtwork(library, trackList, directory);
                    if (outputMessage != null)
                    {
                        dm(outputMessage);
                    }
                    else
                    {
                        dm(new OutputMessage("Error while processing directory \"" + directory + "\": No OutputMessage object specified from OutputDirectoryArtwork().", MessageSeverity.Error));
                    }
                }
                catch (Exception ex)
                {
                    dm(new OutputMessage("Error while processing directory \"" + directory + "\": " + ex.Message, MessageSeverity.Error));
                }
            }

            bgw.ReportProgress(100);
        }
예제 #10
0
    void formUser_OnAfterSave(object sender, EventArgs e)
    {
        // Get user info from form
        UserInfo ui = (UserInfo)formUser.Data;

        // Add user prefix if settings is on
        // Ensure site prefixes
        if (UserInfoProvider.UserNameSitePrefixEnabled(CurrentSiteName))
        {
            ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(ui.UserName, SiteContext.CurrentSite);
        }

        ui.Enabled         = EnableUserAfterRegistration;
        ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
        ui.UserCampaign    = Service.Resolve <ICampaignService>().CampaignCode;

        ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;

        // Fill optionally full user name
        if (String.IsNullOrEmpty(ui.FullName))
        {
            ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
        }

        // Ensure nick name
        if (ui.UserNickName.Trim() == String.Empty)
        {
            ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
        }

        ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
        ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
        ui.UserSettings.UserLogActivities        = true;
        ui.UserSettings.UserShowIntroductionTile = true;

        // Check whether confirmation is required
        if (!ConfirmationRequired)
        {
            // If confirmation is not required check whether administration approval is required
            if (AdminApprovalRequired)
            {
                ui.Enabled = false;
                ui.UserSettings.UserWaitingForApproval = true;
            }
        }
        else
        {
            // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable
            ui.Enabled = false;
        }

        // Set user's starting alias path
        if (!String.IsNullOrEmpty(StartingAliasPath))
        {
            ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
        }

        // Get user password and save it in appropriate format after form save
        string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);

        UserInfoProvider.SetPassword(ui, password);

        if (!ConfirmationRequired)
        {
            SendAdminNotification(ui);
            LogOMActivity(ui);
        }

        SendRegistrationEmail(ui);
        LogWebAnalytics(ui);
        AssignToRoles(ui);

        if (ui.Enabled)
        {
            // Authenticate currently created user
            AuthenticationHelper.AuthenticateUser(ui.UserName, true);
        }

        var displayMessage = DisplayMessage.Trim();

        if (!String.IsNullOrEmpty(displayMessage))
        {
            ShowInformation(displayMessage);
        }
        else
        {
            if (RedirectToURL != String.Empty)
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL));
            }

            string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty);
            if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~", StringComparison.Ordinal) || returnUrl.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath")))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(HttpUtility.UrlDecode(returnUrl)));
            }
        }

        // Hide registration form
        pnlRegForm.Visible = false;
    }
예제 #11
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
            return;
        }
        // Ban IP addresses which are blocked for registration
        if (!BannedIPInfoProvider.IsAllowed(CurrentSiteName, BanControlEnum.Registration))
        {
            ShowError(GetString("banip.ipisbannedregistration"));
            return;
        }

        // Check if captcha is required and verify captcha text
        if (DisplayCaptcha && !captchaElem.IsValid())
        {
            // Display error message if captcha text is not valid
            ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError"));
            return;
        }

        string userName   = String.Empty;
        string nickName   = String.Empty;
        string emailValue = String.Empty;

        // Check duplicate user
        // 1. Find appropriate control and get its value (i.e. user name)
        // 2. Try to find user info
        FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];

        if (txtUserName != null)
        {
            userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
        }

        FormEngineUserControl txtEmail = formUser.FieldControls["Email"];

        if (txtEmail != null)
        {
            emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
        }

        // If user name and e-mail aren't filled stop processing and display error.
        if (string.IsNullOrEmpty(userName))
        {
            userName = emailValue;
            if (String.IsNullOrEmpty(emailValue))
            {
                formUser.StopProcessing = true;
                formUser.DisplayErrorLabel("Email", GetString("customregistrationform.usernameandemail"));
                return;
            }

            // Set username after data retrieval in case the username control is hidden (visible field hidden in custom layout)
            formUser.OnBeforeSave += (s, args) => formUser.Data.SetValue("UserName", userName);
        }

        FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];

        if (txtNickName != null)
        {
            nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
        }

        // Test if "global" or "site" user exists.
        SiteInfo si     = SiteContext.CurrentSite;
        UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));

        if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
        {
            ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))));
            return;
        }

        // Check for reserved user names like administrator, sysadmin, ...
        if (UserInfoProvider.NameIsReserved(CurrentSiteName, userName))
        {
            ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))));
            return;
        }

        if (UserInfoProvider.NameIsReserved(CurrentSiteName, nickName))
        {
            ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName)));
            return;
        }

        // Check limitations for site members
        if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
        {
            ShowError(GetString("License.MaxItemsReachedSiteMember"));
            return;
        }

        // Check whether email is unique if it is required
        if (!UserInfoProvider.IsEmailUnique(emailValue, SiteList, 0))
        {
            formUser.DisplayErrorLabel("Email", GetString("UserInfo.EmailAlreadyExist"));
            return;
        }

        formUser.SaveData(null, String.IsNullOrEmpty(DisplayMessage.Trim()));
    }
예제 #12
0
 // Start is called before the first frame update
 void Start()
 {
     displayMessage = this.GetComponent <DisplayMessage>();
     audioSource    = this.GetComponent <AudioSource>();
 }
예제 #13
0
 public void ShowWarningDialog()
 {
     _dialogResult = DisplayMessage.Show(MessageId.TempPostPermission, _owner, ApplicationEnvironment.ProductName_Short);
 }
예제 #14
0
 public void Handler()
 {
     _dialogResult = DisplayMessage.Show(_messageId, _owner, _parameters);
 }
예제 #15
0
        /// <summary>
        /// Возвращает количество пользователей подключенных к БД db
        /// </summary>
        /// <param name="db">строка подключения к БД</param>
        /// <param name="output">Делегат вывода сообщений - если указан - будет выведен список подключенных пользователей к БД</param>
        /// <returns>Количество подключенных пользователей к БД +1 (наше соедиенение до БД)</returns>
        public int ConnectedUsersCount(string db, DisplayMessage output = null)
        {
            using (FbConnection fc = new FbConnection(db))
            {
                fc.Open();
                FbCommand fcmd = new FbCommand(Properties.Resources.FBMonCnt, fc);
                int MonCnt = (int)fcmd.ExecuteScalar();
                if (output != null)
                {
                    if (MonCnt > 1)
                    {
                        output(string.Format("К БД подключены следующие пользователи ({0}, не считая нас):", MonCnt - 1));
                        fcmd.CommandText = Properties.Resources.FBMon;
                        using (FbDataReader fbdr = fcmd.ExecuteReader())
                        {
                            while (fbdr.Read())
                            {
                                string s1 = "";
                                for (int z = 0; z < fbdr.FieldCount; z++)
                                {
                                    s1 += (string.IsNullOrEmpty(s1) ? "" : ":") + fbdr.GetValue(z).ToString();
                                }
                                if (!s1.Contains(Application.ExecutablePath)) output(s1);
                            }
                        }
                    }
                    else output("К БД подключены только мы.");
                }

                fc.Close();
                return MonCnt;
            }
        }
예제 #16
0
        static void Main(string[] args)
        {
            PlayerInfoDel ronaldinho = new PlayerInfoDel(DisplayInformation);

            ronaldinho();

            PlayerInfoWithNameDel playerName = new PlayerInfoWithNameDel(DisplayInformation);

            playerName("Messi");

            PlayerInfoNameWithGoalsDel newPlayer = new PlayerInfoNameWithGoalsDel(DisplayInformation);

            newPlayer("Ronaldo", 60);
            newPlayer("Rooney", 25);

            PlayerBasedOnNumber number = new PlayerBasedOnNumber(DisplayInformation);

            Console.WriteLine(number(8));
            Console.WriteLine(number(10));

            PlayerInformationWithGoals            playerOne = new PlayerInformationWithGoals(DisplayInformation2);
            PlayerInformationBasedOnNumberAndClub playerTwo = new PlayerInformationBasedOnNumberAndClub(DisplayInformation2);

            //playerOne("Ronaldo", 50);
            //playerTwo(7, "Real Madrid","Portugal");

            Console.WriteLine(playerTwo.Method);

            foreach (var item in playerTwo.Method.GetParameters())
            {
                Console.WriteLine($"{item.ParameterType.Name}, {item.Name}, {item.Position}, {item.IsOptional}, {item.DefaultValue} ");
            }

            SayHiDelegate sayHi = null;

            sayHi  = new SayHiDelegate(SayHiEnglish);
            sayHi += new SayHiDelegate(SayHiSpanish);
            sayHi += new SayHiDelegate(SayHiJapanese);
            sayHi += new SayHiDelegate(SayHiItalian);
            sayHi += new SayHiDelegate(SayHiGerman);
            sayHi += new SayHiDelegate(SayHiArabic);

            sayHi();

            //genreic delegate
            Console.WriteLine("------Generic Delegate------");
            DisplayInfo <int> myNumber = new DisplayInfo <int>(DisplayValue);

            Console.WriteLine(myNumber(42));

            DisplayInfo <double> myDoubleNumber = new DisplayInfo <double>(DisplayValue);

            Console.WriteLine(myDoubleNumber(34.32));

            DisplayInfo <DateTime> myDate = new DisplayInfo <DateTime>(DisplayValue);

            Console.WriteLine(myDate(new DateTime(2010, 2, 23)));

            //Anonymous Method
            Multiply MultiplyNumber = delegate(int n) { { return(n * 3); } };

            Console.WriteLine(MultiplyNumber(10));

            DisplayMessage Message = delegate { Console.WriteLine("Hi from the anonymous method "); };

            Message();

            //Lambda\
            Console.WriteLine("-------Lambda-------");
            MultiplyLambda MultiplyNumberLambda = n => n * 3;

            Console.WriteLine(MultiplyNumber(10));

            DisplayMessageLambda MessageLambda = () => Console.WriteLine("Hi from anonymous lambda");

            Message();

            //Func Delegate
            Console.WriteLine("------Func Delegate-----");
            Func <int, int, int> funcOne = AddTwoNumbers;

            Console.WriteLine(AddTwoNumbers(3, 5));

            Func <int> funcTwo = AddTwoNumbers;

            Console.WriteLine(funcTwo());

            //Action Delegate
            Console.WriteLine("------Action Delegate--------");
            Action <int> actionOne = DisplayInformationActionDelegate;

            actionOne(16);

            Action actionTwo = DisplayInformationActionDelegate;

            actionTwo();

            //Predict Delegate
            Console.WriteLine("-------Predict Delegate------");
            Predicate <int> condition = IsAdmin;

            Console.WriteLine(condition(11));
            Console.WriteLine(condition(10));
        }
예제 #17
0
 private void ActiveConnectorOnDisplayMessage(object sender, MessageArgs messageArgs)
 {
     DisplayMessage?.Invoke(this, messageArgs);
 }
예제 #18
0
    protected void lbSelected_Command(object sender, CommandEventArgs e)
    {
        int result = 0;

        try
        {
            string userDomainName = e.CommandArgument.ToString();
            if (userDomainName.ToLower().Contains("founder\\"))
            {
                userDomainName = "founder\\" + userDomainName;
            }

            WorkflowHelper.ForwardToNextApprover_Change(_BPMContext.Sn, _BPMContext.CurrentUser.LoginId, userDomainName);

            string Opinion = Request["optionTxt"];

            //2015-1-26 对转签的已办做增加Item处理,去掉为空意见优化
            string ApproveResult    = "转签";
            string OpinionType      = "";
            string IsSign           = "2";
            string DelegateUserName = "";
            string DelegateUserCode = "";

            WorkFlowInstance workFlowInstance = new WF_WorkFlowInstance().GetWorkFlowInstanceById(_BPMContext.ProcID);
            var appRecord = new Pkurg.PWorldBPM.Business.Sys.WF_Approval_Record()
            {
                ApprovalID        = Guid.NewGuid().ToString(),
                WFTaskID          = K2_TaskItem.ID,
                FormID            = workFlowInstance.FormId,
                InstanceID        = workFlowInstance.InstanceId,
                Opinion           = Opinion,
                ApproveAtTime     = DateTime.Now,
                ApproveByUserCode = _BPMContext.CurrentPWordUser.EmployeeCode,
                ApproveByUserName = _BPMContext.CurrentPWordUser.EmployeeName,
                ApproveResult     = ApproveResult,
                OpinionType       = OpinionType,
                CurrentActiveName = CustomWorkflowHelper.SuperNodeName == K2_TaskItem.ActivityInstanceDestination.Name ? CustomWorkflowDataProcess.GetCurrentStepNameById(_BPMContext.ProcID, K2_TaskItem.ActivityInstanceDestination.Name) : K2_TaskItem.ActivityInstanceDestination.Name,
                ISSign            = IsSign,
                CurrentActiveID   = K2_TaskItem.ActivityInstanceDestination.ActID.ToString(),
                DelegateUserName  = DelegateUserName,
                DelegateUserCode  = DelegateUserCode,
                CreateAtTime      = K2_TaskItem.ActivityInstanceDestination.StartDate,
                CreateByUserCode  = _BPMContext.CurrentPWordUser.EmployeeCode,
                CreateByUserName  = _BPMContext.CurrentPWordUser.EmployeeName,
                UpdateAtTime      = DateTime.Now,
                UpdateByUserCode  = _BPMContext.CurrentPWordUser.EmployeeCode,
                UpdateByUserName  = _BPMContext.CurrentPWordUser.EmployeeName,
                FinishedTime      = DateTime.Now
            };

            if (new BFApprovalRecord().AddApprovalRecord(appRecord))
            {
                if (new WF_WorkFlowInstance().UpdateStatus(workFlowInstance.WfInstanceId,
                                                           "1", K2_TaskItem.ActivityInstanceDestination.ID.ToString(),
                                                           K2_TaskItem.ActivityInstanceDestination.Name, K2_TaskItem.ID, null,
                                                           _BPMContext.CurrentPWordUser))
                {
                    result = 1;
                }
            }
        }
        catch (Exception)
        {
        }
        DisplayMessage.ExecuteJs(string.Format("window.returnValue = {0};window.close();", result));
    }
예제 #19
0
    private void SaveWorkItemDataToTemplation()//Pkurg.PWorldBPM.Business.Sys.WF_Custom_InstanceItems itemInfo)
    {
        int result = 0;

        string FormId = Request["FormId"];

        try
        {
            var itemList = CustomWorkflowDataProcess.GetWorkItemsData(FormId);
            if (itemList == null)
            {
                DisplayMessage.ExecuteJs(string.Format("window.returnValue = {0};window.close();", result));
                return;
            }
            string syncString = string.Empty;
            lock (syncString)
            {
                int maxId = 1;
                if (SysContext.WF_Custom_Templation.Count() > 0)
                {
                    maxId = SysContext.WF_Custom_Templation.Max(x => x.Id) + 1;
                    if (maxId <= 0)
                    {
                        maxId = 1;
                    }
                }

                SysContext.WF_Custom_Templation.InsertOnSubmit(new Pkurg.PWorldBPM.Business.Sys.WF_Custom_Templation()
                {
                    Id                 = maxId,
                    CreateTime         = DateTime.Now,
                    Name               = tbStepName.Text,
                    CreateUserID       = _BPMContext.CurrentPWordUser.EmployeeCode,
                    CreateUserDeptCode = _BPMContext.CurrentPWordUser.DepartCode,
                    CreateUserName     = _BPMContext.CurrentPWordUser.EmployeeName,
                    LastUpdateTime     = DateTime.Now,
                    IsOpen             = cbIsOpen.Checked ? 1 : 0,
                    RelationDeptCode   = GetCheckDept(),
                    Des                = tbDes.Text
                });


                long stepId = 1;
                if (SysContext.WF_Custom_TemplationItems.Count() > 0)
                {
                    stepId = SysContext.WF_Custom_TemplationItems.Max(x => x.StepID) + 1;
                }
                foreach (var item in itemList)
                {
                    SysContext.WF_Custom_TemplationItems.InsertOnSubmit(new Pkurg.PWorldBPM.Business.Sys.WF_Custom_TemplationItems()
                    {
                        TemplD     = maxId,
                        CreateTime = DateTime.Now,
                        PartUsers  = item.PartUsers,
                        OrderId    = item.OrderId,
                        StepID     = stepId++,
                        StepName   = item.StepName,
                        Condition  = item.Condition
                    });
                }
                SysContext.SubmitChanges();
            }
            result = 1;
        }
        catch (Exception)
        {
            //
        }
        DisplayMessage.ExecuteJs(string.Format("window.returnValue = {0};window.close();", result));
    }
예제 #20
0
 protected void ShowValidationError(Control control, MessageId displayMessageType, params object[] args)
 {
     DisplayMessage.Show(displayMessageType, control.FindForm(), args);
     control.Focus();
 }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName   = String.Empty;
            string nickName   = String.Empty;
            string firstName  = String.Empty;
            string lastName   = String.Empty;
            string emailValue = String.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            if (txtUserName != null)
            {
                userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            }

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName))
            {
                userName = emailValue;
                if (String.IsNullOrEmpty(emailValue))
                {
                    formUser.StopProcessing = true;
                    lblError.Visible        = true;
                    lblError.Text           = GetString("customregistrationform.usernameandemail");
                    return;
                }
                else
                {
                    formUser.Data.SetValue("UserName", userName);
                }
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            // Test if "global" or "site" user exists.
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
            if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                return;
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Validate and save form with new user data
            if (!formUser.Save())
            {
                // Return if saving failed
                return;
            }

            // Get user info from form
            UserInfo ui = (UserInfo)formUser.Info;

            // Add user prefix if settings is on
            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign    = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            // Fill optionally full user name
            if (String.IsNullOrEmpty(ui.FullName))
            {
                ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
            }

            // Ensure nick name
            if (ui.UserNickName.Trim() == String.Empty)
            {
                ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
            }

            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
            ui.UserSettings.UserLogActivities        = true;
            ui.UserSettings.UserShowIntroductionTile = true;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            // Get user password and save it in apropriate format after form save
            string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
            UserInfoProvider.SetPassword(ui, password);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            // Prepare macro replacements
            string[,] replacements = new string[6, 2];
            replacements[0, 0]     = "confirmaddress";
            replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
            replacements[1, 0]     = "username";
            replacements[1, 1]     = userName;
            replacements[2, 0]     = "password";
            replacements[2, 1]     = password;
            replacements[3, 0]     = "Email";
            replacements[3, 1]     = emailValue;
            replacements[4, 0]     = "FirstName";
            replacements[4, 1]     = firstName;
            replacements[5, 0]     = "LastName";
            replacements[5, 1]     = lastName;

            // Set resolver
            resolver.SetNamedSourceData(replacements);

            // Email message
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.EmailFormat = EmailFormatEnum.Default;
            emailMessage.Recipients  = ui.Email;

            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                }
            }

            if (template != null)
            {
                emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                // Enable macro encoding for body
                resolver.Settings.EncodeResolvedValues = true;
                emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                // Disable macro encoding for plaintext body and subject
                resolver.Settings.EncodeResolvedValues = false;
                emailMessage.PlainTextBody             = resolver.ResolveMacros(template.TemplatePlainText);
                emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                emailMessage.CcRecipients  = template.TemplateCc;
                emailMessage.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(currentSiteName, emailMessage, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                }

                if (mEmailTemplate == null)
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    // E-mail template ok
                    replacements       = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = userName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(currentSiteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                {
                    HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }

                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Site and roles addition and authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string siteName in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, sn))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlRegForm.Visible = false;
                lblInfo.Visible    = true;
                lblInfo.Text       = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty);
                if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash")))
                {
                    URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
                }
                else if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion


            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch");
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text    = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verifiy captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = txtEmail.Text.Trim();
            ui.FirstName      = txtFirstName.Text.Trim();
            ui.LastName       = txtLastName.Text.Trim();
            ui.FullName       = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName     = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign    = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")))
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion


            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text    = errorMessage;
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);
            resolver.Settings.EncodeResolvedValues = true;

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Retrieve contact ID for confirmation e-mail
                int contactId = 0;
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    // Check if loggin registration activity is enabled
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                    }
                }

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator, contactId);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = plainUserName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = passStrength.Text;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = txtEmail.Text;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = txtFirstName.Text;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = txtLastName.Text;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;

                email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress"));
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.Settings.EncodeResolvedValues = false;
                email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject       = resolver.ResolveMacros(emailSubject);

                email.CcRecipients  = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    string[,] replacements = new string[4, 2];
                    replacements[0, 0]     = "firstname";
                    replacements[0, 1]     = ui.FirstName;
                    replacements[1, 0]     = "lastname";
                    replacements[1, 1]     = ui.LastName;
                    replacements[2, 0]     = "email";
                    replacements[2, 1]     = ui.Email;
                    replacements[3, 0]     = "username";
                    replacements[3, 1]     = plainUserName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);

                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    resolver.Settings.EncodeResolvedValues = false;
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWithCSafe(".") ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
                    }
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
예제 #23
0
 public Task DisplayMessageAsync(string method, string message)
 {
     return(DisplayMessage?.Invoke(method, message) ?? Task.CompletedTask);
 }
        public void EnsureLoggedIn(string username, string password, string service, bool showUi, string uri)
        {
            try
            {
                if (IsValid(username, password, service))
                {
                    return;
                }

                string captchaToken = null;
                string captchaValue = null;

                string source = string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", ApplicationEnvironment.CompanyName, ApplicationEnvironment.ProductName, ApplicationEnvironment.ProductVersion);

                while (true)
                {
                    GoogleLoginRequestFactory glrf = new GoogleLoginRequestFactory(username,
                                                                                   password,
                                                                                   service,
                                                                                   source,
                                                                                   captchaToken,
                                                                                   captchaValue);
                    if (captchaToken != null && captchaValue != null)
                    {
                        captchaToken = null;
                        captchaValue = null;
                    }

                    HttpWebResponse response;
                    try
                    {
                        response = RedirectHelper.GetResponse(uri, new RedirectHelper.RequestFactory(glrf.Create));
                    }
                    catch (WebException we)
                    {
                        response = (HttpWebResponse)we.Response;
                        if (response == null)
                        {
                            Trace.Fail(we.ToString());
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.WeblogConnectionError, we.Message);
                            }
                            throw;
                        }
                    }

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Hashtable ht = ParseAuthResponse(response.GetResponseStream());
                        if (ht.ContainsKey("Auth"))
                        {
                            _auths[new AuthKey(username, password, service)] = new AuthValue((string)ht["Auth"], ht["YouTubeUser"] as string);
                            return;
                        }
                        else
                        {
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.GoogleAuthTokenNotFound);
                            }
                            throw new BlogClientInvalidServerResponseException(uri, "No Auth token was present in the response.", string.Empty);
                        }
                    }
                    else if (response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        // login failed

                        Hashtable ht    = ParseAuthResponse(response.GetResponseStream());
                        string    error = ht["Error"] as string;
                        if (error != null && error == "CaptchaRequired")
                        {
                            captchaToken = (string)ht["CaptchaToken"];
                            string captchaUrl = (string)ht["CaptchaUrl"];

                            GDataCaptchaHelper helper = new GDataCaptchaHelper(
                                new Win32WindowImpl(BlogClientUIContext.ContextForCurrentThread.Handle),
                                captchaUrl);

                            BlogClientUIContext.ContextForCurrentThread.Invoke(new ThreadStart(helper.ShowCaptcha), null);

                            if (helper.DialogResult == DialogResult.OK)
                            {
                                captchaValue = helper.Reply;
                                continue;
                            }
                            else
                            {
                                throw new BlogClientOperationCancelledException();
                            }
                        }

                        if (showUi)
                        {
                            if (error == "NoLinkedYouTubeAccount")
                            {
                                if (DisplayMessage.Show(MessageId.YouTubeSignup, username) == DialogResult.Yes)
                                {
                                    ShellHelper.LaunchUrl(GLink.Instance.YouTubeRegister);
                                }
                                return;
                            }

                            showUi = false;

                            if (error == "BadAuthentication")
                            {
                                ShowError(MessageId.LoginFailed, ApplicationEnvironment.ProductNameQualified);
                            }
                            else
                            {
                                ShowError(MessageId.BloggerError, TranslateError(error));
                            }
                        }
                        throw new BlogClientAuthenticationException(error, TranslateError(error));
                    }
                    else
                    {
                        if (showUi)
                        {
                            showUi = false;
                            ShowError(MessageId.BloggerError, response.StatusCode + ": " + response.StatusDescription);
                        }
                        throw new BlogClientAuthenticationException(response.StatusCode + "", response.StatusDescription);
                    }
                }
            }
            catch (BlogClientOperationCancelledException)
            {
                throw;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.ToString());
                if (showUi)
                {
                    ShowError(MessageId.UnexpectedErrorLogin, e.Message);
                }
                throw;
            }
        }
예제 #25
0
        protected void SendMessageToClients(string message, Action action)
        {
            MessageArgs args = new MessageArgs(message, action);

            DisplayMessage?.Invoke(this, args);
        }
 private void BtnTweetViewButtonClick()
 {
     MessageType           = "Tweet";
     ContentControlBinding = new DisplayMessage(MessageType);
     OnChanged(nameof(ContentControlBinding));
 }
예제 #27
0
        private static List <NewImageInfo> ScanImages(IBlogPostHtmlEditor currentEditor, IEditorAccount editorAccount, ContentEditor editor, bool useDefaultTargetSettings)
        {
            List <NewImageInfo> newImages = new List <NewImageInfo>();

            ApplicationPerformance.ClearEvent("InsertImage");
            ApplicationPerformance.StartEvent("InsertImage");

            using (new WaitCursor())
            {
                IHTMLElement2 postBodyElement = (IHTMLElement2)((BlogPostHtmlEditorControl)currentEditor).PostBodyElement;
                if (postBodyElement != null)
                {
                    foreach (IHTMLElement imgElement in postBodyElement.getElementsByTagName("img"))
                    {
                        string imageSrc = imgElement.getAttribute("srcDelay", 2) as string;

                        if (string.IsNullOrEmpty(imageSrc))
                        {
                            imageSrc = imgElement.getAttribute("src", 2) as string;
                        }

                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                        // decorator settings. "wlCopySrcUrl" is inserted while copy/pasting within canvas.
                        bool   copyDecoratorSettings = false;
                        string attributeCopySrcUrl   = imgElement.getAttribute("wlCopySrcUrl", 2) as string;
                        if (!string.IsNullOrEmpty(attributeCopySrcUrl))
                        {
                            copyDecoratorSettings = true;
                            imgElement.removeAttribute("wlCopySrcUrl", 0);
                        }

                        // Check if we need to apply default values for image decorators
                        bool   applyDefaultDecorator       = true;
                        string attributeNoDefaultDecorator = imgElement.getAttribute("wlNoDefaultDecorator", 2) as string;
                        if (!string.IsNullOrEmpty(attributeNoDefaultDecorator) && string.Compare(attributeNoDefaultDecorator, "TRUE", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            applyDefaultDecorator = false;
                            imgElement.removeAttribute("wlNoDefaultDecorator", 0);
                        }

                        string applyDefaultMargins = imgElement.getAttribute("wlApplyDefaultMargins", 2) as string;
                        if (!String.IsNullOrEmpty(applyDefaultMargins))
                        {
                            DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);
                            MarginStyle          defaultMargin        = defaultImageSettings.GetDefaultImageMargin();
                            // Now apply it to the image
                            imgElement.style.marginTop    = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Top);
                            imgElement.style.marginLeft   = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Left);
                            imgElement.style.marginBottom = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Bottom);
                            imgElement.style.marginRight  = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Right);
                            imgElement.removeAttribute("wlApplyDefaultMargins", 0);
                        }

                        if ((UrlHelper.IsFileUrl(imageSrc) || IsFullPath(imageSrc)) && !ContentSourceManager.IsSmartContent(imgElement))
                        {
                            Uri imageSrcUri = new Uri(imageSrc);
                            try
                            {
                                BlogPostImageData imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, imageSrcUri);
                                Emoticon          emoticon  = EmoticonsManager.GetEmoticon(imgElement);
                                if (imageData == null && emoticon != null)
                                {
                                    // This is usually an emoticon copy/paste and needs to be cleaned up.
                                    Uri inlineImageUri = editor.EmoticonsManager.GetInlineImageUri(emoticon);
                                    imgElement.setAttribute("src", UrlHelper.SafeToAbsoluteUri(inlineImageUri), 0);
                                }
                                else if (imageData == null)
                                {
                                    if (!File.Exists(imageSrcUri.LocalPath))
                                    {
                                        throw new FileNotFoundException(imageSrcUri.LocalPath);
                                    }

                                    // WinLive 188841: Manually attach the behavior so that the image cannot be selected or resized while its loading.
                                    DisabledImageElementBehavior disabledImageBehavior = new DisabledImageElementBehavior(editor.IHtmlEditorComponentContext);
                                    disabledImageBehavior.AttachToElement(imgElement);

                                    Size sourceImageSize                      = ImageUtils.GetImageSize(imageSrcUri.LocalPath);
                                    ImagePropertiesInfo  imageInfo            = new ImagePropertiesInfo(imageSrcUri, sourceImageSize, new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag()));
                                    DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);

                                    // Make sure this is set because some imageInfo properties depend on it.
                                    imageInfo.ImgElement = imgElement;

                                    bool isMetafile = ImageHelper2.IsMetafile(imageSrcUri.LocalPath);
                                    ImageClassification imgClass = ImageHelper2.Classify(imageSrcUri.LocalPath);
                                    if (!isMetafile && ((imgClass & ImageClassification.AnimatedGif) != ImageClassification.AnimatedGif))
                                    {
                                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                                        // decorator settings.
                                        if (copyDecoratorSettings)
                                        {
                                            // Try to look up the original copied source image.
                                            BlogPostImageData imageDataOriginal = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, new Uri(attributeCopySrcUrl));
                                            if (imageDataOriginal != null && imageDataOriginal.GetImageSourceFile() != null)
                                            {
                                                // We have the original image reference, so lets make a clone of it.
                                                BlogPostSettingsBag originalBag            = (BlogPostSettingsBag)imageDataOriginal.ImageDecoratorSettings.Clone();
                                                ImageDecoratorsList originalDecoratorsList = new ImageDecoratorsList(editor.DecoratorsManager, originalBag);

                                                ImageFileData originalImageFileData = imageDataOriginal.GetImageSourceFile();
                                                Size          originalImageSize     = new Size(originalImageFileData.Width, originalImageFileData.Height);
                                                imageInfo = new ImagePropertiesInfo(originalImageFileData.Uri, originalImageSize, originalDecoratorsList);
                                            }
                                            else
                                            {
                                                // There are probably decorators applied to the image, but in a different editor so we can't access them.
                                                // We probably don't want to apply any decorators to this image, so apply blank decorators and load the
                                                // image as full size so it looks like it did before.
                                                imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                                imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                            }
                                        }
                                        else if (applyDefaultDecorator)
                                        {
                                            imageInfo.ImageDecorators = defaultImageSettings.LoadDefaultImageDecoratorsList();

                                            if ((imgClass & ImageClassification.TransparentGif) == ImageClassification.TransparentGif)
                                            {
                                                imageInfo.ImageDecorators.AddDecorator(NoBorderDecorator.Id);
                                            }
                                        }
                                        else
                                        {
                                            // Don't use default values for decorators
                                            imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                            imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                        }
                                    }
                                    else
                                    {
                                        ImageDecoratorsList decorators = new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag());
                                        decorators.AddDecorator(editor.DecoratorsManager.GetDefaultRemoteImageDecorators());
                                        imageInfo.ImageDecorators = decorators;
                                    }

                                    imageInfo.ImgElement       = imgElement;
                                    imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;

                                    //discover the "natural" target settings from the DOM
                                    string linkTargetUrl = imageInfo.LinkTargetUrl;
                                    if (linkTargetUrl == imageSrc)
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.IMAGE;
                                    }
                                    else if (!String.IsNullOrEmpty(linkTargetUrl) && !UrlHelper.IsFileUrl(linkTargetUrl))
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.URL;
                                    }
                                    else
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.NONE;
                                    }

                                    if (useDefaultTargetSettings)
                                    {
                                        if (!GlobalEditorOptions.SupportsFeature(ContentEditorFeature.SupportsImageClickThroughs) && imageInfo.DefaultLinkTarget == LinkTargetType.IMAGE)
                                        {
                                            imageInfo.DefaultLinkTarget = LinkTargetType.NONE;
                                        }

                                        if (imageInfo.LinkTarget == LinkTargetType.NONE)
                                        {
                                            imageInfo.LinkTarget = imageInfo.DefaultLinkTarget;
                                        }
                                        if (imageInfo.DefaultLinkOptions.ShowInNewWindow)
                                        {
                                            imageInfo.LinkOptions.ShowInNewWindow = true;
                                        }
                                        imageInfo.LinkOptions.UseImageViewer       = imageInfo.DefaultLinkOptions.UseImageViewer;
                                        imageInfo.LinkOptions.ImageViewerGroupName = imageInfo.DefaultLinkOptions.ImageViewerGroupName;
                                    }

                                    Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize();
                                    Size initialSize      = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, sourceImageSize);

                                    // add to list of new images
                                    newImages.Add(new NewImageInfo(imageInfo, imgElement, initialSize, disabledImageBehavior));
                                }
                                else
                                {
                                    // When switching blogs, try to adapt image viewer settings according to the blog settings.

                                    ImagePropertiesInfo imageInfo = new ImagePropertiesInfo(imageSrcUri, ImageUtils.GetImageSize(imageSrcUri.LocalPath), new ImageDecoratorsList(editor.DecoratorsManager, imageData.ImageDecoratorSettings));
                                    imageInfo.ImgElement = imgElement;
                                    // Make sure the new crop and tilt decorators get loaded
                                    imageInfo.ImageDecorators.MergeDecorators(DefaultImageSettings.GetImplicitLocalImageDecorators());
                                    string viewer = imageInfo.DhtmlImageViewer;
                                    if (viewer != editorAccount.EditorOptions.DhtmlImageViewer)
                                    {
                                        imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;
                                        imageInfo.LinkOptions      = imageInfo.DefaultLinkOptions;
                                    }

                                    // If the image is an emoticon, update the EmoticonsManager with the image's uri so that duplicate emoticons can point to the same file.
                                    if (emoticon != null)
                                    {
                                        editor.EmoticonsManager.SetInlineImageUri(emoticon, imageData.InlineImageFile.Uri);
                                    }
                                }
                            }
                            catch (ArgumentException e)
                            {
                                Trace.WriteLine("Could not initialize image: " + imageSrc);
                                Trace.WriteLine(e.ToString());
                            }
                            catch (DirectoryNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (FileNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (IOException e)
                            {
                                Debug.WriteLine("Image file cannot be read: " + imageSrc + " " + e);
                                DisplayMessage.Show(MessageId.FileInUse, imageSrc);
                            }
                        }
                    }
                }
            }

            return(newImages);
        }
 // And a simple method that invokes the provided DisplayMessage delegate with a value.
 public void DelegateRunner(DisplayMessage displayer)
 {
     Console.WriteLine("About to call...");
     displayer("this is the message");
     Console.WriteLine("Finished call.");
 }
예제 #29
0
 public QueryHandler()
 {
     _messenger      = new DisplayMessage();
     subQueryHandler = new SubQueryHandler();
 }
예제 #30
0
 public QueryHandler(SqlForm form)
 {
     _messenger      = new DisplayMessage(form);
     subQueryHandler = new SubQueryHandler();
 }
예제 #31
0
 public Brain(DisplayMessage displayMessageDelegate)
 {
     displayMessage = displayMessageDelegate;
 }
예제 #32
0
        static void Unzip(string source, string dest, DisplayMessage output)
        {
            if (!File.Exists(source))
            {
                throw new FileNotFoundException();
            }

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(source)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    try
                    {

                        //Console.WriteLine(theEntry.Name);
                        string fname = dest + (dest.EndsWith("\\") ? "" : "\\") + theEntry.Name;
                        string directoryName = Path.GetDirectoryName(fname);
                        string fileName = Path.GetFileName(fname);
                        output(fname);

                        // create directory
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(fname))
                            {

                                int size = 2048;
                                byte[] data = new byte[size];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0) streamWriter.Write(data, 0, size); else break;
                                }
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        output(ex.ToString());
                    }
                }
            }
        }
예제 #33
0
 protected void DisplayMessageToUser(DisplayMessage message)
 {
     TempData[DirtyGirlConfig.Settings.DisplayMessageKey] = message;
 }