private void ProcessRequest(Instance request) { try { var names = new UserName { FamilyName = String.IsNullOrEmpty(FamilyName) ? null : FamilyName, GivenName = String.IsNullOrEmpty(GivenName) ? null : GivenName }; var user = new User { PrimaryEmail = String.IsNullOrEmpty(PrimaryEmail) ? null : PrimaryEmail, Name = names, Suspended = Suspended, Password = String.IsNullOrEmpty(Password) ? null : Password, HashFunction = String.IsNullOrEmpty(HashFunction) ? null : HashFunction, ChangePasswordAtNextLogin = ChangePasswordAtNextLogon, IpWhitelisted = IpWhiteListed, OrgUnitPath = String.IsNullOrEmpty(OrgUnitPath) ? null : OrgUnitPath, IncludeInGlobalAddressList = IncludeInGlobalAddressList }; var service = request.DirectoryService.Users.Update(user, UserId); WriteObject(service.Execute()); } catch (Exception e) { Console.WriteLine("Failed to Update User!"); Console.WriteLine("Error: " + e); WriteObject(false); } }
public void TestUserConstructor() { Email email = new Email("*****@*****.**"); UserName name = new UserName("first","last"); User user = new User(email, name, "pwd123", null); Assert.AreEqual(user.Email.EmailAddress, email.EmailAddress); Assert.AreEqual(user.Name.FirstName, name.FirstName); }
/// <summary> /// Initializes a new instance of the <see cref="UpdateUserConfiguration"/> class /// with the specified values. /// </summary> /// <param name="name">A <see cref="UserName"/> object providing the new name and host for the user. If this value is <see langword="null"/>, the name and host address for the database user is not changed.</param> /// <param name="password">The new password for the user. If this value is <see langword="null"/>, the existing password for the database user is not changed.</param> public UpdateUserConfiguration(UserName name, string password) { if (name != null) { _name = name.Name; _host = name.Host; } _password = password; }
public void TestUserName() { var n0 = new UserName("%E3%82%82%E3%81%A8%E3%81%A1%E3%82%83%E3%82%93"); var n1 = new UserName("%E3%81%B5%E3%81%B2%E3%81%B2"); var n2 = new UserName("%E4%B8%8A%E6%B5%B7%E4%B8%80%E4%B9%9D%E5%9B%9B%E4%B8%89"); var n3 = new UserName("%73%70%69%6E%65%73"); Assert.AreEqual("もとちゃん", n0.Name, "n0"); Assert.AreEqual("ふひひ", n1.Name, "n1"); Assert.AreEqual("上海一九四三", n2.Name, "n2"); Assert.AreEqual("spines", n3.Name, "n3"); }
public void ShouldTestValidUserLogin() { UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); User user = new User(email, name, "pwd", null); _mockRepository.Setup(ur => ur.LoadUser(user.EmailAddress)).Returns(user); UserRegistration.UserRegistrationService service = new UserRegistrationService(_mockRepository.Object); Assert.True(service.AreCredentialsValid(email.EmailAddress, user.Password)); }
public void ShouldRegisterUserIfNotDuplicate() { Mock<IUserRepository> mockRepository = new Mock<IUserRepository>(); UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); User user = new User(email, name, "pwd", null); mockRepository.Setup(ur => ur.LoadUser(user.EmailAddress)).Returns((User)null); mockRepository.Setup(ur => ur.SaveUser(user)); new UserRegistrationService(mockRepository.Object).CreateUser(user); mockRepository.Verify(ur => ur.LoadUser(user.EmailAddress)); mockRepository.Verify(ur => ur.SaveUser(user)); }
public void ShouldNotRegisterIfDuplicate() { Mock<IUserRepository> mockRepository = new Mock<IUserRepository>(); UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); User user = new User(email, name, "pwd", null); mockRepository.Setup(ur => ur.LoadUser(user.EmailAddress)).Returns(user); Assert.Throws(typeof(DuplicateRegistrationException), delegate() { new UserRegistrationService(mockRepository.Object). CreateUser(user); }); mockRepository.Verify(ur => ur.LoadUser(user.EmailAddress)); }
public void TestLoadUserByEmailAddress() { UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); User user = new User(email, name, "pwd", null); IUserRepository userRepository = UserRepository.Instance; userRepository.SaveUser(user); var loadedUser = userRepository.LoadUser("*****@*****.**"); try { Assert.AreEqual(user.Email.EmailAddress, loadedUser.Email.EmailAddress); }finally { userRepository.Delete(user); } }
public UserName[] List(int startIndex, int count) { if (startIndex < 0 || startIndex + count > this.users.Count) { throw new ArgumentOutOfRangeException("Invalid start index or count."); } UserName[] listOfSelectedUsers = new UserName[count]; for (int currentIndex = startIndex; currentIndex <= startIndex + count - 1; currentIndex++) { UserName currentUser = this.sortedUsers[currentIndex]; listOfSelectedUsers[currentIndex - startIndex] = currentUser; } return listOfSelectedUsers; }
public void TestUserGroupAssociation() { UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); UserGroup userGroup=new UserGroup{Id = 4,Name = "Pune",}; User user = new User(email, name, "pwd", userGroup); IUserRepository userRepository = UserRepository.Instance; userRepository.SaveUser(user); var loadedUser = userRepository.LoadUser("*****@*****.**"); try { Assert.AreEqual(userGroup,loadedUser.UserGroup); } finally { userRepository.Delete(user); } }
public bool AddPhone(string name, IEnumerable<string> phones) { var usersWithSameName = from user in this.users where user.Name.ToLowerInvariant() == name.ToLowerInvariant() select user; bool isAddNewUser; if (usersWithSameName.Count() == 0) { UserName user = new UserName(); user.Name = name; user.Strings = new SortedSet<string>(); foreach (var phone in phones) { user.Strings.Add(phone); } this.users.Add(user); isAddNewUser = true; } else if (usersWithSameName.Count() == 1) { UserName user = usersWithSameName.First(); foreach (var phone in phones) { user.Strings.Add(phone); } isAddNewUser = false; } else { Console.WriteLine("Duplicated name in the phonebook found: " + name); return false; } return isAddNewUser; }
public bool AddPhone(string name, IEnumerable<string> phones) { string nameToLowerInvariant = name.ToLowerInvariant(); UserName user; bool isEmpty = !this.users.TryGetValue(nameToLowerInvariant, out user); if (isEmpty) { user = new UserName(); user.Name = name; user.Strings = new SortedSet<string>(); this.users.Add(nameToLowerInvariant, user); this.sortedUsers.Add(user); } foreach (var phone in phones) { this.phonebook.Add(phone, user); } user.Strings.UnionWith(phones); return isEmpty; }
/// <summary> /// Check out the files from Live SVN repository for particular date, here we had used commandprompt command to do so /// Input: User details username, password, backup/restored date and live svn server url /// Output: Checking out the files from Live SVN repository /// </summary> public void mtdChkLive() { try { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C svn co -r {\"" + BackupDate + " 23:59:59\"} " + LiveURL.Trim() + " \"" + LocalDrive.Trim() + "\\svn-compare\\checkout\" --username " + UserName.Trim() + " --password " + Password.Trim(); process.StartInfo = startInfo; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); StringBuilder proc = new StringBuilder(); while (!process.HasExited) { proc.Append(process.StandardOutput.ReadToEnd()); } ChkLiveCmd = "\n" + startInfo.Arguments.Replace(" --password " + Password, " --password *******"); ChkLive = "\n" + proc.ToString().Trim(); liveVersion = FindVersion(ChkLive).ToString().Split(' ').Last().Replace(".", ""); totalLiveFile = TotalFiles(ChkLive).ToString(); startInfo = null; process = null; } catch (Exception chklive) { Error = chklive.Message.ToString(); } }
public override int GetHashCode() { return(UserName.GetHashCode()); }
protected override void Execute(NativeActivityContext context) { RestSharp.RestClient client = new RestSharp.RestClient(); MCser.SoapClient soapClient = null; String ExistAuthToken = "" + ExistingAuth.Get(context); String ExistServiceURL = "" + ExistingServ.Get(context); if (ExistAuthToken.Trim().Length > 1) { RespAuthToken = ExistAuthToken.Trim(); RespServiceURL = ExistServiceURL.Trim(); } else { String sfdcConsumerkey = ""; String sfdcConsumerSecret = ""; String sfdcServiceURL = ""; String sfdcUserName = ""; String sfdcPassword = ""; Boolean EnvType = (EnvironmentType == Type_of_Environment.Design_and_Test) ? true : false; if (EnvType) { sfdcConsumerkey = ConsumerKey.Get(context); sfdcConsumerSecret = ConsumerSecret.Get(context); sfdcServiceURL = ServiceURL.Get(context); sfdcUserName = UserName.Get(context); sfdcPassword = Password.Get(context); } else { sfdcConsumerkey = ConsumerKeyProd.Get(context); sfdcConsumerSecret = SecureStringToString(ConsumerSecretProd.Get(context)); sfdcServiceURL = "" + SecureStringToString(ServiceURLProd.Get(context)); sfdcUserName = UserNameProd.Get(context); sfdcPassword = SecureStringToString(PasswordProd.Get(context)); } try { client.BaseUrl = new Uri("https://auth.exacttargetapis.com/v1/requestToken"); var request2 = new RestRequest(Method.POST); request2.RequestFormat = DataFormat.Json; request2.AddParameter("clientId", sfdcConsumerkey); request2.AddParameter("clientSecret", sfdcConsumerSecret); JObject jsonObj = JObject.Parse(client.Post(request2).Content); RespAuthToken = (String)jsonObj["accessToken"]; String ErrorType = ""; ErrorType = (String)jsonObj["error"]; String ErrorMsg = ""; ErrorMsg = (String)jsonObj["error_description"]; if ((RespAuthToken != null && RespAuthToken != "") && ErrorMsg == null) { BasicHttpsBinding binding = new BasicHttpsBinding(); binding.Name = "MyServicesSoap"; binding.CloseTimeout = TimeSpan.FromMinutes(1); binding.OpenTimeout = TimeSpan.FromMinutes(1); binding.ReceiveTimeout = TimeSpan.FromMinutes(60); binding.SendTimeout = TimeSpan.FromMinutes(1); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MaxBufferSize = 20000000; binding.MaxBufferPoolSize = 20000000; binding.MaxReceivedMessageSize = 20000000; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; binding.ReaderQuotas.MaxDepth = 32; binding.ReaderQuotas.MaxStringContentLength = 8192; binding.ReaderQuotas.MaxArrayLength = 16384; binding.ReaderQuotas.MaxBytesPerRead = 4096; binding.ReaderQuotas.MaxNameTableCharCount = 16384; binding.Security.Mode = BasicHttpsSecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; binding.Security.Transport.Realm = ""; binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default; String endpointStr = "https://webservice.s10.exacttarget.com/Service.asmx"; EndpointAddress endpoint = new EndpointAddress(endpointStr); soapClient = new MCser.SoapClient(binding, endpoint); soapClient.ClientCredentials.UserName.UserName = sfdcUserName; soapClient.ClientCredentials.UserName.Password = sfdcPassword; soapClient.Endpoint.EndpointBehaviors.Add(new FuelOAuthHeaderBehavior(RespAuthToken)); RespServiceURL = sfdcServiceURL; } else if (RespAuthToken == null && (ErrorMsg != "" && ErrorMsg != null)) { RespAuthToken = "Error Type: " + ErrorType; RespServiceURL = "Error: " + ErrorMsg; } } catch (Exception ex) { RespAuthToken = "Error Type: " + ex.ToString(); RespServiceURL = "Error: " + ex.ToString(); } } var salesForceProperty = new SalesForceProperty(soapClient, true, RespAuthToken, RespServiceURL); if (Body != null) { context.ScheduleAction <SalesForceProperty>(Body, salesForceProperty, OnCompleted, OnFaulted); } }
public User Find(UserName name) { throw new System.NotImplementedException(); }
protected void Page_Load(object sender, EventArgs e) { IsUseFriendlyUrls=pagebase.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls); UserName.Focus(); if (!IsPostBack) { HideSignUp(); Password.Attributes.Add("onkeypress", "return clickButton(event,'" + LoginButton.ClientID + "')"); hypForgetPassword.Text = "Forgot Password?"; if (IsUseFriendlyUrls) { if (GetPortalID > 1) { signup.Attributes.Add("href", ResolveUrl("~/portal/" + GetPortalSEOName + "/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalRegistrationPage) + ".aspx")); signup1.Attributes.Add("href", ResolveUrl("~/portal/" + GetPortalSEOName + "/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalRegistrationPage) + ".aspx")); hypForgetPassword.NavigateUrl = ResolveUrl("~/portal/" + GetPortalSEOName + "/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalForgotPassword) + ".aspx"); } else { signup.Attributes.Add("href", ResolveUrl("~/User-Registration.aspx")); signup1.Attributes.Add("href", ResolveUrl("~/User-Registration.aspx")); hypForgetPassword.NavigateUrl = ResolveUrl("~/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalForgotPassword) + ".aspx"); } } else { hypForgetPassword.NavigateUrl = ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalForgotPassword)); signup.Attributes.Add("href", ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm="+pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalRegistrationPage))); signup1.Attributes.Add("href", ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm="+pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalRegistrationPage))); } if (pagebase.GetSettingBollByKey(SageFrameSettingKeys.RememberCheckbox)) { RememberMe.Visible = true; lblrmnt.Visible = true; } else { RememberMe.Visible = false; lblrmnt.Visible = false; } } if (HttpContext.Current.User != null) { MembershipUser user = Membership.GetUser(); FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity; if (identity != null) { FormsAuthenticationTicket ticket = identity.Ticket; int LoggedInPortalID = int.Parse(ticket.UserData.ToString()); if (user != null && user.UserName != "") { string[] sysRoles = SystemSetting.SUPER_ROLE; if (GetPortalID == LoggedInPortalID || Roles.IsUserInRole(user.UserName, sysRoles[0])) { RoleController _role = new RoleController(); string userinroles = _role.GetRoleNames(GetUsername, LoggedInPortalID); if (userinroles != "" || userinroles != null) { MultiView1.ActiveViewIndex = 1; } else { MultiView1.ActiveViewIndex = 0; } } else { MultiView1.ActiveViewIndex = 0; } } else { MultiView1.ActiveViewIndex = 0; } } else { MultiView1.ActiveViewIndex = 0; } } }
public void LoginMiddleTest(string name, string password) { UserName.EnterText(name); UserPassword.EnterText(password); }
private void Button1_Click(System.Object sender, System.EventArgs e) { try { int RowsAffected = 0; if (Strings.Len(Strings.Trim(cmbUserType.Text)) == 0) { MessageBox.Show("Please select user type", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); cmbUserType.Focus(); return; } if (Strings.Len(Strings.Trim(UserName.Text)) == 0) { MessageBox.Show("Please enter user name", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); UserName.Focus(); return; } if (Strings.Len(Strings.Trim(OldPassword.Text)) == 0) { MessageBox.Show("Please enter old password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); OldPassword.Focus(); return; } if (Strings.Len(Strings.Trim(NewPassword.Text)) == 0) { MessageBox.Show("Please enter new password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); NewPassword.Focus(); return; } if (Strings.Len(Strings.Trim(ConfirmPassword.Text)) == 0) { MessageBox.Show("Please confirm new password", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ConfirmPassword.Focus(); return; } if (NewPassword.TextLength < 5) { MessageBox.Show("The New Password Should be of Atleast 5 Characters", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); NewPassword.Text = ""; ConfirmPassword.Text = ""; NewPassword.Focus(); return; } else if (NewPassword.Text != ConfirmPassword.Text) { MessageBox.Show("Password do not match", "Input error", MessageBoxButtons.OK, MessageBoxIcon.Error); NewPassword.Text = ""; OldPassword.Text = ""; ConfirmPassword.Text = ""; OldPassword.Focus(); return; } else if (OldPassword.Text == NewPassword.Text) { MessageBox.Show("Password is same..Re-enter new password", "Input error", MessageBoxButtons.OK, MessageBoxIcon.Error); NewPassword.Text = ""; ConfirmPassword.Text = ""; NewPassword.Focus(); return; } con = new OleDbConnection(ck); con.Open(); string co = "update Registration set user_password = '******'where username='******' and user_password = '******' and usertype='" + cmbUserType.Text + "'"; cmd = new OleDbCommand(co); cmd.Connection = con; RowsAffected = cmd.ExecuteNonQuery(); if (RowsAffected > 0) { MessageBox.Show("Successfully changed", "Password", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Hide(); My.MyProject.Forms.Frmlogin.Show(); My.MyProject.Forms.Frmlogin.cmbUserType.Text = ""; My.MyProject.Forms.Frmlogin.txtUsername.Text = ""; My.MyProject.Forms.Frmlogin.txtPassword.Text = ""; My.MyProject.Forms.Frmlogin.cmbUserType.Focus(); } else { MessageBox.Show("invalid user name or password", "input error", MessageBoxButtons.OK, MessageBoxIcon.Error); UserName.Text = ""; NewPassword.Text = ""; OldPassword.Text = ""; ConfirmPassword.Text = ""; UserName.Focus(); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void syncServerCtl1_DataReceivedHandler(int ClientID, object Data) { #region PopupMessageSend if (Data is DtPopUpMessageSend) { DtPopUpMessageSend pms = (DtPopUpMessageSend)Data; if (pms.MessageType == enMessageType.InternalMessage && pms.Caption == "_Warning_") { string strQuery = CreateSqlWarning(pms.MessageData.ToString()); //using (StreamWriter sw = new StreamWriter("DataLog.txt", false)) //{ // sw.WriteLine("Events utk Tabel: " + pms.MessageData.ToString() + // ", NoDok: " + pms.Message); // sw.WriteLine(strQuery); //} IList <clsWarningSend> ListWarningSend = BaseFramework.DefaultDp .ListFastLoadEntitiesUsingSqlSelect <clsWarningSend>(null, strQuery, string.Empty, new FieldParam("NoDok", pms.Message)); DtPopUpMessageReceive pmr = new DtPopUpMessageReceive( FindSender(ClientID), pms.Caption, pms.Message, null, enMessageType.Information); foreach (clsWarningSend ws in ListWarningSend) { //using (StreamWriter sw = new StreamWriter("DataLog.txt", true)) //{ // sw.WriteLine(ws.NoDokumen + ":" + ws.NamaPeringatan); // sw.WriteLine("Penanggung Jawab: " + ws.PenanggungJawab); // sw.WriteLine("DictUserClient.Count=" + DictUserClient.Count); // foreach (string nm in DictUserClient.Keys) // sw.WriteLine(nm); //} pmr.Caption = ws.NamaPeringatan; pmr.Message = string.Concat("NoDok: ", ws.NoDokumen, "; Pembuat: ", ws.Pembuat, '\n', ws.Keterangan); pmr.MessageType = ws.JenisWarning ? enMessageType.Warning : enMessageType.Information; List <int> ListClient; if (DictUserClient.TryGetValue( ws.PenanggungJawab.ToLower(), out ListClient)) { foreach (int Id in ListClient) { syncServerCtl1.Send(Id, pmr); } } } } else { DtPopUpMessageReceive pmr = new DtPopUpMessageReceive( FindSender(ClientID), pms.Caption, pms.Message, pms.MessageData, pms.MessageType); foreach (string UserName in pms.UserName) { List <int> ListClient; if (DictUserClient.TryGetValue(UserName.Trim().ToLower(), out ListClient)) { foreach (int Id in ListClient) { syncServerCtl1.Send(Id, pmr); } } } } return; } #endregion #region RaiseEventData if (Data is DtRaiseEventData) { DtRaiseEventData red = (DtRaiseEventData)Data; int Id; if (DictActionListener.TryGetValue(red.EventName, out Id)) { syncServerCtl1.Send(Id, red); } List <int> ListClient; if (DictUserListener.TryGetValue(red.EventName, out ListClient)) { foreach (int ClId in ListClient) { syncServerCtl1.Send(ClId, red); } } return; } #endregion #region RegisterActionListener if (Data is DtRegisterActionListener) { DtRegisterActionListener ral = (DtRegisterActionListener)Data; foreach (string EventName in ral.EventName) { if (!DictActionListener.ContainsKey(EventName)) { DictActionListener.Add(EventName, ClientID); } else { syncServerCtl1.Send(ClientID, new DtPopUpMessageReceive("BxEventServer", "Error Registrasi Action Listener", string.Concat( "Event ", EventName, " sudah dihandle Action Listener lain !"), null, enMessageType.Error)); } } return; } #endregion #region RegisterUserListener if (Data is DtRegisterUserListener) { DtRegisterUserListener rul = (DtRegisterUserListener)Data; foreach (string EventName in rul.EventName) { List <int> ListClient; if (!DictUserListener.TryGetValue(EventName, out ListClient)) { ListClient = new List <int>(); DictUserListener.Add(EventName, ListClient); } else { bool ClientExist = false; foreach (int cl in ListClient) { if (cl == ClientID) { ClientExist = true; break; } } if (ClientExist) { continue; } } ListClient.Add(ClientID); } return; } #endregion #region DtLogin if (Data is DtLogin) { DtLogin lg = (DtLogin)Data; List <int> ListClient; if (!DictUserClient.TryGetValue(lg.UserName.ToLower(), out ListClient)) { ListClient = new List <int>(); DictUserClient.Add(lg.UserName.ToLower(), ListClient); } ListClient.Add(ClientID); syncServerCtl1.Send(ClientID, true); //using (StreamWriter sw = new StreamWriter("DataLog.txt", false)) //{ // sw.WriteLine(lg.UserName + " Logged; ClientId=" + ClientID); //} //string Message = BuildWelcomeMessage(); //if (Message.Length > 0) //{ // DateTime dt = DateTime.Now; // string Caption; // if (dt.Hour <= 10) // Caption = "Selamat Pagi !"; // else if (dt.Hour <= 15) // Caption = "Selamat Siang !"; // else if (dt.Hour <= 19) // Caption = "Selamat Sore !"; // else // Caption = "Selamat Malam !"; // syncServerCtl1.Send(ClientID, new DtPopUpMessageReceive( // string.Empty, Caption, // Message, null, enMessageType.Information)); //} } #endregion }
public IDbConnection GetBasicConnection() { IDbConnection connection = null; string connectionString = string.Empty; if (_properties is SqlConnectionProperties || _properties is OleDBConnectionProperties) { if (_properties is OleDBConnectionProperties) { connectionString += "Provider=" + _properties["Provider"].ToString() + ";"; } connectionString += "Data Source='" + ServerName.Replace("'", "''") + "';"; if (UserInstance) { connectionString += "User Instance=true;"; } if (UseWindowsAuthentication) { connectionString += "Integrated Security=" + _properties["Integrated Security"].ToString() + ";"; } else { connectionString += "User ID='" + UserName.Replace("'", "''") + "';"; connectionString += "Password='******'", "''") + "';"; } if (_properties is SqlConnectionProperties) { connectionString += "Pooling=False;"; } } if (_properties is OdbcConnectionProperties) { connectionString += "DRIVER={SQL Server};"; connectionString += "SERVER={" + ServerName.Replace("}", "}}") + "};"; if (UseWindowsAuthentication) { connectionString += "Trusted_Connection=Yes;"; } else { connectionString += "UID={" + UserName.Replace("}", "}}") + "};"; connectionString += "PWD={" + Password.Replace("}", "}}") + "};"; } } if (_properties is SqlConnectionProperties) { connection = new SqlConnection(connectionString); } if (_properties is OleDBConnectionProperties) { connection = new OleDbConnection(connectionString); } if (_properties is OdbcConnectionProperties) { connection = new OdbcConnection(connectionString); } return(connection); }
public IEnumerable <SubscriptionCspId> GetAssignedSubscriptionIds(CustomerCspId customerId, UserName userName) { // Fake implementation. We would use the actual Microsoft Office365 API in here. return(Enumerable.Empty <SubscriptionCspId>()); }
public void DeleteUser(CustomerCspId customerId, UserName userName) { // Fake implementation. We would use the actual Microsoft Office365 API in here. }
public bool Equals(string operatorUserName) { return(UserName.ToLower() == operatorUserName.ToLower()); }
public bool Equals(Operador operatorToCompare) { return(UserName.ToLower() == operatorToCompare.UserName.ToLower()); }
public void SetNormalizedNames() { NormalizedUserName = UserName.ToUpperInvariant(); NormalizedEmailAddress = EmailAddress.ToUpperInvariant(); }
/// <summary> /// Initializes a new instance of the <see cref="UserConfiguration"/> class /// with the specified user name, password, and databases to initially grant /// access to. /// </summary> /// <param name="name">A <see cref="UserName"/> object describing the name and host of the user to add.</param> /// <param name="password">The password for the new user.</param> /// <param name="databases">A collection of <see cref="DatabaseName"/> objects identifying the databases to initially grant access to for the new user.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is <see langword="null"/>. /// <para>-or-</para> /// <para>If <paramref name="password"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="password"/> is empty. /// <para>-or-</para> /// <para>If <paramref name="databases"/> contains any <see langword="null"/> values.</para> /// </exception> public UserConfiguration(UserName name, string password, params DatabaseName[] databases) { if (name == null) throw new ArgumentNullException("name"); if (password == null) throw new ArgumentNullException("password"); if (string.IsNullOrEmpty(password)) throw new ArgumentException("password cannot be empty"); if (databases != null && databases.Contains(null)) throw new ArgumentException("databases cannot contain any null values", "databases"); _name = name.Name; _password = password; _host = name.Host; if (databases != null && databases.Length > 0) { if (databases.Length == 1) _database = databases[0]; else _databases = Array.ConvertAll(databases, i => new WrappedDatabaseName(i)); } }
public override bool Equals(object obj) { if (this == obj) { return(true); } if (obj == null) { return(false); } if (GetType() != obj.GetType()) { return(false); } var other = (SimpleTrade)obj; if (AccountName == null) { if (other.AccountName != null) { return(false); } } else if (!AccountName.Equals(other.AccountName)) { return(false); } if (BuyRequest != other.BuyRequest) { return(false); } if (OrderType == null) { if (other.OrderType != null) { return(false); } } else if (!OrderType.Equals(other.OrderType)) { return(false); } if (Price != other.Price) { return(false); } if (Quantity != other.Quantity) { return(false); } if (RequestId == null) { if (other.RequestId != null) { return(false); } } else if (!RequestId.Equals(other.RequestId)) { return(false); } if (Ticker == null) { if (other.Ticker != null) { return(false); } } else if (!Ticker.Equals(other.Ticker)) { return(false); } if (UserName == null) { if (other.UserName != null) { return(false); } } else if (!UserName.Equals(other.UserName)) { return(false); } return(true); }
protected void Page_Load(object sender, EventArgs e) { try { FailureText.Text = ""; if (!IsPostBack) { string ReturnURL; if (Request.QueryString["mode"] == null) { string strCurrentUser = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1); //string strCurrentUser =Page.Identity.Name;// Membership.GetUser().UserName; //System.Environment.UserName;//System.Security.Principal.WindowsIdentity.GetCurrent().Name;//.Substring(System.Security.Principal.WindowsIdentity.GetCurrent().Name.LastIndexOf(@"\") + 1); //string ped = Membership.GetUser().GetPassword(); if (strCurrentUser != "IUSR") { Credentials credential = new Credentials(); credential.UserName = strCurrentUser; credential.Password = ""; UserName.Text = strCurrentUser; string error; if (LoginUtilities.AuthenticateUser(credential, out error, out ReturnURL)) { if (Convert.ToString(error) == "") { if (ReturnURL == "") { string UserID = LoginUtilities.GetUserID(UserName.Text); if (UserID != "0") { string tokenresult = SessionClient.CreateSession().ToString(); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "setsession", "setsession('" + tokenresult + "','" + UserName.Text + "','" + UserID + "');", true); //Response.Redirect("Pages/Overview.html?tokenkey=" + tokenresult + "&user="******"Invalid User"; } } else { Response.Redirect(ReturnURL); } } else { if (ReturnURL == "") { ErrorMessage = SetErrorMsg(error); EmployeeLogsBO.StatusID = 5; // Login Failed (Authentication) EmployeeLogsBO.MessageLog = FailureText.Text; InsertOrUpdateEmployeeLogs(); ErrorMessage = SetErrorMsg(error); FailureText.Text = ErrorMessage; } else { ErrorMessage = SetErrorMsg(error); EmployeeLogsBO.MessageLog = ErrorMessage; EmployeeLogsBO.StatusID = 5; // Login Failed (Authentication) InsertOrUpdateEmployeeLogs(); Response.Redirect(ReturnURL); } } } else { FailureText.Text = error; } } } } } catch (Exception ex) { SetErrorMsg(ex.Message); EmployeeLogsBO.StatusID = 4; // Logged Out By System EmployeeLogsBO.MessageLog = ex.Message; InsertOrUpdateEmployeeLogs(); throw; } UserName.Focus(); }
public bool IsReadonly(string user) => !UserName.Equals(user);
//Login Form credentials public void LoginApplication() { int selectEnviornment = Constant.VersionNumber; switch (selectEnviornment) { case 1: // LanguageSelect.SendKeys(Keys.ArrowDown); Thread.Sleep(1500); UserName.EnterText(Constant.newClientUser); UserPassword.EnterText(Constant.loginPassword); Thread.Sleep(500); Browser.Driver.FindElement(By.XPath("//*[@id='loginForm']/div[2]/div[4]/div/p/button")).ClickOn(); // Thread.Sleep(1500); if (Pages.Home_Page.AppointmentBtn_1.Displayed) { //nothing } else if (Pages.Home_Page.AppointmentBtn_2.Displayed) { SideBarArrow.ClickOn(); } break; case 2: // LanguageSelect.SendKeys(Keys.ArrowDown); Thread.Sleep(1500); UserName.EnterText(Constant.testUser); UserPassword.EnterText(Constant.loginPassword); Thread.Sleep(500); Browser.Driver.FindElement(By.XPath("//*[@id='loginForm']/div[2]/div[4]/div/p/button")).ClickOn(); Thread.Sleep(1500); if (Pages.Home_Page.AppointmentBtn_1.Displayed) { //nothing } else if (Pages.Home_Page.AppointmentBtn_2.Displayed) { SideBarArrow.ClickOn(); } break; case 3: Pages.MobileTherapist_Page.MobileLogin(); break; case 4: // LanguageSelect.SendKeys(Keys.ArrowDown); Thread.Sleep(1500); UserName.EnterText(Constant.newClientUser); UserPassword.EnterText(Constant.prodPassword); Thread.Sleep(500); Browser.Driver.FindElement(By.XPath("//*[@id='loginForm']/div[2]/div[4]/div/p/button")).ClickOn(); Thread.Sleep(1500); if (Pages.Home_Page.AppointmentBtn_1.Displayed) { //nothing } else if (Pages.Home_Page.AppointmentBtn_2.Displayed) { SideBarArrow.ClickOn(); } break; } }
public AppUser(UserName name, UserDisplayName displayName, UserRoles roles) { Name = Guard.NotNull(name, nameof(name)); DisplayName = Guard.NotNull(displayName, nameof(displayName)); Roles = Guard.NotNull(roles, nameof(roles)); }
public void AssertRightUserNameSet(string userName) { App.Assert.AreEqual(userName, UserName.GetText()); }
/// <summary> /// Get a database user by ID. /// </summary> /// <param name="service">The database service instance.</param> /// <param name="instanceId">The database instance ID. This is obtained from <see cref="DatabaseInstance.Id">DatabaseInstance.Id</see>.</param> /// <param name="userName">A <see cref="UserName"/> object identifying the database user. This is obtained from <see cref="UserConfiguration.UserName">UserConfiguration.UserName</see>.</param> /// <returns> /// A <see cref="DatabaseUser"/> object describing the user. /// </returns> /// <exception cref="ArgumentNullException">If <paramref name="service"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="instanceId"/> is <see langword="null"/>. /// <para>-or-</para> /// <para>If <paramref name="userName"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="WebException">If the REST request does not return successfully.</exception> /// <seealso href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/GET_listUser__version___accountId__instances__instanceId__users__name__.html">List User (Rackspace Cloud Databases Developer Guide - API v1.0)</seealso> public static DatabaseUser GetUser(this IDatabaseService service, DatabaseInstanceId instanceId, UserName userName) { if (service == null) throw new ArgumentNullException("service"); try { return service.GetUserAsync(instanceId, userName, CancellationToken.None).Result; } catch (AggregateException ex) { ReadOnlyCollection<Exception> innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Count == 1) throw innerExceptions[0]; throw; } }
public void EnterUsernameAndPassword(string username, string passsword) { UserName.SendKeys(username); Password.SendKeys(passsword); }
public void testUserRegistration() { UserName name = new UserName("Bill", "Clinton"); Email email = new Email("*****@*****.**"); User user = new User(email, name, "pwd", null); IUserRepository userRepository = UserRepository.Instance; UserRegistration.UserRegistrationService service = new UserRegistrationService(userRepository); service.CreateUser(user); userRepository.Delete(user); }
//clear the box when mouse clicks private void UserName_PreviewMouseDown(object sender, MouseButtonEventArgs e) { UserName.Clear(); }
/// <summary> /// Set the password for a database user. /// </summary> /// <param name="service">The database service instance.</param> /// <param name="instanceId">The database instance ID. This is obtained from <see cref="DatabaseInstance.Id">DatabaseInstance.Id</see>.</param> /// <param name="userName">A <see cref="UserName"/> object identifying the database user. This is obtained from <see cref="UserConfiguration.UserName">UserConfiguration.UserName</see>.</param> /// <param name="password">The new password for the user.</param> /// <exception cref="ArgumentNullException">If <paramref name="service"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="instanceId"/> is <see langword="null"/>. /// <para>-or-</para> /// <para>If <paramref name="userName"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para>If <paramref name="password"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentException">If <paramref name="password"/> is empty.</exception> /// <exception cref="WebException">If the REST request does not return successfully.</exception> /// <seealso href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/PUT_changePass__version___accountId__instances__instanceId__users_.html">Change User(s) Password (Rackspace Cloud Databases Developer Guide - API v1.0)</seealso> public static void SetUserPassword(this IDatabaseService service, DatabaseInstanceId instanceId, UserName userName, string password) { if (service == null) throw new ArgumentNullException("service"); try { service.SetUserPasswordAsync(instanceId, userName, password, CancellationToken.None).Wait(); } catch (AggregateException ex) { ReadOnlyCollection<Exception> innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Count == 1) throw innerExceptions[0]; throw; } }
protected override bool Execute(CodeActivityContext context) { string Email = ""; if (string.IsNullOrEmpty(UserName)) { Error.Set(context, "Значение свойства 'Пользователь' не может быть пустым"); return(false); } bool FoundUser = false; try { List <UserInfo> UList = ARM_Service.EXPL_Get_All_Users(); foreach (UserInfo u in UList) { if (u.UserName.ToLower(System.Globalization.CultureInfo.InvariantCulture) == UserName.ToLower(System.Globalization.CultureInfo.InvariantCulture)) { FoundUser = true; Email = u.Email; break; } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } if (!string.IsNullOrEmpty(Error.Get(context))) { return(false); } if (!FoundUser) { Error.Set(context, "Не найден пользователь с именем '" + UserName + "'"); return(false); } if (string.IsNullOrEmpty(Email)) { Error.Set(context, "У пользователя '" + UserName + "' не определен адрес электронной почты"); return(false); } Expl_UserNotify_EMailServiceConfiguration Config = null; try { Config = ARM_Service.EXPL_Get_UserNotify_EmailServiceConfigurations().FirstOrDefault(); if (Config == null) { Error.Set(context, "Не найдено ни одной записи в таблице конфигурации почтового сервиса"); return(false); } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } UserNotify_EMailServiceConfigurationItem ConfigurationItem = null; try { ConfigurationItem = UserNotify_EMailServiceConfigurationItem.FromXElement(Config.Data); } catch (Exception ex) { Error.Set(context, "Ошибка разбора Xml : " + ex.Message); if (!HideException.Get(context)) { throw ex; } } //if (UseZipArchive) //{ // MemoryStream compresStream = new MemoryStream(); // ComponentAce.Compression.ZipForge.ZipForge zip = new ComponentAce.Compression.ZipForge.ZipForge(); // zip.FileName = attachName + ".zip"; ; // AttachContent.Position = 0; // zip.OpenArchive(compresStream, true); // zip.AddFromStream(attachName + GetFileExtByReportFormat(), AttachContent); // zip.CloseArchive(); // Attach = new Attachment(AttachContent, zip.FileName); // zip.Dispose(); //} // try { Pop3Helper.ReadAllMails(UserNotifyConfigClass.Pop3_Host, UserNotifyConfigClass.Smtp_User, UserNotifyConfigClass.Smtp_Password); var mailMessage = new System.Net.Mail.MailMessage(); mailMessage.To.Add(Email); if (string.IsNullOrEmpty(Subject.Get(context))) { mailMessage.Subject = ConfigurationItem.Smtp_Subject; } else { mailMessage.Subject = Subject.Get(context); } if (mailMessage.Subject != null) { mailMessage.Subject = mailMessage.Subject.Replace("@PsName", "") .Replace("@data", "") .Replace("@ReportName", ""); } mailMessage.Body = Body.Get(context); mailMessage.From = new System.Net.Mail.MailAddress(ConfigurationItem.Smtp_From); var smtp = new System.Net.Mail.SmtpClient(); smtp.Host = ConfigurationItem.Smtp_Host; smtp.Port = ConfigurationItem.Smtp_Port; MemoryStream a = Attach.Get(context); if (a != null) { string an = AttachName.Get(context); if (string.IsNullOrEmpty(an)) { an = "Вложение"; } Attachment at = new Attachment(a, an); mailMessage.Attachments.Add(at); } smtp.Credentials = new System.Net.NetworkCredential(ConfigurationItem.Smtp_User, ConfigurationItem.Smtp_Password); //smtp.EnableSsl = true; smtp.Send(mailMessage); } catch (Exception ex) { Error.Set(context, "Ошибка отправки письма : " + ex.Message); if (!HideException.Get(context)) { throw ex; } } return(string.IsNullOrEmpty(Error.Get(context))); }
/// <summary> /// Gets a collection of all users within a database instance. /// </summary> /// <remarks> /// <note> /// This is a <see href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/pagination.html">paginated collection</see>. /// </note> /// </remarks> /// <param name="service">The database service instance.</param> /// <param name="instanceId">The database instance ID. This is obtained from <see cref="DatabaseInstance.Id">DatabaseInstance.Id</see>.</param> /// <param name="marker">The <see cref="UserConfiguration.UserName"/> of the last user in the previous page of results. This parameter is used for <see href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/pagination.html">pagination</see>. If the value is <see langword="null"/>, the list starts at the beginning.</param> /// <param name="limit">The maximum number of <see cref="Database"/> objects to return in a single page of results. This parameter is used for <see href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/pagination.html">pagination</see>. If the value is <see langword="null"/>, a provider-specific default value is used.</param> /// <returns> /// A collection of <see cref="DatabaseUser"/> objects describing the database instance users. /// </returns> /// <exception cref="ArgumentNullException">If <paramref name="service"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">If <paramref name="instanceId"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="limit"/> is less than or equal to 0.</exception> /// <exception cref="WebException">If the REST request does not return successfully.</exception> /// <seealso href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/GET_getUsers__version___accountId__instances__instanceId__users_.html">List Users in Database Instance (Rackspace Cloud Databases Developer Guide - API v1.0)</seealso> /// <seealso href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/pagination.html">Pagination (Rackspace Cloud Databases Developer Guide - API v1.0)</seealso> public static ReadOnlyCollectionPage<DatabaseUser> ListDatabaseUsers(this IDatabaseService service, DatabaseInstanceId instanceId, UserName marker, int? limit) { if (service == null) throw new ArgumentNullException("service"); try { return service.ListDatabaseUsersAsync(instanceId, marker, limit, CancellationToken.None).Result; } catch (AggregateException ex) { ReadOnlyCollection<Exception> innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Count == 1) throw innerExceptions[0]; throw; } }
/// <summary> /// Check whether the user and Backup/Restored server URL enter is valid or not /// Input: User given data Username, password and Backup/Restored Server URL /// Output: Check the given compination of username, password and URL are correct or not /// </summary> /// <returns></returns> public bool CheckLoginBack() { //System.Threading.Thread.Sleep(1000); try { System.Diagnostics.Process chkLog = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startchkLog = new System.Diagnostics.ProcessStartInfo(); startchkLog.CreateNoWindow = true; startchkLog.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startchkLog.FileName = "cmd.exe"; startchkLog.Arguments = "/C svn list \"" + BackupURL.Trim() + "\" --username " + UserName.Trim() + " --password " + Password.Trim(); chkLog.StartInfo = startchkLog; chkLog.StartInfo.RedirectStandardOutput = true; chkLog.StartInfo.RedirectStandardError = true; chkLog.StartInfo.UseShellExecute = false; chkLog.Start(); StringBuilder ch = new StringBuilder(); while (!chkLog.HasExited) { ch.Append(chkLog.StandardOutput.ReadToEnd()); ch.Append(chkLog.StandardError.ReadToEnd()); } String login = ch.ToString().Trim(); chkLog.WaitForExit(); chkLog = null; startchkLog = null; if (login.Contains("E175013") || login.Contains("E155007") || login.Contains("E230001") || login.Contains("E175002") || login.Contains("E731004") || login.Contains("E120171") || login.Contains("E020024")) { MessageBox.Show("User credentials or Backup Repository URL is invalid.", "Invalid Input!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } else { return(true); } } catch (Exception loginback) { return(false); } }
//======================================================== // Private events //======================================================== void InputName_FormClosed(object sender, FormClosedEventArgs e) { if (InputName.DialogResult == System.Windows.Forms.DialogResult.OK) { UserName = InputName.Name; TSLbl_Name.Text = string.Format("Name: {0}", UserName); ImageBlockControl_1.Clear(); _index = 0; if (UserExists(UserName) && (MessageBox.Show("User already exists, do you want to load saved images?", string.Empty, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)) { LoadUserImages(); } } else if ((InputName.DialogResult == System.Windows.Forms.DialogResult.Cancel) && (UserName.Equals(string.Empty))) { this.Close(); } UpdateUI(); }
/// <summary> /// Initializes a new instance of the <see cref="UserConfiguration"/> class /// with the specified user name, password, and databases to initially grant /// access to. /// </summary> /// <param name="name">A <see cref="UserName"/> object describing the name and host of the user to add.</param> /// <param name="password">The password for the new user.</param> /// <param name="databases">A collection of <see cref="DatabaseName"/> objects identifying the databases to initially grant access to for the new user.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is <see langword="null"/>. /// <para>-or-</para> /// <para>If <paramref name="password"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="password"/> is empty. /// <para>-or-</para> /// <para>If <paramref name="databases"/> contains any <see langword="null"/> values.</para> /// </exception> public UserConfiguration(UserName name, string password, IEnumerable<DatabaseName> databases) : this(name, password, databases != null ? databases.ToArray() : null) { }
public override int GetHashCode( ) => UserName?.GetHashCode( ) ?? 0;
public String Generate(Int32?IdCustomer, Int32?IdAccount, DateTime?StartDate, DateTime?EndDate, Boolean?GetTransmited) { UserName = UserName.Replace(" ", "").Replace(".", ""); CustomerName = CustomerName.Replace(" ", "").Replace(".", ""); ReportDocument rpt = new ReportDocument(); rpt.Load(this.ReportPath); rpt.FileName = this.ReportPath; CustomerName = CustomerName.Replace(@"\", "") .Replace(@"/", "") .Replace(@":", "") .Replace(@"*", "") .Replace(@"?", "") .Replace("\"", "") .Replace(@"<", "") .Replace(@">", "") .Replace(@"&", "") .Replace(@"=", ""); this.FilePath = this.FilePath + @"\" + UserName + @"\" + CustomerName; this.Url = this.Url + @"/" + UserName + @"/" + CustomerName; if (!Directory.Exists(this.FilePath)) { Directory.CreateDirectory(this.FilePath); } foreach (FileInfo file in new DirectoryInfo(this.FilePath).GetFiles()) { file.Delete(); } String FileNameNoPath = DateTime.Now.ToString("ddMMyyhhmmss"); String FileName = this.FilePath + @"\" + FileNameNoPath; List <Commons.Reports.ExportList> data = new List <Commons.Reports.ExportList>(); DateTime start = (DateTime)StartDate; DateTime end = (DateTime)EndDate; Api.Client apiClient = new Api.Client(System.Configuration.ConfigurationManager.AppSettings["URLAPI"]); IRestResponse WSR = Task.Run(() => apiClient.getJArray("Reporte/ListaExportacion", "IdCustomer=" + IdCustomer + "&IdAccount=" + IdAccount + "&StartDate=" + start.ToString("yyy-MM-dd") + "&EndDate=" + end.ToString("yyy-MM-dd") + "&GetTransmited=" + GetTransmited)).Result; if (WSR.StatusCode == HttpStatusCode.OK) { data = JArray.Parse(WSR.Content).ToObject <List <Commons.Reports.ExportList> >(); } DataSet ds = new DataSet(); ds.Tables.Add(Data.ListToDataTable <Commons.Reports.ExportList>(data)); ds.Tables[0].TableName = "ado"; rpt.SetDataSource(ds); rpt.ParameterFields["Fecha_Inicial"].CurrentValues.Add(Data.CrParameterConvert(StartDate)); rpt.ParameterFields["Fecha_Final"].CurrentValues.Add(Data.CrParameterConvert(EndDate)); rpt.ParameterFields["Usuario"].CurrentValues.Add(Data.CrParameterConvert(UserName)); rpt.ExportToDisk(ExportFormatType.PortableDocFormat, FileName + ".pdf"); //rpt.ExportToDisk(ExportFormatType.Excel, FileName + ".xls"); ExportOptions exOpt = new ExportOptions(); ExcelFormatOptions xlsOpt = new ExcelFormatOptions(); DiskFileDestinationOptions diskOpt = new DiskFileDestinationOptions(); exOpt = rpt.ExportOptions; xlsOpt.ExcelUseConstantColumnWidth = false; xlsOpt.ExcelTabHasColumnHeadings = true; exOpt.ExportFormatType = ExportFormatType.Excel; exOpt.FormatOptions = xlsOpt; exOpt.ExportDestinationType = ExportDestinationType.DiskFile; diskOpt.DiskFileName = FileName + ".xls"; exOpt.DestinationOptions = diskOpt; rpt.ExportOptions.FormatOptions = xlsOpt; rpt.Export(); rpt.Close(); rpt.Dispose(); return(this.Url + @"/" + FileNameNoPath); }
/// <summary> /// Revoke access to a database for a particular user. /// </summary> /// <param name="service">The database service instance.</param> /// <param name="instanceId">The database instance ID. This is obtained from <see cref="DatabaseInstance.Id">DatabaseInstance.Id</see>.</param> /// <param name="databaseName">The database name. This is obtained from <see cref="Database.Name">Database.Name</see>.</param> /// <param name="userName">A <see cref="UserName"/> object identifying the database user. This is obtained from <see cref="UserConfiguration.UserName">UserConfiguration.UserName</see>.</param> /// <exception cref="ArgumentNullException">If <paramref name="service"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="instanceId"/> is <see langword="null"/>. /// <para>-or-</para> /// <para>If <paramref name="databaseName"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para>If <paramref name="userName"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="WebException">If the REST request does not return successfully.</exception> /// <seealso href="http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/DELETE_revokeUserAccess__version___accountId__instances__instanceId__users__name__databases__databaseName__.html">Revoke User Access (Rackspace Cloud Databases Developer Guide - API v1.0)</seealso> public static void RevokeUserAccess(this IDatabaseService service, DatabaseInstanceId instanceId, DatabaseName databaseName, UserName userName) { if (service == null) throw new ArgumentNullException("service"); try { service.RevokeUserAccessAsync(instanceId, databaseName, userName, CancellationToken.None).Wait(); } catch (AggregateException ex) { ReadOnlyCollection<Exception> innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Count == 1) throw innerExceptions[0]; throw; } }
public async Task <IActionResult> upload() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } StringValues UserName; SiteConfig.HttpContextAccessor.HttpContext.Request.Headers.TryGetValue("UName", out UserName); // Used to accumulate all the form url encoded key value pairs in the // request. var formAccumulator = new KeyValueAccumulator(); // string targetFilePath = null; var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); var uploadPath = SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(DirectoryPaths.UserVideosDefaultDirectoryPath, UserName.ToString()); if (!Directory.Exists(uploadPath)) { Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, UserName.ToString())); } /*if (!Directory.Exists(uploadPath)) * { * return Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath, message = "Main Directory Not Exist" }); * } * * if (!Directory.Exists(uploadPath + "default/")) * { * return Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath + "default/", message = "Default Directory Not Exist" }); * }*/ var fileName = ""; try { while (section != null) { ContentDispositionHeaderValue contentDisposition; var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { var output = formAccumulator.GetResults(); var chunk = "0"; foreach (var item in output) { if (item.Key == "name") { fileName = item.Value; } else if (item.Key == "chunk") { chunk = item.Value; } } var Path = uploadPath + "" + fileName; using (var fs = new FileStream(Path, chunk == "0" ? FileMode.Create : FileMode.Append)) { await section.Body.CopyToAsync(fs); fs.Flush(); } } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); var encoding = GetEncoding(section); using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = String.Empty; } formAccumulator.Append(key.ToString(), value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded."); } } } } var result = formAccumulator.GetResults(); // Drains any remaining section body that has not been consumed and // reads the headers for the next section. section = await reader.ReadNextSectionAsync(); } } catch (Exception ex) { return(Ok(new { jsonrpc = "2.0", result = "Error", fname = uploadPath, message = ex.Message })); } string url = VideoUrlConfig.Source_Video_Url(UserName.ToString()) + "/" + fileName; string fileType = System.IO.Path.GetExtension(fileName); string fileIndex = fileName.Replace(fileType, ""); return(Ok(new { jsonrpc = "2.0", result = "OK", fname = fileName, url = url, filetype = fileType, filename = fileName, fileIndex = fileIndex })); }
set => AddItem(UserName, value);
/// <summary> /// Adds a new google user account. /// </summary> /// <param name="accountName">The account name of the new account. this prepends the @domain.com.</param> /// <param name="givenName">The first name of the accountholder.</param> /// <param name="familyName">The last name of the accountholder.</param> /// <param name="password">The chosen password of the new account.</param> /// <param name="orgUnitPath">The organizational location to place the new account.</param> /// <returns>Returns a google user object of the created account.</returns> public static User AddNewUser(string accountName, string givenName, string familyName, string password, string orgUnitPath) { //make sure that ALL parameters are provided. if ((string.IsNullOrEmpty(accountName)) || (string.IsNullOrEmpty(givenName)) || (string.IsNullOrEmpty(familyName)) || (string.IsNullOrEmpty(password)) || (string.IsNullOrEmpty(orgUnitPath))) { throw new Exception("Invalid parameter(s) passed"); } using (var service = (DirectoryService)BuildService("*****@*****.**")) { var newuserbody = new User(); var newusername = new UserName(); newuserbody.PrimaryEmail = $"{accountName}@gsd.wednet.edu"; newusername.GivenName = givenName; newusername.FamilyName = familyName; newuserbody.Name = newusername; newuserbody.Password = password; newuserbody.OrgUnitPath = orgUnitPath; // "/Staff/CO"; var results = service.Users.Insert(newuserbody).Execute(); return results; } }
private void RefreshThisForm() { UserName.Clear(); Password.Clear(); Email.Clear(); Manager.IsChecked = false; VacationDaysBox.Clear(); }