public override CommandResult Execute(CommandResult pipeIn) { // Obtain cmdlet parameters string identity = _arguments.Get <StringArgument>("Identity").Value; // Obtain distinguishedname for group CommandResult dn = LDAPHelper.QueryLDAP( string.Format("(&(objectCategory=group)(cn={0}))", identity), new List <string>(1) { "distinguishedName" } ); string distinguishedName = dn[0]["distinguishedName"]; _results = LDAPHelper.QueryLDAP( string.Format("(memberOf={0})", distinguishedName), new List <string>(1) { "distinguishedName", "name", "objectClass", "objectGUID", "SamAccountName", "SID" } ); return(_results); }
internal static LoogonUserResult User_Logon(string userName, string password, string domain) { LoogonUserResult loogonUserResult = new LoogonUserResult(); loogonUserResult.Autenticated = false; try { LDAPHelper _ADHelper = new LDAPHelper(domain, ActiveDirectoryService.CnnStringName, true, false); TechnicalException logError = null; loogonUserResult.LogResult = _ADHelper.User_Logon(userName, password, out logError).ToString(); if (logError != null) { loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(logError); } else { loogonUserResult.ErrorMessage = string.Empty; loogonUserResult.Autenticated = true; } } catch (Exception ex) { loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex); } return(loogonUserResult); }
public async Task <ActionResult> Create([Bind(Include = "userName,hashPassword,permissionGroup")] UserAccount useraccount) { if (ModelState.IsValid) { //check that the user has sufficient priveliges if (useraccount.permissionGroup == "Boss" || useraccount.permissionGroup == "Admins") { if (!LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name)) { RedirectToAction("Error", "ErrorPages"); } } else //auto generate a password for the customers { useraccount.hashPassword = System.Web.Security.Membership.GeneratePassword(9, 2); } //hash the password with the apps secret key useraccount.hashPassword = EncryptionHelper.Encrypt(useraccount.hashPassword); db.UserAccounts.Add(useraccount); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(useraccount)); }
private void Signin_Load(object sender, System.EventArgs e) { if (!bool.Parse(portalSettings.CustomSettings["SITESETTINGS_ALLOW_NEW_REGISTRATION"].ToString())) { RegisterBtn.Visible = false; } if (bool.Parse(Settings["SIGNIN_AUTOMATICALLYHIDE"].ToString()) && Request.IsAuthenticated) { this.Visible = false; } else if (!bool.Parse(Settings["SIGNIN_ALLOW_AUTOCOMPLETE"].ToString())) { //New setting on Signin fo disable IE autocomplete by Mike Stone password.Attributes.Add("autocomplete", "off"); } if (!IsPostBack) { GroupList.Items.Add(new ListItem("Default", "Default")); string contexts = System.Configuration.ConfigurationSettings.AppSettings["LDAPContexts"]; if (contexts != null) { string[] names = contexts.Split(";".ToCharArray()); for (int i = 0; i < names.Length; i++) { GroupList.Items.Add(new ListItem(LDAPHelper.GetContext(names[i]), names[i])); } } LDAPCheckBox.Checked = "True" == Settings["LDAP"].ToString(); } }
public async Task <ActionResult> About() { var apiBaseUrl = Environment.GetEnvironmentVariable("API_URL") ?? "http://localhost:60201/"; var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }); client.BaseAddress = new Uri(apiBaseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); string json = await Task.Run(() => JsonConvert.SerializeObject(new UPNInfo() { UPN = LDAPHelper.GetUPN(User.Identity.Name) })); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync("api/values", content); AdInfo adinfo = new AdInfo(); if (response.IsSuccessStatusCode) { string data = await response.Content.ReadAsStringAsync(); JavaScriptSerializer JSserializer = new JavaScriptSerializer(); adinfo = JSserializer.Deserialize <AdInfo>(data); } return(View(adinfo)); }
/// <summary> /// /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="domain"></param> /// <returns></returns> internal static LoogonUserResult User_Logon2(string userName, string password, string domain) { LoogonUserResult loogonUserResult = new LoogonUserResult(); loogonUserResult.Autenticated = false; try { LDAPHelper _ADWrapper = new LDAPHelper(domain, Common.CnnStringNameAD); TechnicalException logError = null; loogonUserResult.LogResult = _ADWrapper.User_Logon(userName, password, out logError).ToString(); if (logError != null) { loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(logError); } else { loogonUserResult.ErrorMessage = string.Empty; loogonUserResult.Autenticated = true; } return(loogonUserResult); } catch (Exception ex) { throw ex; } }
// GET: /Invoices/ public async Task <ActionResult> Index(string account, string time) { //only show your own invoices past 3 months, 90 days DateTime cutoffDate = DateTime.Now.Subtract(new TimeSpan(90, 0, 0, 0)); var invoices = db.Invoices.Where(i => i.customerID.ToLower() == User.Identity.Name.ToLower()).Include(i => i.PDFFile); if (string.IsNullOrWhiteSpace(time)) { //then use cutoff date invoices = invoices.Where(i => i.date > cutoffDate); } else { ViewBag.time = "all"; } if (LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name) || LDAPHelper.UserIsMemberOfGroupOC("Admins", User.Identity.Name)) { if (string.IsNullOrWhiteSpace(account)) { invoices = db.Invoices.Include(i => i.PDFFile); } else { invoices = db.Invoices.Where(i => i.customerID.ToLower() == account.ToLower()).Include(i => i.PDFFile); } } return(View(await invoices.ToListAsync())); }
public static object Update(SessionInfo sessioninfo, MA_USER record, int intCheckAD) { try { UserBusiness _userBusiness = new UserBusiness(); if (intCheckAD == 1) { bool validUser = LDAPHelper.UserExists(record.USERCODE); if (!validUser) { return new { Result = "ERROR", Message = "User is not exist." } } ; } record.DEPARTMENT = record.DEPARTMENT.ToUpper(); record.NAME = record.NAME.ToUpper(); record.USER_OPICS = record.USER_OPICS.ToUpper(); record.USERCODE = record.USERCODE.ToUpper(); record.ISACTIVE = record.ISACTIVE == null || !record.ISACTIVE.Value ? false : true; record.ISLOCKED = record.ISLOCKED == null || !record.ISACTIVE.Value ? false : true; record.LOG.MODIFYBYUSERID = sessioninfo.CurrentUserId; record.LOG.MODIFYDATE = DateTime.Now; var addedStudent = _userBusiness.UpdateUser(sessioninfo, record); return(new { Result = "OK" }); } catch (Exception ex) { return(new { Result = "ERROR", Message = ex.Message }); } }
// GET: /File/ public async Task <ActionResult> PDFFile(int id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Invoices invoices = await db.Invoices.FindAsync(id); if (invoices == null || invoices.PDFFileID == null) { return(HttpNotFound()); } if (LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name) || LDAPHelper.UserIsMemberOfGroupOC("Admins", User.Identity.Name) || invoices.customerID.ToLower() == User.Identity.Name.ToLower()) { var fileToRetrieve = db.PDFFiles.Find(invoices.PDFFileID); if (fileToRetrieve == null) { return(HttpNotFound()); } return(File(fileToRetrieve.Content, "application/pdf", "Computrex_Invoice" + invoices.name + ".pdf")); } else { return(HttpNotFound()); } }
/// <summary> /// authentica contra LDAP /// </summary> /// <param name="userName">Nombre de usuario de dominio</param> /// <param name="password">password</param> /// <param name="domain">Nombre de dominio</param> /// <returns></returns> internal static LoogonUserResult User_Logon(string userName, string password, string domain) { LoogonUserResult loogonUserResult = new LoogonUserResult(); loogonUserResult.Autenticated = false; var cnn = apiAppSettings.get_cnnString_byName(Common.CnnStringNameAD); if (cnn == null) { var te = new TechnicalException("No esta coonfigurado elrepositorio de datos de dominios. Cadena de conexion no se encuentra"); te.ErrorId = "9000"; } LDAPHelper _ADWrapper = new LDAPHelper(domain, cnn.cnnString, true, false); TechnicalException logError = null; loogonUserResult.LogResult = _ADWrapper.User_Logon(userName, password, out logError).ToString(); if (logError != null) { loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(logError); } else { loogonUserResult.ErrorMessage = string.Empty; loogonUserResult.Autenticated = true; } return(loogonUserResult); }
public override CommandResult Execute(CommandResult pipeIn) { // Obtain cmdlet parameters string identity = _arguments.Get <StringArgument>("Identity").Value; string ldapFilter = _arguments.Get <StringArgument>("LDAPFilter").Value; string filter = _arguments.Get <StringArgument>("Filter").Value; string properties = _arguments.Get <StringArgument>("Properties").Value; // Determine filters bool filledIdentity = !string.IsNullOrEmpty(identity); bool filledLdapFilter = !string.IsNullOrEmpty(ldapFilter); bool filledFilter = !string.IsNullOrEmpty(filter); // Input checks if (filledIdentity && filledLdapFilter) { throw new InvalidOperationException("Specify either Identity or LDAPFilter, not both"); } if (!filledIdentity && !filledLdapFilter && !filledFilter) { throw new InvalidOperationException("Specify either Identity, Filter or LDAPFilter"); } // Build filter string filterBase = "(&(objectCategory=group){0})"; string queryFilter = string.Empty; // -Identity Administrator if (filledIdentity) { queryFilter = string.Format(filterBase, string.Format("(sAMAccountName={0})", identity)); } // -LDAPFilter "(adminCount=1)" else if (filledLdapFilter) { queryFilter = string.Format(filterBase, ldapFilter); } // -Filter * else if (filledFilter) { // TODO: allow more types of filters if (filter != "*") { throw new InvalidOperationException("Currently only * filter is supported"); } queryFilter = string.Format(filterBase, string.Empty); } // Query _results = LDAPHelper.QueryLDAP(queryFilter, new List <string>(properties.Split(','))); return(_results); }
//public static SessionInfo LogOn(string username) //{ // SessionInfo _session = new SessionInfo(); // if (username.ToUpper().Equals("ADMINISTRATOR")) // { // UserBusiness _userBusiness = new UserBusiness(); // _session = _userBusiness.LogOn(username); // } // return _session; //} public static SessionInfo LogOn(string username, string password, string userIP, int intADLogin) { UserBusiness _userBusiness = new UserBusiness(); SessionInfo _session = null; //string currentpassword = DecodeJSPassEncoding(password); string currentpassword = password.Trim(); try { if (username.ToUpper().Equals("ADMINISTRATOR")) { string systempassword = DecodeJSPassEncoding((string)ConfigurationSettings.AppSettings[AppSettingName.SYSTEM_KEY]); if (systempassword.Equals(currentpassword)) { _session = _userBusiness.LogOn(username, userIP); } else { throw new Exception("That password is incorrect. Be sure you're using the password for your Deal Maker account."); } _session.IsSystemUser = true; } else { //log on via AD user bool validUser = false; if (intADLogin == 1) { validUser = LDAPHelper.ValidateUser(username, currentpassword); } else { validUser = _userBusiness.GetAll().FirstOrDefault(p => p.USERCODE.ToLower().Equals(username.ToLower())) != null ? true : false; } if (validUser) { _session = _userBusiness.LogOn(username, userIP); _session.IsSystemUser = false; } else { throw new Exception("That username is not authorized. Be sure you're using the username and password for your Windows account."); } } } catch (Exception ex) { throw new UIPException(ex); } return(_session); }
bool SetAD(Boolean pSecure) { if (_DomainUrlInfo == null) { lblCheckResult.Text = "Nombre de dominio incorrecto"; return(false); } //_ADHelper = new ADHelper(wDomainUrlInfo.LDAPPath, wDomainUrlInfo.Usr, wDomainUrlInfo.Pwd); _ADHelper = new LDAPHelper(_DomainUrlInfo); //_ADHelper = new LDAPHelper(wDomainUrlInfo.DomainName, "testActiveDirectory", pSecure); return(true); }
/// <summary> /// Check if user present in AD /// </summary> /// <param name="userID"></param> /// <returns></returns> public static HeadCount CheckUserInAD(HeadCount headcount) { if (String.IsNullOrEmpty(headcount.UserID)) { headcount.Active = null; } else { var exists = LDAPHelper.SearchAUserByLogin(headcount.UserID); headcount.Active = exists != null ? true : false; } return(headcount); }
public async Task <ActionResult> DeleteConfirmed(string id) { UserAccount useraccount = await db.UserAccounts.FindAsync(id); if (useraccount.permissionGroup == "Boss" && !LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name)) { return(HttpNotFound()); } db.UserAccounts.Remove(useraccount); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public EmployeeData LoginDomain([FromBody] JObject LogInData) { EmployeeData authenRs = null; try { LDAPHelper authen = new LDAPHelper(WebConfigurationManager.AppSettings["ADDomainName"] , WebConfigurationManager.AppSettings["ADIPAddress"] , Convert.ToInt32(WebConfigurationManager.AppSettings["ADPort"])); authenRs = authen.Authenticate(LogInData["username"].ToString(), LogInData["password"].ToString()); } catch (Exception e) { if (authenRs != null) { authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } else { authenRs = new EmployeeData(); authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } } if (authenRs.Result == true) { UserLogSvr svr = ServiceContainer.GetService <UserLogSvr>(); try { svr.EmployeeActivityLog(authenRs.EmployeeID, "LOGIN"); var header = ServiceContainer.GetService <PesWeb.Service.Modules.EvaManage>(); tblEmployee emp = header.getEmployees().Where(a => a.EmployeeNo.Trim() == authenRs.EmployeeID.Trim()).FirstOrDefault(); authenRs.positionNo = (emp != null)?(int)emp.PositionNo:0; } catch (Exception e) { authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } } return(authenRs); }
internal static Fwk.CentralizedSecurity.Contracts.LoogonUserResult User_Logon2(string userName, string password, string domain) { Fwk.CentralizedSecurity.Contracts.LoogonUserResult loogonUserResult = new LoogonUserResult(); try { LDAPHelper _ADHelper = new LDAPHelper(domain, ActiveDirectoryService.CnnStringName, true, false); var x = _ADHelper.User_Logon_IsAuthenticated(userName, password); loogonUserResult.Autenticated = x; } catch (Exception ex) { loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex); } return(loogonUserResult); }
public EmployeeData LoginDomain([FromBody] JObject LogInData) { EmployeeData authenRs = null; try { LDAPHelper authen = new LDAPHelper(WebConfigurationManager.AppSettings["ADDomainName"] , WebConfigurationManager.AppSettings["ADIPAddress"] , Convert.ToInt32(WebConfigurationManager.AppSettings["ADPort"])); authenRs = authen.Authenticate(LogInData["username"].ToString(), LogInData["password"].ToString()); } catch (Exception e) { if (authenRs != null) { authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } else { authenRs = new EmployeeData(); authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } } if (authenRs.Result == true) { UserLogSvr svr = ServiceContainer.GetService <UserLogSvr>(); try { svr.EmployeeActivityLog(authenRs.EmployeeID, "LOGIN"); } catch (Exception e) { authenRs.Result = false; authenRs.Message = e.Message; return(authenRs); } } return(authenRs); }
public async Task <ActionResult> Delete(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserAccount useraccount = await db.UserAccounts.FindAsync(id); if (useraccount == null) { return(HttpNotFound()); } if (useraccount.permissionGroup == "Boss" && !LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name)) { return(HttpNotFound()); } return(View(useraccount)); }
private static int DiscoverADGroups(string group, SecurityGroupMapping map) { var users = LDAPHelper.SearchUsersByGroup(group); var count = 0; foreach (LDAPUser user in users) { if (CheckOffice(user.Office, map.Office)) { var prefix = ""; prefix = "i:0e.t|adfs|"; try { var employee = Employee.GetBy("AccountName", prefix + user.UPN); if (!employee.Division.Contains(map.Abbreviation)) { if (employee.Division == "N/A") { employee.Division = ""; } if (employee.Division != "") { employee.Division += ", "; } employee.Division += map.Abbreviation; employee.Save(); count++; } } catch (Exception ex) { LDAPHelper.WriteException(ex, "SecurityGroupMapping.DiscoverADGroups : " + prefix + user.UPN); } } } return(count); }
public Object Post(UPNInfo upn) { var windowsIdentity = User.Identity as WindowsIdentity; if (windowsIdentity is null) { return("not using windows auth."); } var testData = new List <Result>(); Ldap ldapInfo = new Ldap(); try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); ldapInfo.ConnectedServer = ctx.ConnectedServer; ldapInfo.Container = ctx.Container; var identity = UserPrincipal.FindByIdentity(ctx, windowsIdentity.Name); ldapInfo.UserPrincipalName = identity?.UserPrincipalName; var connectionString = Environment.GetEnvironmentVariable("CONNECTION") ?? "server=sqlserver.win.local;DataBase=testdb;integrated security=SSPI"; testData = SQLHelper.GetTestData(connectionString, LDAPHelper.GetUPN(upn.UPN)); } catch (Exception ex) { ldapInfo.ErrorMessage = ex.ToString(); } return(new AdInfo() { MachineName = Environment.MachineName, AuthenticationType = User.Identity.AuthenticationType.ToString(), ImpersonationLevel = windowsIdentity.ImpersonationLevel.ToString(), TestData = testData, Claims = windowsIdentity.Claims.DistinctBy(claim => claim.Type).ToDictionary(claim => claim.Type, claim => claim.Value), Groups = windowsIdentity.Groups.Select(x => new AdGroup() { Name = AdGroup.ToName(x), Value = x.Value }).ToList(), LDAP = ldapInfo, }); }
public ActionResult SyncLDAP() { var user = Session["User"] as DB.user; if (user == null) { return(RedirectToAction("Index", "Home")); } var users = LDAPHelper.GetADUsers(); foreach (var u in users) { var dbUser = new user { FullName = u.DisplayName, Username = u.UserName, Email = u.Email }; Operations.AddUser(dbUser); } return(RedirectToAction("Index")); }
private void LoginBtn_Click(Object sender, System.EventArgs e) { // modified by Jonathan Fong // www.gt.com.au string id = null; if (LDAPCheckBox.Checked && GroupList.SelectedValue != "Default") { string dn = "cn=" + email.Text + "," + GroupList.SelectedValue; LDAPHelper.SignOn(dn, password.Text, RememberCheckBox.Checked, null); } else { id = PortalSecurity.SignOn(email.Text, password.Text, RememberCheckBox.Checked); } if (id == null) { Message.Text = "Login failed"; Message.TextKey = "LOGIN_FAILED"; } }
private void Page_Load(object sender, System.EventArgs e) { try { RainbowPrincipal user = HttpContext.Current.User as RainbowPrincipal; if (user != null) { Hashtable userProfile = LDAPHelper.GetUserProfile(user.Identity.ID); this.UseridField.Text = ((string[])userProfile["DN"])[0]; this.NameField.Text = ((string[])userProfile["FULLNAME"])[0]; this.EmailField.Text = ((string[])userProfile["MAIL"])[0]; this.DepartmentField.Text = ((string[])userProfile["OU"])[0]; this.MembershipListBox.DataSource = userProfile["GROUPMEMBERSHIP"]; this.MembershipListBox.DataBind(); } } catch (Exception ex) { ErrorMessage.Visible = true; Rainbow.Configuration.ErrorHandler.HandleException("Error retrieving user", ex); } }
public static MA_USER ValidateUser(SessionInfo sessioninfo, string strUsername, string strPassword, int intADLogin) { UserBusiness _userBusiness = new UserBusiness(); try { bool validUser = true; if (intADLogin == 1) { validUser = LDAPHelper.ValidateUser(strUsername, strPassword); } if (validUser) { MA_USER user = _userBusiness.GetByUserCode(sessioninfo, strUsername); return(user); } else { return(null); } } catch (Exception ex) { throw new UIPException(ex); } //if (strUsername == "Admin") //{ // return new { Result = "OK", Message = "" }; //} //else //{ // return new { Result = "ERROR", Message = "User has no right to approve limit." }; //} }
public async Task <ActionResult> Edit([Bind(Include = "userName,hashPassword,permissionGroup")] UserAccount useraccount) { if (ModelState.IsValid) { UserAccount acct = await db.UserAccounts.FindAsync(useraccount.userName); if (acct == null) { return(HttpNotFound()); } if (acct.permissionGroup == "Boss" && !LDAPHelper.UserIsMemberOfGroupOC("Boss", User.Identity.Name)) { return(HttpNotFound()); } //hash the password with the apps secret key useraccount.hashPassword = EncryptionHelper.Encrypt(useraccount.hashPassword); db.Entry(useraccount).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(useraccount)); }
static void AttemptImpersonateUser(string user, Action action) { //still need to get run time version to work. string upn = LDAPHelper.GetUPN(user); if (string.IsNullOrEmpty(upn)) { //unable to find the user. Console.WriteLine(String.Format("Unable to find user: {0} in domain.", user)); action(); Console.WriteLine("Ran action without impersonation"); } else { using (System.Security.Principal.WindowsImpersonationContext impersonationContext = new WindowsIdentity(upn).Impersonate()) { Console.WriteLine("Impersonating user: "******"Ran action with impersonation"); } } }
public void SendMessage(string qname, string directFormatProtocol, string messageBody, string label) { CreateQueue(qname); try { string upn = LDAPHelper.GetUPN(User); string directFormatName = GetDirectFormatName(qname, directFormatProtocol); if (string.IsNullOrEmpty(upn)) { //unable to find the user. Console.WriteLine("Unable to find User in domain, trying out a regular path instead"); Message msg = new Message(); int len = messageBody.Length; if (len > Constants.MAX_MESSAGE_SIZE) { //do something here? Console.WriteLine("Message contents larger than expected, possible truncation."); } msg.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(messageBody)); msg.Label = label; msg.UseDeadLetterQueue = true; //Log metadata with both qname LogQueueMetadata(qname); //Log Metadata with direct format name (permissions issue?) // LogQueueMetadata(directFormatName); //send with direct format name Console.WriteLine(String.Format("Send with Direct Format Queue Name: {0}", directFormatName)); MessageQueue mq = GetMessageQueue(directFormatName, accessMode: QueueAccessMode.Send); mq.Send(msg, MessageQueueTransactionType.Single); mq.Close(); mq.Dispose(); } else { using (System.Security.Principal.WindowsImpersonationContext impersonationContext = new WindowsIdentity(upn).Impersonate()) { Message msg = new Message(); int len = messageBody.Length; if (len > Constants.MAX_MESSAGE_SIZE) { //do something here? Console.WriteLine("Message contents larger than expected, possible truncation."); } msg.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(messageBody)); msg.Label = label; msg.UseDeadLetterQueue = true; //Log metadata with both qname LogQueueMetadata(qname); //Log Metadata with direct format name (permissions issue?) // LogQueueMetadata(directFormatName); //send with direct format name Console.WriteLine(String.Format("Send with Direct Format Queue Name: {0}", directFormatName)); MessageQueue mq = GetMessageQueue(directFormatName, accessMode: QueueAccessMode.Send); mq.Send(msg, MessageQueueTransactionType.Single); mq.Close(); mq.Dispose(); } } } catch (Exception ex) { Console.WriteLine("issue with sending message."); if (Trace >= TraceLevel.Info) { Console.WriteLine(ex.ToString()); } } }
void CreateQueue(string qname, bool transactional = true) { Console.WriteLine("Testing with Queue Name: " + qname); try { string upn = LDAPHelper.GetUPN(User); if (string.IsNullOrEmpty(upn)) { //unable to find the user. Console.WriteLine("Unable to find user in domain, trying out a regular path instead"); StringBuilder sb = new StringBuilder(); sb.AppendLine("Computer Name: " + Environment.MachineName); sb.AppendLine("Logged in User: "******"Registry Key Value: " + RegistryHelper.GetRegistryValue(Constants.REGISTRY_HKLM, Constants.REGISTRY_MSMQ_PARAMETERS, Constants.REGISTRY_MSMQ_WORKGROUP)); Console.WriteLine(sb.ToString()); Console.WriteLine("Checking for queue existance " + qname); if (!MessageQueue.Exists(qname)) { Console.WriteLine("Queue doesn't exist so we will create one."); MessageQueue mq = MessageQueue.Create(qname, transactional); //This should only be set for containers. Otherwise we can use the Current User WindowsIdentity.GetCurrent().Name mq.SetPermissions(Constants.EVERYONE, MessageQueueAccessRights.FullControl); Console.WriteLine("Setting Permissions"); mq.SetPermissions(Constants.AUTHENTICATED_USERS, MessageQueueAccessRights.FullControl); Console.WriteLine("Finished Setting Permissions"); } Console.WriteLine("Queue should exist! " + qname); Console.WriteLine("Ran action without impersonation"); } else { using (System.Security.Principal.WindowsImpersonationContext impersonationContext = new WindowsIdentity(upn).Impersonate()) { Console.WriteLine("Impersonating user: "******"Computer Name: " + Environment.MachineName); sb.AppendLine("Logged in User: "******"Registry Key Value: " + RegistryHelper.GetRegistryValue(Constants.REGISTRY_HKLM, Constants.REGISTRY_MSMQ_PARAMETERS, Constants.REGISTRY_MSMQ_WORKGROUP)); Console.WriteLine(sb.ToString()); Console.WriteLine("Checking for queue existance " + qname); if (!MessageQueue.Exists(qname)) { Console.WriteLine("Queue doesn't exist so we will create one."); MessageQueue mq = MessageQueue.Create(qname, transactional); //This should only be set for containers. Otherwise we can use the Current User WindowsIdentity.GetCurrent().Name mq.SetPermissions(Constants.EVERYONE, MessageQueueAccessRights.FullControl); Console.WriteLine("Setting Permissions"); mq.SetPermissions(Constants.AUTHENTICATED_USERS, MessageQueueAccessRights.FullControl); Console.WriteLine("Finished Setting Permissions"); } Console.WriteLine("Queue should exist! " + qname); Console.WriteLine("Ran action with impersonation"); } } } catch (Exception ex) { Console.WriteLine("issue with creating the queue."); if (Trace >= TraceLevel.Info) { Console.WriteLine(ex.ToString()); } } }
public Message ReceiveMessage(string qname, string directFormatProtocol) { Message msg = null; try { string upn = LDAPHelper.GetUPN(User); string directFormatName = GetDirectFormatName(qname, directFormatProtocol); if (string.IsNullOrEmpty(upn)) { //unable to find the user. Console.WriteLine("Unable to find user in domain, trying out a regular path instead"); MessageQueue mq = GetMessageQueue(qname, accessMode: QueueAccessMode.PeekAndAdmin); Console.WriteLine(GetQueueMetadata(qname)); mq.Close(); mq.Dispose(); //Release usage of queue //Does this need to use direct queue name? Console.WriteLine(String.Format("Receive with Direct Format Queue Name: {0}", directFormatName)); mq = GetMessageQueue(directFormatName, accessMode: QueueAccessMode.Receive); msg = mq.Receive(); long len = msg.BodyStream.Length; byte[] msgBodyBytes = new byte[(Constants.MAX_MESSAGE_SIZE < (int)len) ? Constants.MAX_MESSAGE_SIZE : (int)len]; if (len > Constants.MAX_MESSAGE_SIZE) { //do something here? Console.WriteLine("Message contents larger than expected, possible truncation."); } msg.BodyStream.Read(msgBodyBytes, 0, (int)len); //repack the message contents into the body of the message. msg.Body = Encoding.ASCII.GetString(msgBodyBytes); mq.Close(); mq.Dispose(); } else { using (System.Security.Principal.WindowsImpersonationContext impersonationContext = new WindowsIdentity(upn).Impersonate()) { MessageQueue mq = GetMessageQueue(qname, accessMode: QueueAccessMode.PeekAndAdmin); Console.WriteLine(GetQueueMetadata(qname)); mq.Close(); mq.Dispose(); //Does this need to use direct queue name? Console.WriteLine(String.Format("Receive with Direct Format Queue Name: {0}", directFormatName)); mq = GetMessageQueue(directFormatName); msg = mq.Receive(); long len = msg.BodyStream.Length; byte[] msgBodyBytes = new byte[(Constants.MAX_MESSAGE_SIZE < (int)len) ? Constants.MAX_MESSAGE_SIZE : (int)len]; if (len > Constants.MAX_MESSAGE_SIZE) { //do something here? Console.WriteLine("Message contents larger than expected, possible truncation."); } msg.BodyStream.Read(msgBodyBytes, 0, (int)len); //repack the message contents into the body of the message. msg.Body = Encoding.ASCII.GetString(msgBodyBytes); mq.Close(); mq.Dispose(); } } } catch (Exception ex) { Console.WriteLine("issue with receiving message."); if (Trace >= TraceLevel.Info) { Console.WriteLine(ex.ToString()); } } return(msg); }