How to open NavigationController's root and pass a value? - c#

I am creating the login part of a Xamarin.iOS application. When logging in I want to pass an User Object to the ProjectsViewController. First a user enters the username and password, then it is validated and lastly, once it is validated I want to go to the main screen which is called ProjectsViewController.
//first get user from Restful service
var response = await apiService.GetUserByToken("http://192.168.1.20:55405",
"/api",
"/Account/FullUser",
token.TokenType,
token.AccessToken);
//get User object
var user = (User)response.Result;
user.Password = password;
if (response.IsSuccess)
{
//loguser is the User object that will be passed to the root
logUser = user;
}
//get storyboard
UIStoryboard board = UIStoryboard.FromName("Main", null);
ProjectsViewController ctrl = (ProjectsViewController)board.InstantiateViewController("projectsViewController");
//current user is the propery that I want to access in the next screen
ctrl.CurrentUser = logUser;
ctrl.ModalTransitionStyle = UIModalTransitionStyle.CoverVertical;
UINavigationController nav = (UINavigationController)board.InstantiateViewController("navController");
nav.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve;
//this sends me to the root but the object is not passed
PresentViewController(nav, true, null);
The code so far validates the user and sends me to the root screen, but the object is not passed. Please help!
thanks in advance!

The thing is that you are creating a new instance of the: ProjectsViewController and setting its CurrentUser, but you are not showing that controller at all.
What you should do is:
UINavigationController nav = (UINavigationController)board.InstantiateViewController("navController");
nav.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve;
//New code
var projectVC = (ProjectsViewController)nav.ViewControllers.FirstOrDefault();
projectVC.CurrentUser = logUser;
PresentViewController(nav, true, null);
Since when you instantiate the: "navController" from storyboard it will also instantiate its ProjectsViewController, which is in its ViewControllers list.

Related

C# Can not add user to Active Directory. It show error There is no such object on the server

I want to use C# add user to Active Directory from my computer.
AD install in server 10.1.1.5
Username and password for login to AD is "Administrator", "Pass12345678".
I create OU name Guest on AD.
This is my code to add user to AD.
private void Btn_ok_Click(object sender, EventArgs e)
{
UserInfo newUserInfo;
newUserInfo.firstName = "TestName" ;
newUserInfo.lastName = "TestLastName";
newUserInfo.displayName = "TestName Lastname";
newUserInfo.username = "TestName.t";
newUserInfo.sAMAccountName = "TestName.t";
DirectoryEntry adUserFolder = new DirectoryEntry("LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com", "Administrator", "Pass12345678");
/******** It show error this line **********/
if(adUserFolder.SchemaEntry.Name == "container")
{
DirectoryEntry newUser = adUserFolder.Children.Add("CN=" + newUserInfo.username, "User");
if (DirectoryEntry.Exists(newUser.Path))
{
//Remove exist user
adUserFolder.Children.Remove(new DirectoryEntry(newUser.Path));
}
newUser.Properties["sAMAccountName"].Value = newUserInfo.sAMAccountName;
newUser.Properties["givenName"].Value = newUserInfo.firstName;
newUser.Properties["sn"].Value = newUserInfo.lastName;
newUser.Properties["displayName"].Value = newUserInfo.displayName;
newUser.CommitChanges();
newUser.Invoke("setpassword", "Test123456");
newUser.CommitChanges();
}
}
when I click OK button it show error.
System.DirectoryServices.DirectoryServicesCOMException: 'There is no
such object on the server. '
at line
if(adUserFolder.SchemaEntry.Name == "container")
How to fix it ?
The DirectoryEntry constructor will never throw an exception. It doesn't actually connect to AD until you start using it. Since that line is the first time you are using adUserFolder, that's when it first connects to AD.
The error means what it says: there is no object with a distinguishedName of CN=Users,OU=Guest,DC=myhome,DC=com.
Are you sure you have that right? It seems like you are looking for a container called Users inside of an OU called Guest. Is that what you are trying to do?
Is Users a container or an OU?
You can confirm the distinguishedName by using AD Users and Computers: navigate to the object you want -> right-click -> 'Properties' -> Attribute Editor tab and look at the distinguishedName attribute.
For creating user objects in active directory I've always used UserPrincipals as opposed to DirectoryEntries:
public void create(string lanid, string new_password, string container)
{
using (UserPrincipal new_user = new UserPrincipal(new PrincipalContext(ContextType.Domain, this.domain_string, container)))
{
new_user.SamAccountName = lanid;
new_user.SetPassword(new_password);
new_user.Enabled = true;
new_user.Save();
}
}
In that example "container" would be something like:
"OU=container,OU=container,OU=container,OU=container,DC=domain,DC=domain,DC=domain";
As for your original error with the DirectoryEntries I'd step through it and see if the object is actually set to anything:
The string:
"LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com"
Doesn't look right to me;
"LDAP://CN=10.1.1.5,CN=Users,OU=Guest,DC=myhome,DC=com"
May work...

