string uname = txt1.Text;
string pwd = txt2.Text;
NavigationService.Navigate(new Uri("/newPage.xaml?name="+uname+"&pwd="+pwd,UriKind.Relative));
I have two text boxes: username and password
now I am entering values on those textboxes and those values are for example:
username: abcd
password:1234
now I want those values in multiple pages, so how it will possible?
I am using query string but every time I have to define values with navigation URI,
So please suggest me any other way like SESSION in ASP.NET.
public class Users
{
public string Username { get; set; }
public string Password { get; set; }
}
Users objUser = new Users();
objUser.Username = "Viraj";
objUser.Password = "12345";
//save data in phone state use in multiple pages.
PhoneApplicationService.Current.State["UserInfo"] = objUser;
//To retrieve data on another screen from phone state
if(PhoneApplicationService.Current.State["UserInfo"]!=null)
{
Users objUser = PhoneApplicationService.Current.State["UserInfo"] as Users;
}
//To update data in phone state
if(PhoneApplicationService.Current.State["UserInfo"]!=null)
{
Users objUser = PhoneApplicationService.Current.State["UserInfo"] as Users;
objUser.Username = "aman";
PhoneApplicationService.Current.State["UserInfo"] = objUser;
}
//at last remember that always remove data from phone state on app exist
private void Application_Closing(object sender, ClosingEventArgs e)
{
if(PhoneApplicationService.Current.State["UserInfo"]!=null)
{
PhoneApplicationService.Current.State.Remove("UserInfo");
}
}
Once the login is success, you can copy the Username and Password to static variables which have same namespace as of the app so that it will be accessible in every pages.
public static string Username;
public static string Password;
Hope this will solve your issue
Create a static public variable you set. Example:
public static class AppState
{
public static string Username { get; set; }
public static string Password { get; set; }
}
Then you can simple set the values any where:
AppState.Username = "Viraj";
IsolatedStorageSettings.ApplicationSettings["uname"] = uname;
then call it in other page like:
string name = IsolatedStorageSettings.ApplicationSettings["uname"] as string;
this also works greater.
Related
At my current project(blazor server side) I want to start using the session storage for user data like roles and names.
I've tried Blazored.SessionStorage and AspNetCore.Components.Server.ProtectedBrowserStorage.
The problem I'm facing is, that I just can't get the value(it's always null) and I don't know why.
Code I'm using:
public void GetUserInfo()
{
var x = sessionStorage.GetAsync<string>("Name");
var y = sessionStorage.GetAsync<string>("Email");
string Name = x.ToString();
string Email = y.ToString();
}
And
[Inject] public ProtectedSessionStorage sessionStorage { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
string Name = Helper.Name;
string Email = Helper.Email;
await sessionStorage.SetAsync("Name", Name);
await sessionStorage.SetAsync("Email", Email);
var x = sessionStorage.GetAsync<string>("Name");
var y = sessionStorage.GetAsync<string>("Email");
Name = x.Result.Value;
Email = y.Result.Value;
}
Thanks to everyone in advance and have a great day! :)
DO NOT USE THIS SOLUTION AS IS. WHEN I GET THE TIME I WILL UPDATE IT TO A WORKING SOLUTION
I suggest adding this as an injected object using Dependency Injection.
Create a class to hold this information and add is as a Scoped service.
Class:
public class UserInfo : IUserInfo //Create an interface
{
public static Name { get; set; }
public static Email { get; set; }
}
Injection (Program.cs on .NET 6):
public static async Task Main(string[] args)
{
//For WSAM
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//For Server
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddScoped<IUserInfo, UserInfo>(); //Scoped Service injection
}
Add data to injected service:
[Inject]
public IUserInfo UserInfo { get; set; }
protected override void OnInitialized() //Use whatever Life Cycle methods works for your implementation
{
UserInfo.Name = Helper.Name;
UserInfo.Email = Helper.Email;
}
Usage example:
#inject IUserInfo UserInfo
#page "/"
<div>#UserInfo.Name</div>
<div>#UserInfo.Email</div>
I am trying to call the CRM Dynamics On Premise 2016 Web API.
I configured Authorization Code Flow using OAuth and it is working. But, i need to set up the Client Credentials flow since many applications are running on background and they can't be prompted with login screen.
Since, its On Premise, we dont have Azure AD.
Where do we go and register our application?
Is there another way to access Web API for On premise dynamics CRM( For example userid,password etc)
Xrm api is accessible via client credentials without any special setup (be it on-prem or on-line) - you just setup S2S user with appropriate permissions, and you can log him in like:
static void InContext(Action<IOrganizationService> callback, Org org)
{
var credentials = new ClientCredentials();
if (!org.IsLocal)
{
credentials.UserName.UserName = org.UserName;
credentials.UserName.Password = org.Password;
}
else
{
credentials.Windows.ClientCredential = new NetworkCredential(org.UserName, org.Password);
}
using (var serviceProxy =
new OrganizationServiceProxy(new Uri(org.OrganizationServiceUri),
null, credentials
, null))
{
callback.Invoke(serviceProxy);
}
}
public class Org
{
public string UserName { get; set; }
public string Password { get; set; }
public string OrganizationServiceUri { get; set; }
public bool IsLocal { get; set; }
public Org()
{
}
public Org(bool isLocal, string userName, string password, string organizationServiceUri)
{
IsLocal = isLocal;
UserName = userName;
Password = password;
OrganizationServiceUri = organizationServiceUri;
DiscoveryServiceUri = discoveryServiceUri;
}
}
And then in your backend code:
var org = new Org(true, "Administrator", "Password",
"http://ondracrm/org/XRMServices/2011/Organization.svc");
InContext((os) => {
// some sample work with organization service
var response = (RetrieveEntityResponse)os.Execute(
new RetrieveEntityRequest
{
LogicalName = "contact",
EntityFilters = EntityFilters.Attributes
});
}, org);
I have a test class with a couple tests that check to see if the entity IsValid. I moved to using IValidatableObject from having my own custom validation but I'm stuck with the correct validation technique.
This is my Test class:
[TestFixture]
public class StudentTests {
private static Student GetContactWithContactInfo()
{
return new Student(new TestableContactRepository())
{
Phone = "7275551111"
};
}
private static Student GetContactWithoutContactInfo()
{
return new Student(new TestableContactRepository());
}
[Test]
public void Student_Saving_StudentHasInfo_IsValid ()
{
// Arrange
Student student = GetContactWithContactInfo();
// Act
student.Save();
// Assert
Assert.IsTrue(student.IsValid);
}
[Test]
public void Student_Saving_StudentDoesNotHaveInfo_IsNotValid ()
{
// Arrange
Student student = GetContactWithoutContactInfo();
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
}
This is my entity:
public class Student : IValidatableObject
{
private readonly IContactRepository contactRepository;
public Student(IContactRepository _contactRepository)
{
contactRepository = _contactRepository;
Contacts = new List<Student>();
}
[Required]
public int Id { get; private set; }
[StringLength(10, MinimumLength = 10)]
public string Phone { get; set; }
public List<Student> Contacts { get; private set; }
public bool IsValid { get; private set; }
public void Save()
{
if (IsValidForPersistance())
{
IsValid = true;
Id = contactRepository.Save();
}
}
private bool IsValidForPersistance()
{
return Validator.TryValidateObject(this, new ValidationContext(this), null, true);
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Phone) && Contacts.All(c => string.IsNullOrEmpty(c.Phone)))
yield return new ValidationResult("The student or at least one contact must have a phone number entered", new[] { "Phone Number" });
}
}
As you can see the tests test for IsValid by calling the IsValidForPersistance. Validate will eventually have more validation .
The above tests all pass using this method but this test below also passes but should not.
[Test]
public void Student_Saving_HasContactInfoWithInvalidLength_IsNotValid()
{
// Arrange
Contact student = GetContactWithoutContactInfo();
student.Phone = "string";
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
Here I'm setting my own Phone value of an invalid length string. I expect validation to fail because of the StringLength annotation set at min and max 10 characters.
Why is this passing?
Update
There was a problem with the custom validation, updated the code with the change. Along with the suggestion from nemesv about not having a private modifier on the Phone property it now works. I've updated all the code to working.
Validator.TryValidateObject only checks the RequiredAttributes (and also other things like type level attributes and IValidatableObject implementation) by default.
If you need to validate all the attributes like StringLength etc. you need to set the validateAllProperties parameter of the method to true
private bool IsValidForPersistance() {
return Validator.TryValidateObject(this,
new ValidationContext(this),
null,
true /* validateAllProperties */);
}
I am trying to use AutoMapper for the first time and have some problems with it.
My code is below and I get error below. Maybe someone could show how to map the list of models?
cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'Entity.Product' C:\Users\Administrator\Projects\PC\trunk\PC\Controllers\AdminController.cs 37 100 PC
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int UsersCount { get; set; }
}
var products = _repository.GetProducts(true).Select(p=> new
{
p.Id,
p.Name,
UsersCount = 0
});
Mapper.CreateMap<Product, ProductViewModel>();
ViewData["Products"] = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products); //Error appears on products object
//Product domain model(linq2sql generated model)
public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private bool _Active;
private System.Nullable<int> _Sort;
private System.Nullable<int> _Category;
private string _Name;
private int _ProductTypeId;
private decimal _Price;
private System.Nullable<int> _Months;
private System.Nullable<int> _Credits;
private string _Features;
private string _BlockReason;
private string _BuyUrl1;
private string _BuyUrl2;
private bool _UsersManager;
}
In your LINQ query you select an anonymous object. Make sure you select a Product which is your source type (or more specifically IEnumerable<Product>):
IEnumerable<Product> products = _repository.GetProducts(true);
IEnumerable<ProductViewModel> productsViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products);
return View(productsViewModel);
Also do not call Mapper.CreateMap<TSource, TDest> inside your controller action. This must be called only once in the lifetime of the AppDomain, ideally in your Application_Start.
Also notice that I have gotten rid of ViewData which is a great thing. You don't need ViewData. You are working with view models. That's what they are supposed to do. Contain information that will be needed by your view in a strongly typed manner.
I have an ASP.NET web site that will use Active Directory to store Users.
There is a requirement to allow users to use their emails as username.
Active directory will not allow characters like "#" in the usernames.
I created a class to extend the ActiveDirectoryMembershipProvider; It converts usernames from (user#domain.com to user_x0040_domain.com ) before calling the base class functions.
example:
public override bool ValidateUser(string username, string password)
{
string encodedUsername = this.Encode(username);
return base.ValidateUser(encodedUsername, password);
}
The Problem is that in the MembershipUser does not allow changing the username.
How can I handle overriding the methods that return MembershipUser?
Like MembershipUser GetUser(string username, bool userIsOnline)
I suppose you could do this overriding the MembershipUser returned by the Active Directory provider, something like this:
public class MyActiveDirectoryMembershipProvider : ActiveDirectoryMembershipProvider
{
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
ActiveDirectoryMembershipUser user = (ActiveDirectoryMembershipUser)base.GetUser(providerUserKey, userIsOnline);
if (user == null)
return null;
return new MyActiveDirectoryMembershipUser(user);
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
MembershipUserCollection newColl = new MembershipUserCollection();
foreach (ActiveDirectoryMembershipUser user in base.FindUsersByName(usernameToMatch, pageIndex, pageSize, out totalRecords))
{
newColl.Add(new MyActiveDirectoryMembershipUser(user));
}
return newColl;
}
// TODO: check other methods to override
}
public class MyActiveDirectoryMembershipUser : ActiveDirectoryMembershipUser
{
private string _userName;
public override string UserName
{
get
{
return _userName;
}
}
public MyActiveDirectoryMembershipUser(ActiveDirectoryMembershipUser user)
{
// TODO: do your decoding stuff here
_userName = MyDecode(user.Email);
}
}
NOTE: you will need to ensure all methods that return a user are overriden. It also has a some performance impact on collection methods, because you'll need to duplicate the collection (as I have shown in the sample).