I'm trying to find the best solution to have a local database in my WP8.1 application.
I'm using the standard WP8.1 (non-SL) and Visual Studio 2013.
I've looked into SQLite but I couldn't manage to get it to work on my application/Visual Studio.
If I can use SQLite, I need someone to point me out the way to go. Else, please refer me the best solution.
Thanks in advance!
Here's a repository class that leverages SQLite:
public class ContactsRepository : IContactsRepository
{
SQLiteAsyncConnection _connection = null;
static ContactsRepository _repository = null;
private ContactsRepository()
{
}
public async Task Initialize()
{
_connection = new SQLiteAsyncConnection(Constants.DATABASE_FILE_NAME);
await EnsureTableExist<ContactReference>(_connection);
}
public static ContactsRepository Instance
{
get
{
if (_repository == null)
{
_repository = new ContactsRepository();
}
return _repository;
}
}
public async Task Add(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
else
{
await _connection.InsertAsync(new ContactReference()
{
CategoryName = category.Name,
ContactId = contact.Id
});
}
}
public async Task Update(Category category, Contact contact)
{
var result = await _connection.Table<ContactReference>().Where(c => c.ContactId == contact.Id).FirstOrDefaultAsync();
Debug.Assert(result != null);
if (result == null)
{
throw new Exception("Unable to update category. Candidate not found");
}
if (result != null)
{
result.CategoryName = category.Name;
await _connection.UpdateAsync(result);
}
}
public async Task<ObservableCollection<Contact>> Get(string categoryName)
{
var result = new ObservableCollection<Contact>();
var query = _connection.Table<ContactReference>().Where(c => c.CategoryName == categoryName);
var queryResult = await query.ToListAsync();
foreach(var contact in queryResult)
{
var phoneContacts = ResourceLocator.Instance[typeof(ObservableCollection<Contact>)] as ObservableCollection<Contact>;
var phoneContact = phoneContacts.Where(c => c.Id == contact.ContactId).FirstOrDefault();
Debug.Assert(phoneContact != null);
if (phoneContact != null)
{
result.Add(phoneContact);
}
}
return result;
}
public async Task<ObservableCollection<ContactReference>> Get()
{
var result = new ObservableCollection<ContactReference>();
var query = _connection.Table<ContactReference>();
var queryResult = await query.ToListAsync();
foreach (var contact in queryResult)
{
result.Add(contact);
}
return result;
}
private async Task EnsureTableExist<T>(SQLiteAsyncConnection connection) where T : new()
{
bool noTableExists = false;
try
{
var query = await connection.Table<T>().FirstOrDefaultAsync();
}
catch (SQLiteException ex)
{
if (ex.Message.Contains("no such table"))
{
noTableExists = true;
}
}
if (noTableExists)
{
await connection.CreateTableAsync<T>();
}
}
}
Related
this controller login
[EnableCors("AllowOrigin")]
[HttpPost("login")]
public IActionResult Login(string aimUserMail, string aimUserPassword)
{
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserMail == aimUserMail && x.AimUserPassword == aimUserPassword);
return BadRequest(error: new { message = "UserEmail or password is not correct" });
//}
if (user == null)
{
return BadRequest(error: new { message = "UserEmail or password is not correct ...." });
}
var jwt = this.jwt.Generete(user.AimUserId);
Response.Cookies.Append("jwt",jwt, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
});
return Ok(user);
}
this is controller check auth :
[HttpGet("user")]
public IActionResult User()
{
try
{
var jwt = Request.Cookies["jwt"];
var token = this.jwt.Verify(jwt);
int aimUserId = int.Parse(token.Issuer);
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserId == aimUserId);
return Ok(user);
}
catch (Exception e)
{
return Unauthorized();
}
}
Your jwt is null, seems you have add return method in your login function.
If you want get all cookie, you can try below code. Then you can check what you want.
[HttpGet("GetAllCookie")]
public IActionResult GetCookie()
{
int count = Request.Cookies.Count;
var CookiesArray = Request.Cookies.Keys.ToArray();
List<CookieObj> list = new List<CookieObj>();
CookieObj o;
for (int i = 0; i < count; i++)
{
o = new CookieObj();
string cookieKey = CookiesArray[i];
o.cookiename = cookieKey;
o.cookievalue = Request.Cookies[cookieKey];
list.Add(o);
}
return Ok(list);
}
public class CookieObj {
public string cookiename { get; set; }
public string cookievalue { get; set; }
}
I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.
I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.
Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.
So I am trying to use the Novell.Directory.Ldap.NetStandard library.
Here is the code the other developer sent me:
public static List<UserProfileModel> GetADUsers(string alias)
{
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
// Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
de2.Path = ConfigurationManager.AppSettings["AD_Path"];
de2.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de2;
deSearch.Filter = "(samaccountname=*" + alias + "*)";
LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));
SearchResultCollection results = deSearch.FindAll();
String raw = "";
LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));
if (results.Count > 0)
{
foreach (SearchResult item in results)
{
UserProfileModel userProfileModel = new UserProfileModel();
userProfileModel.Name = GetADProperty("name", item);
userProfileModel.email = GetADProperty("mail", item);
userProfileModel.identity = GetADProperty("userPrincipalName", item);
userProfileModel.first_name = GetADProperty("givenName", item);
userProfileModel.last_name = GetADProperty("sn", item);
users.Add(userProfileModel);
raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
}
LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
}
}
catch (Exception e)
{
LOGGER.Error("Unable to Query Active Directory", e);
}
return users;
}
I need to translate this into Novell's LDAP library.
Here is my attempt:
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = "ourOrg.gov";
string loginDn = #"ourOrg\myName";
string password = "myPass";
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchResults results = con.Search(
"cn=users,dc=ourOrg,dc=gov",
LdapConnection.SCOPE_ONE,
"samaccountname=*",
null,
false);
// NO RESULTS:(
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
I don't get an error.
But there are 0 results.
I originally had this part:
"samaccountname=*",
like:
"samaccountname={alias}",
but I'm just trying to get back results at this point.
I got this working:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hrsa.Core.Web.App.Controllers.Api
{
[Route("api/[controller]")]
public class ActiveDirectoryController : Controller
{
private readonly AppSettings _appSettings;
public ActiveDirectoryController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = _appSettings.HrsaLdapHost; // ourOrgName.gov
string loginDn = _appSettings.AdUser;
string password = _appSettings.AdPassword;
string searchBase = _appSettings.HrsaAdSearchBase;
string searchFilter = $"(samaccountname=*{alias}*)";
string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
"description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchQueue queue = con.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
attributes,
false,
(LdapSearchQueue)null,
(LdapSearchConstraints)null);
LdapMessage message;
while ((message = queue.getResponse()) != null)
{
if (message is LdapSearchResult)
{
LdapEntry entry = ((LdapSearchResult)message).Entry;
LdapAttributeSet attributeSet = entry.getAttributeSet();
users.Add(new UserProfileModel
{
Cn = attributeSet.getAttribute("cn")?.StringValue,
UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
St = attributeSet.getAttribute("st")?.StringValue,
Givenname = attributeSet.getAttribute("givenname")?.StringValue,
Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
Description = attributeSet.getAttribute("description")?.StringValue,
Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
Department = attributeSet.getAttribute("department")?.StringValue,
Displayname = attributeSet.getAttribute("displayname")?.StringValue,
Name = attributeSet.getAttribute("name")?.StringValue,
Mail = attributeSet.getAttribute("mail")?.StringValue,
GivenName = attributeSet.getAttribute("givenName")?.StringValue,
Sn = attributeSet.getAttribute("sn")?.StringValue
});
}
}
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
I have been following the tutorials here to build my application. Everything works well at the authentication side. Now, the problem I am having is when I move to the resource server to retrieve data. If I place the [Authorize] on any method in the resource server I get the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 500.". If I remove it everything works fine but I am unable access any claims or roles associated with the user
Excerpts of the startup.cs code of my AuthServer is as follows
public class Startup
{
string PublicHostUri { get { return "https://localhost:44354"; } }
private readonly IHostingEnvironment _environment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
_environment = env;
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration["Data:UserAccConnection:ConnectionString"];
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "reportbook.auth.pfx"), "");
var reportbookConnnectionString = Configuration["Data:ReportBookDbConnection:connectionString"];
services.AddDbContext<ReportBookDbContext>(options =>
options.UseSqlServer(reportbookConnnectionString));
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(connectionString, b => b.MigrationsAssembly(migrationsAssembly)));
// Register the Identity services.
services.AddIdentity<ApplicationUser, UserRole>()
.AddEntityFrameworkStores<UserDbContext, Guid>()
.AddDefaultTokenProviders();
services.AddCors();
services.AddMvc();
services.AddIdentityServer()
.AddDefaultEndpoints()
.AddOperationalStore(builder =>
builder.UseSqlServer(connectionString,
options => options.MigrationsAssembly(migrationsAssembly)))
.AddConfigurationStore(builder =>
builder.UseSqlServer(connectionString,
options => options.MigrationsAssembly(migrationsAssembly)))
.SetSigningCredential(cert)
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IUnitOfWorkAsync, UnitOfWork>();
services.AddScoped<IDataContextAsync, ReportBookDbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
InitializeDbTestData(app);
}else
{
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
}
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseCsp(options => options.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self()
.CustomSources("*"))
.ScriptSources(directive => directive.Self()
.UnsafeInline())
.StyleSources(directive => directive.Self()
.UnsafeInline()));
app.UseXContentTypeOptions();
app.UseXfo(options => options.Deny());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
app.UseIdentity();
app.UseIdentityServer();
//app.UseMvc(routes =>
//{
// routes.MapRoute(
// name: "default",
// template: "{controller=Home}/{action=Index}/{id?}");
//});
app.UseMvcWithDefaultRoute();
app.UseMvc();
//databaseInitializer.Seed(app).GetAwaiter().GetResult();
}
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
if (!context.Clients.Any())
{
foreach (var client in Clients.Get())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.Scopes.Any())
{
foreach (var clientSope in Scopes.Get())
{
context.Scopes.Add(clientSope.ToEntity());
}
context.SaveChanges();
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<UserRole>>();
if (!userManager.Users.Any())
{
foreach (var newUser in Users.Get())
{
ApplicationUser user = new ApplicationUser();
user.Id = new Guid();
user.EmailConfirmed = true;
user.UserName = newUser.Email;
user.UserNo = newUser.UserNo;
user.FirstName = newUser.FirstName;
user.LastName = newUser.LastName;
user.Gender = newUser.Gender;
user.UserCategory = newUser.UserCategory;
user.ZoneInfo = newUser.ZoneInfo;
userManager.CreateAsync(user, "Password123!").Wait();
userManager.AddClaimAsync(user, new Claim("UserCategory", user.UserCategory)).Wait();
foreach (var role in newUser.UserRoles)
{
if (!roleManager.RoleExistsAsync(role).GetAwaiter().GetResult())
{
UserRole userRole = new UserRole();
userRole.Id = new Guid();
userRole.Name = role;
roleManager.CreateAsync(userRole).Wait();
}
userManager.AddToRoleAsync(user, role).Wait();
userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Role, role)).Wait();
}
}
}
}
}
}
Excerpts of startup.cs file of the resource server is as follows
public class Startup
{
private IHostingEnvironment _env { get; set; }
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
//private static void InitializeDbTestData(IApplicationBuilder app)
//{
// using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
// {
// scope.ServiceProvider.GetRequiredService<ReportBookDbContext>().Database.Migrate();
// }
//}
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
var folderForKeyStore = Configuration["Data:keystore:KeyStoreFolderWhichIsBacked"];
var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "reportbook.auth.pfx"), "");
services.AddDataProtection()
.SetApplicationName("ReportBook")
.ProtectKeysWithDpapiNG("CERTIFICATE=Hashid:" + cert.Thumbprint,flags: DpapiNGProtectionDescriptorFlags.None);
services.AddDbContext<ReportBookDbContext>(options =>
options.UseSqlServer(Configuration["Data:ReportBookDbConnection:connectionString"],
b => b.MigrationsAssembly("ReportBook.Resource")));
// Add framework services.
services.AddCors();
services.AddApplicationInsightsTelemetry(Configuration);
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
app.UseStatusCodePagesWithReExecute("/error");
if (env.IsDevelopment())
{
//InitializeDbTestData(app);
}
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
{
Authority = "https://localhost:44354/",
ScopeName = "resource_server",
ScopeSecret = new IdentityServer4.Models.Secret("scopeSecret".Sha256()).ToString(),
AutomaticAuthenticate = true,
SupportedTokens = SupportedTokens.Both,
AutomaticChallenge = true
};
app.UseIdentityServerAuthentication(identityServerValidationOptions);
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
app.UseMvc();
}
}
Below is the an excerpt of the the controller whose method I am trying to reach
[HttpGet("GetInstitutions")]
//[Authorize]
public IActionResult GetInstitutions([FromQuery]InstitutionSearchQry model)
{
var authorisation = Request.Headers["Authorization"];
bool auth = User.Identity.IsAuthenticated;
IEnumerable<Institution> _institutions = null;
string userCategory = User.Claims.Where(a => a.Type == "UserCategory").Select(a => a.Value).FirstOrDefault().ToString();
string zoneInfo = User.Claims.Where(a => a.Type == "ZoneInfo").Select(a => a.Value).FirstOrDefault().ToString();
string userNo = User.Claims.Where(a => a.Type == "UserNo").Select(a => a.Value).FirstOrDefault().ToString();
bool admin = User.IsInRole("Admin");
List<Student> students = new List<Student>();
//Institution institution = _institutionService.Find(a => a.InstitutionID == zoneInfo);
var pagination = Request.Headers["Pagination"];
if (!string.IsNullOrEmpty(pagination))
{
string[] vals = pagination.ToString().Split(',');
int.TryParse(vals[0], out page);
int.TryParse(vals[1], out pageSize);
}
switch (userCategory)
{
case "Guardian":
{
students = _guardianService.GetStudents(userNo).ToList();
_institutions = _admissionService.GetInstitutions(students.Select(a => a.StudentID).ToList(),model.StartYear,model.EndYear, s => s.Term.AcademicYear.Institution.UniversityInstitutes.Select(a => a.University));
}
break;
case "Student":
{
_institutions = _admissionService.GetInstitution(userNo,s=>s.Term.AcademicYear.Institution.UniversityInstitutes.Select(a=>a.University));
}
break;
default:
{
_institutions = _institutionService.GetInstitutions(a => a.AdministrativeStructure.ZoneInfo == zoneInfo && a.Level.LevelName==model.Level, page, pageSize, out totalCount, s => s.AdministrativeStructure, s => s.Level,s=>s.UniversityInstitutes.Select(a=>a.University));
}
break;
}
if (!String.IsNullOrEmpty(model.Level) && model.Level != "myschool")
{
_institutions = _institutions.Where(a => a.Level.LevelName == model.Level);
}
var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
Response.AddPagination(page, pageSize, totalCount,totalPages);
Response.AddIdentityInfo(userCategory, admin, userNo, zoneInfo);
IEnumerable<InstitutionDataViewModel> _instDataModel = Mapper.Map<IEnumerable<Institution>, IEnumerable<InstitutionDataViewModel>>(_institutions);
return new OkObjectResult(_instDataModel);
}
The following is the angular 2 code from where the call is made to the resource server
#Injectable()
export class InstitutionService {
private resourceApiUrl: string;
private headers: Headers;
private storage: any;
private actionUrl: string;
public totalItems: number;
constructor(private _http: Http,
private itemsService: ItemsService,
private _configuration: Configuration,
private _router: Router,
private _authService: AuthService) {
this.resourceApiUrl = `${_configuration.resourceServer}api/Institution/`;
}
private SetHeaders(page?: number, itemsPerPage?: number) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
if (page != null && itemsPerPage != null) {
this.headers.append('Pagination', page + ',' + itemsPerPage);
}
var token = this._authService.GetToken();
if (token !== "") {
let tokenValue = 'Bearer ' + token;
console.log("tokenValue:" + tokenValue);
this.headers.append('Authorization', tokenValue);
}
}
public GetInstitutions = (InstitutionSearchQry?: any, page?: number, itemsPerPage?: number): Observable<PaginatedResult<IInstitution[]>> => {
this.SetHeaders(page, itemsPerPage);
var paginatedResult: PaginatedResult<IInstitution[]> = new PaginatedResult<IInstitution[]>();
let options = new RequestOptions({ headers: this.headers, body: '' });
if (!InstitutionSearchQry.level) {
this.actionUrl = "GetInstitutions";
} else {
this.actionUrl = "GetInstitutions/", InstitutionSearchQry;
}
return this._http.get(this.resourceApiUrl + this.actionUrl, options)
.map((res: Response) => {
//console.log(res.headers.keys());
paginatedResult.result = res.json();
if (res.headers.get("Pagination") != null) {
//var pagination = JSON.parse(res.headers.get("Pagination"));
var paginationHeader: Pagination = this.itemsService.getSerialized<Pagination>(JSON.parse(res.headers.get("Pagination")));
paginatedResult.pagination = paginationHeader;
}
if (res.headers.get("IdentityInfo") != null) {
var identityInfo: IdentityInfo = this.itemsService.getSerialized<IdentityInfo>(JSON.parse(res.headers.get("IdentityInfo")));
paginatedResult.identityInfo = identityInfo;
}
this.totalItems = paginatedResult.pagination.TotalItems;
return paginatedResult;
}).catch(this.handleError);
};
}
So basically the authorisation information provided at the AuthServer side is not reaching the resource server.
As one can see I have added the 'CORS' service in both files.
Use this plugin for chrome browser. get from here
i want to check if some files exists in a folder on ftp then do specific task
i have the following methos for files check
public static bool CheckFileExistOnFTP(string ServerUri, string FTPUserName, string FTPPassword)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerUri);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
//request.Method = WebRequestMethods.Ftp.GetFileSize;
// request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
return true;
}
and i call that method on formload
if (FTPUtility.CheckFileExistOnFTP("ftp://ip address/Requests/", "edexcrawler", "edexcrawler123"))
{
btnUploadRequest.Visible = true;
btnUploadRequest.BackColor = System.Drawing.Color.LightGreen;
btnUploadRequest.ForeColor = System.Drawing.Color.Blue;
}
Based on your other question to get a list of files from ftp, you can check if the file you want to check is in that list:
Var fileNameToCkeck = "myfile.txt";
var utility= new FtpUtility();
utility.UserName = "...";
utility.Password = "...";
utility.Path = "...";
If (utility.ListFiles().Contains(fileNameToCkeck))
{
//The file exists
}
Or if you want to know if that path has any file:
If (utility.ListFiles().Count() > 0)
{
//The folder contains files
}
And here is the code for FtpUtility
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
I would like to manage users and roles with the default ASP.NET MVC 5 membership in a LocalDB database file in the app_data folder. This is automatically created if it does not exist.
I wrote a role editor, but when I attempt to apply roles to the Web API as follows:
[Authorize(Roles= "SystemAdmin")]
, the role manager attempts to call a stored procedure inside the database.
Invalid object name 'dbo.aspnet_SchemaVersions'.
This stored procedure would normally be created in a full SQL Server membership database created by the aspnet_regsql utility, however the aspnet_regsql utility only operates on a full SQL Server database and not on a LocalDB database.
Is there any way to tell the Role Provider not to make this stored procedure call without having to write a Role Provider from scratch? I have my database connection defined as follows -
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\DefaultConnection.mdf;Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SqlClient" />
I have written an alternate solution - a custom RoleProvider that works with LocalDB .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using MyApp.Models;
namespace MyAppNamespace
{
/// <summary>
/// The purpose of this role provider is to support membership + roles in a MSSQL LocalDB.
/// It works around the limitation of the standard SqlRoleProvider
/// which requires stored procedures in a SQL Server database.
/// </summary>
public class CustomRoleProvider : RoleProvider
{
public override string ApplicationName { get; set; }
public override string[] GetRolesForUser(string username)
{
using (var usersContext = new ApplicationDbContext())
{
var user = usersContext.Users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) || u.Email.Equals(username, StringComparison.CurrentCultureIgnoreCase));
if (user == null) return new string[] { };
var roles = from ur in user.Roles
from r in usersContext.Roles
where ur.RoleId == r.Id
select r.Name;
if (roles != null)
return roles.ToArray();
else
return new string[] { };
}
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
foreach(var userName in usernames)
{
var roles = GetRolesForUser(userName);
foreach(var roleName in roleNames)
{
if (!roles.Contains<string>(roleName))
{
using (var usersContext = new ApplicationDbContext())
{
var user = usersContext.Users.FirstOrDefault(u => u.UserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase));
if (user != null)
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
if (role != null)
{
var userRole = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole();
userRole.RoleId = role.Id;
userRole.UserId = user.Id;
user.Roles.Add(userRole);
}
}
usersContext.SaveChanges();
}
}
}
}
}
public override string[] GetAllRoles()
{
using (var usersContext = new ApplicationDbContext())
{
return usersContext.Roles.Select(r => r.Name).ToArray();
}
}
public override bool IsUserInRole(string username, string roleName)
{
return this.GetRolesForUser(username).Contains(roleName);
}
public override void CreateRole(string roleName)
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Id = Guid.NewGuid().ToString();
role.Name = roleName;
using (var usersContext = new ApplicationDbContext())
{
usersContext.Roles.Add(role);
usersContext.SaveChanges();
}
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
var usersInRole = GetUsersInRole(roleName);
if (throwOnPopulatedRole)
{
if (usersInRole.Length > 0)
{
throw new Exception("Role " + roleName + " is not empty");
}
}
var roleNameArray = new string[1];
roleNameArray[0] = roleName;
RemoveUsersFromRoles(usersInRole, roleNameArray);
using (var usersContext = new ApplicationDbContext())
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
if (role != null)
{
usersContext.Roles.Remove(role);
usersContext.SaveChanges();
return true;
}
return false;
}
}
public override bool RoleExists(string roleName)
{
using (var usersContext = new ApplicationDbContext())
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
return (role != null);
}
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
foreach (var userName in usernames)
{
var roles = GetRolesForUser(userName);
foreach (var roleName in roleNames)
{
if (!roles.Contains<string>(roleName))
{
using (var usersContext = new ApplicationDbContext())
{
var user = usersContext.Users.FirstOrDefault(u => u.UserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase));
if (user != null)
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
if (role != null)
{
var userRole = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole();
userRole.RoleId = role.Id;
userRole.UserId = user.Id;
user.Roles.Remove(userRole);
}
}
usersContext.SaveChanges();
}
}
}
}
}
public override string[] GetUsersInRole(string roleName)
{
using (var usersContext = new ApplicationDbContext())
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
var users = from ur in role.Users
from u in usersContext.Users
where ur.RoleId == u.Id
select u.UserName;
if (users != null)
return users.ToArray();
else
return new string[] { };
}
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
var regEx = new System.Text.RegularExpressions.Regex(usernameToMatch);
using (var usersContext = new ApplicationDbContext())
{
var role = usersContext.Roles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
var users = from ur in role.Users
from u in usersContext.Users
where ur.RoleId == u.Id
&& regEx.IsMatch(u.UserName)
select u.UserName;
if (users != null)
return users.ToArray();
else
return new string[] { };
}
}
}
}