Open Contact Card Viewer/Editor from Outlook button

I created a custom ribbon for Microsoft Outlook and I have a button called view profile. I want to be able to bring up the Contact Card Viewer/Editor for the current user. I created a call back and I think I have the general idea of how to get his done but I am having trouble making the connection once I find the current user to getting it to open for that user. Here is the code I have so far for the call back.
public void button2_Click(Office.IRibbonControl control)
{
var appOutlook = new Microsoft.Office.Interop.Outlook.Application();
Outlook.ExchangeUser currentUser = appOutlook.Session.CurrentUser.AddressEntry.GetExchangeUser();
ContactItem contactinfo = currentUser;
contactinfo.ShowBusinessCardEditor();
}
You can use the ContactCard.
Here is C# code converted from the VBA example on this page https://msdn.microsoft.com/en-us/library/office/ff869218.aspx
var session = appOutlook.Session;
var adr = session.CurrentUser.AddressEntry;
var cc = session.CreateContactCard(adr);
cc.Show(MsoContactCardStyle.msoContactCardFull, 100, 100, 100, 100, 100, true);
The easiest way is just calling the .Display(modal: true / false) method on the ContactItem.
ContactItem contact = ...
contact.Display(true); // for modal
Simply call AddressEntry.Details:
Outlook.AddressEntry currentUser = appOutlook.Session.CurrentUser.AddressEntry;
currentUser.Details();

GetCurrentPerson returns null

I'm tryin to add login with Google to my app. I'm following this example. I get the button to work and I can choose from my accounts to log in. But when I log in, I can't access GetCurrentPerson (it returns null).
Code:
void UpdateUI (bool isSignedIn)
{
if (isSignedIn) {
var person = PlusClass.PeopleApi.GetCurrentPerson (mGoogleApiClient);
var name = string.Empty;
if (person != null)
name = person.Name.ToString();
mStatus.Text = "Signed in as " + name;
FindViewById (Resource.Id.sign_in_button).Visibility = ViewStates.Gone;
} else {
mStatus.Text = "Signed out";
FindViewById (Resource.Id.sign_in_button).Enabled = true;
FindViewById (Resource.Id.sign_in_button).Visibility = ViewStates.Visible;
}
}
Full code here
I registered my app to the API using the SHA-1 of the keystore etc. (I didn't use the Client ID though...)
Anyone know what I'm forgetting or doing wrong?
Thanks in advance.

frame issue when creating a method in a class for windows phone 8.1

I am trying to create a method I can reuse on multiple pages in my code for windows phone 8.1 universal Runtime app. So I copied this snippet from one of the pages into my helper class. However, I am struggling with "Frame" class.
I also defined "Frame Frame;" outside of my method initially to get rid of the issue I saw when I copied the code initially.
Here is the method snippet:
public async void CheckAuthState(string pagename, string errormessage)
{
string rememberMeValue = (string)appRoamingSettings.Values["RememberMe"];
if (rememberMeValue == "Yes")
{
//First check if the creds were saved
//If saved, check if the cookie is still valid (not past 2 days)
//If still valid, get the cookie value to pass it in an object to the MC page
//If not valid, using the saved creds, go back and get a new cookie and then pass that to the MC page
//Redirect to the MC page with the cookie in the object
//Get the cookie value...
string myCookieValue = (string)appRoamingSettings.Values["MyCookie"];
//Get the original cookie obtain time....
long CookieObtainedTimeValue = (long)appRoamingSettings.Values["CookieObtainedTime"];
//Convertig date/time back to DateTime object....
origCookieObtainedTime = DateTime.FromBinary(CookieObtainedTimeValue);
currentDateTime = DateTime.Now;
//Check to see if cookie has expired....
cookieTimeElasped = currentDateTime - origCookieObtainedTime;
cookieTimeElapsedMins = cookieTimeElasped.TotalMinutes;
// 2 days = 2880 mins but we give a margin of 1 minute
if (cookieTimeElapsedMins <= 2879)
{
//send the cookie to the MC page along with the cookie as an object
var shdCookie = myCookieValue;
var shdPageName = pagename;
// Create an object by populating the class with the data obtained from logging in and getting he cookie....
myCookiePageName myNeededSHDData = new myCookiePageName(shdCookie, shdPageName);
//Pass the object as a paramter to the Naviage method since we need to pass the parameters to the page being navigated to....
this.Frame.Navigate(typeof(MessageCenter), myNeededSHDData);
}
else
{
//get a new cookie
//send the cookie to the MC page along with the cookie as an object
//Get the values for the userID and password from the settings....
string UserIDValue = (string)appRoamingSettings.Values["UserID"];
string PasswordValue = (string)appRoamingSettings.Values["Password"];
//Update the requestData string before sending.....
requestData = "{" + string.Format(RegisterRequestData, UserIDValue, PasswordValue) + "}";
string registerResults = await SHDAPI(registerUrl, requestData, errormessage);
if (registerResults != null)
{
// Get the cookie and the time and save it to settings
var shdCookie = JsonConvert.DeserializeObject<SHDHelper.SHDObject>(registerResults).RegistrationCookie;
var shdPageName = pagename;
// Create an object by populating the class with the data obtained from logging in and getting he cookie....
myCookiePageName myNeededLoginData = new myCookiePageName(shdCookie, shdPageName);
//Pass the object as a paramter to the Naviage method since we need to pass the parameters to the page being navigated to....
this.Frame.Navigate(typeof(MessageCenter), myNeededLoginData);
// Stop showing the progress bar...
mycontrols.progressbarNoShow(pgbar, pgText);
}
else
{
// Stop showing the progress bar...
mycontrols.progressbarNoShow(pgbar, pgText);
//Show the error message...
ServerNetworkError.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
}
else
{
//If NOT saved, then redirect to the SignIn page along with the page name..
var shdCookie = "currentCookieValue"; //Putting some default value....
var shdPageName = pagename;
// Create an object by populating the class with the data obtained from logging in and getting he cookie....
myCookiePageName myNeededSHDData = new myCookiePageName(shdCookie, shdPageName);
//Instantiate the frames class for using in this function since this.Frame.Navigate can't be used...
//Frame myframe = new Frame();
//Frame Frame = new Frame();
//Pass the object as a paramter to the Naviage method since we need to pass the parameters to the page being navigated to....
this.Frame.Navigate(typeof(SHDSignIn), myNeededSHDData);
}
}
My issue is that every time my code hits the "this.Frame" line it tell me Frame is null. I guess I am trying to see how to reference the same Frame that all my pages in app reference so I don't get this null? Or do I need to something else here to reference the proper frame?
Thanks
The Frame should be a shared instance within your app since it mantains the pages the app has navigated (your app's backstack which determines what page you see if any when pressing back button) so recreating a new one will not work.
Typically this is initialized in your Application class ("App" class in most new project wizard apps) and set to Window.Current.Content. The same underlying instance is then also exposed by any Page instantiated in the app (navigated to by the Frame) as a Frame property in the Page.
So you can either reference it from anywhere via Window.Current.Content and then cast it to Frame or preferably it's something you pass as a parameter into your class (from either Page.Frame, an app wide definition that returns Window.Current.Content casted to Frame, or another class singleton instance that encapsulates Frame and is available app wide) that needs it via the class constructor or the specific class method that needs it.

Object reference not set to an instance of an object when accessing user profile information

I have created a different identity table MyUserInfo for my user profile where I store additional info such as Name, address etc. The idea is that if the user has not entered his / her data then he will be sent to another page where it can be done. The issue is that when I try to verify if the client has entered his name, address etc... i get an an error and I don't understand why:
Additional information: Object reference not set to an instance of an object.
this happens at the line where I try to check if the value of the User Name is null
if (currentUser.MyUserInfo.FirstName == null)
Here is the code:
string user = System.Web.HttpContext.Current.User.Identity.Name;
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
store.AutoSaveChanges = false;
var currentUserId = User.Identity.GetUserId();
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindById(User.Identity.GetUserId());
//check if the user is registered and what his role is
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated && System.Web.HttpContext.Current.User.IsInRole("Customer"))
{
if (currentUser.MyUserInfo.FirstName == null) //offending line
{
Response.Redirect("EnterUserData.aspx");
}
}
If manager.FindByID() returns null, you will get that exception when you try and reference properties in the currentUser object (which of course would also be null). In addition, currentUser.MyUserInfo could be null, causing the same issue.

Categories