I have created a database, linked it with DomainService's within my Silverlight Application. Now I want to be able to perform certain actions, such as Registration, Login etc. by using the service.
How would I be able to do this. I have preset methods created in the service, e.g. InsertUser but it only requires one parameter, so I'm not sure how it works. In the metadata I have all fields etc.
Can anyone help me out here.
Thanks.
public IQueryable<User> GetUsers()
{
return this.ObjectContext.Users;
}
public void InsertUser(User user)
{
if ((user.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Added);
}
else
{
this.ObjectContext.Users.AddObject(user);
}
}
For retrieving User I have used (as a base from TBohnen.jnr code):
UserContext _userContext = new UserContext();
public MainPage()
{
InitializeComponent();
LoadOperation loGetUsers = _userContext.Load(_userContext.GetUsersQuery());
loGetUsers.Completed += new EventHandler(loGetUsers_Completed);
}
void loGetUsers_Completed(object sender, EventArgs e)
{
LoadOperation<Web.User> lo = (LoadOperation<Web.User>)sender;
var user = _userContext.Users;
MessageBox.Show(user.ToString());
}
This is to add a new user:
YourDomainContext dc = new YourDomainContext();
User userToAdd = new User();
//You will have to set your properties here as I don't know them, I will give an example.
userToAdd.username = "NewUser";
dc.User.Add(userToAdd);
dc.SubmitChanges();
To retrieve your existing users:
YourDomainContext dc = new YourDomainContext();
LoadOperation loGetUsers = dc.Load(dc.GetUsersQuery());
loGetUsers.Completed += new EventHandler( loadOperation_Completed );// You will see there is a callback overloads as well
and then add this as well.
private void loadOperation_Completed( object sender, EventArgs e )
{
LoadOperation<User> lo = (LoadOperation<User>)sender;
//Have a look at all the properties like lo.Error etc. but to see the retrieved users you can either use:
var users = lo.AllEntities;
//or if you declared your domaincontext as a class level parameter:
var users = dc.User;
foreach (Web.User user in users)
{
MessageBox.show(user.username);
}
}
This will trigger an async call that get's all the users and will add it to the DomainContext and you will be able to access it through dc.User
Related
I have to perform Auth0 authentication process and extract the token.
I have Authenticator class as below -
class Auth0Authenticator
{
public Auth0Authenticator() { performAuthentication(); }
public void performAuthentication()
{
Auth0Client auth0Client = new Auth0Client(new Auth0ClientOptions()
{
Domain = "mydomain",
ClientId = "clientid",
});
var extraParameters = new Dictionary<string, string>();
extraParameters.Add("connection", "parameter");
var result = auth0Client.LoginAsync(extraParameters: extraParameters);
}
}
while executing LoginAsync I am getting error - The calling thread must be STA, because many UI components require this.
even after creating STA thread or adding attribute [STAThread] not helping.
When i executed the same code in a simple dialog based application, code is successufully returning me the token. but putting the same code in my project(consists of MFC/C#/CLI) throwing error.
Can anyone help please?
This may be an XY problem. Auth0Client.LoginAsync is an async API and you are trying to invoke it in the constructor of your class. This can have negative consequences if there is code dependent on that function completing before being able to perform their functions.
Refactor the code to follow suggested syntax
public class Auth0Authenticator {
public Auth0Authenticator() {
//Subscribe to the event
autoAuthenticate += onAutoAuthenticating();
//raise event to allow async operation.
autoAuthenticate(this, EventArgs.Empty);
}
private event EventHandler autoAuthenticate = delegate { };
private async void onAutoAuthenticating(object sender, EventArgs args) {
await PerformAuthenticationAsync();
}
public async Task PerformAuthenticationAsync() {
Auth0Client auth0Client = new Auth0Client(new Auth0ClientOptions() {
Domain = "mydomain",
ClientId = "clientid",
});
var extraParameters = new Dictionary<string, string>();
extraParameters.Add("connection", "parameter");
var result = await auth0Client.LoginAsync(extraParameters: extraParameters);
//...do something with the result as needed
string access_token = result.AccessToken;
string refresh_token = result.RefreshToken;
//...
}
}
I am currently attempting to implement DayPilot Lite MVC on my project. I've set up my events and they are clickable(tested with a Debug statement). However what i am looking to do is process the click and load a new View, using a ViewModel built from the id of the event I clicked.
public ActionResult Booking()
{
ApplicationDbContext db = new ApplicationDbContext();
int id = Dpc.eventID;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lesson lesson = db.Lessons.Find(id);
if (lesson == null)
{
return HttpNotFound();
}
return View(lesson);
}
class Dpc : DayPilotCalendar
{
public int eventID;
protected override void OnInit(InitArgs e)
{
ApplicationDbContext db = new ApplicationDbContext();
Events = from ev in db.Lessons select ev;
DataIdField = "ClassID";
DataTextField = "ClassLevel";
DataStartField = "ClassStartDate";
DataEndField = "ClassEndDate";
Update();
}
protected override void OnEventClick(EventClickArgs e)
{
//Test to check the method was firing
Debug.WriteLine("Hey I clicked you");
//Parse the event ID for processing
eventID = int.Parse(e.Id);
//Redirect to the booking page
Redirect("Schedule/Booking");
}
}
When I tried to code the Booking method, it resulted in telling me that Dpc.eventID needs an object reference. I have tried making the class and the variable public, but the error persists. I can't make the eventClick public as then i can't override the original. I'm using Redirect because if i try any other link it fails for the same reason. I'm guessing it's because it's a non-inherited subclass, but should i not still be able to access its member attributes if they have a public scope?
I'm having an issue with an internal MVC site. I may have titled this wrong as I don't know exactly where the issue lies. I have the following custom authorize attribute:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute(params string[] roles)
{
using (var dataLayer = new CarrierBoundEntities())
{
string userNames = string.Empty;
foreach (var user in dataLayer.tbl_PremiumWriteOffs_Users)
{
if (roles.Contains(user.Role))
{
userNames += user.Username + ",";
}
}
if (userNames.Length > 0)
{
// Remove last comma
userNames.Remove(userNames.Length - 1);
}
Users = userNames;
}
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
}
The datalayer is the default DbContext created by the Entity Framework. There is a view that allows users with an admin role to add/edit users. Here is the controller that handles a post to edit a user:
[HttpPost]
[ValidateAntiForgeryToken]
[CustomAuthorize(new string[] { "Admin" })]
public ActionResult UsersEditView(UsersVM viewModel)
{
using (var dataLayer = new CarrierBoundEntities())
{
var userToEdit = dataLayer.tbl_PremiumWriteOffs_Users.SingleOrDefault(x => x.ID == viewModel.UserSubmit.ID);
if (userToEdit == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// If the username was changed then check and display error if it's the same as another entry
if (userToEdit.Username.Equals(viewModel.UserSubmit.Username, StringComparison.OrdinalIgnoreCase) == false)
{
foreach (var user in dataLayer.tbl_PremiumWriteOffs_Users)
{
if (user.Username.Equals(viewModel.UserSubmit.Username, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("UserSubmit.Username", "A user with this username already exists.");
break;
}
}
}
if (ModelState.IsValid)
{
userToEdit.Username = viewModel.UserSubmit.Username;
userToEdit.Role = viewModel.UserSubmit.Role;
userToEdit.UserLastModified = this.User.Identity.Name;
userToEdit.DateLastModified = DateTime.Now;
dataLayer.SaveChanges();
return RedirectToAction("UsersView");
}
viewModel.RoleSelect = GetRoleSelectList();
return View(viewModel);
}
}
Now when I run it locally on my machine things work fine, but when deployed on a server something doesn't get updated when a new user is added or the role of an existing user is changed. New users still don't get access to any part of the site, and a user that is changed from admin to user will still have access to the admin areas. It stays this way until the app is restarted on the server.
The odd thing is that after making a change, the change is visible on both the front end and back end, so it seems that both the database and entity context are being updated fine. So I'm thinking it might be the custom authorize attributes that aren't updating with the new list of usernames, but I really have no idea and am having trouble debugging since it works as it should locally.
Any help would be greatly appreciated.
The way you are trying to extend the AuthorizeAttribue is wrong. You need to do something like this:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private string[] _roles;
public CustomAuthorizeAttribute(params string[] roles)
{
_roles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var user = httpContext.User;
var isAuthorized = false;
// check in the database to see if the user
// is in one of the Roles in _roles and therefore authorized...
if(/* some code to check if the user is authorized */)
{
isAuthorized = true;
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
}
So basically I am trying to be able to show custom messages to the Burn UI during a custom action. (In this case show progress from DISM running in the background. This is the code I tried:
public static class CAExtensions
{
public static void SendMessage(this Session session, string message)
{
var record = new Record();
record.SetString(0, message);
session.Message(InstallMessage.Info, record);
}
}
This in my custom action I do this:
session.SendMessage("Message goes here");
I subscribe to the ExecuteMsiMessage event:
model.BootstrapperApplication.ExecuteMsiMessage += HandleMessage;
private void HandleMessage(object sender, ExecuteMsiMessageEventArgs e)
{
Installer.Dispatcher.Invoke((Action) (() =>
{
var rawMessage = string.Empty;
var app = model.GetAppData(e.PackageId);
if (app != null)
{
rawMessage = app.Item1.DisplayName + ": ";
}
rawMessage += e.Message;
InstallMessage = rawMessage;
}));
}
InstallMessage is bound to a Label in the UI. This shows all the standard messages, but not the ones I send in my custom actions.
Any idea what I am doing wrong?
The main issue is that Info level messages don't get passed to the ExecuteMsiMessage event. From my testing, I found that Warning was the only level that reliable were passed through.
I implemented this by adding an additional flag to the message so I could tell which messages were mine and which were real warning messages (which I didn't want to show in the UI). However, I don't show that here for simplicity:
In the CustomAction:
public virtual void SendMessage(string message, string[] data)
{
var fields = new List<object>(data);
using (var record = new Record(fields.ToArray()) { FormatString = message })
{
_session.Message(InstallMessage.Warning, record);
}
}
In the Bootstrapper:
private void EventProviderOnExecuteMsiMessage(object sender, ExecuteMsiMessageEventArgs executeMsiMessageEventArgs)
{
if (executeMsiMessageEventArgs.MessageType == InstallMessage.Warning)
{
var theActualMessage = executeMsiMessageEventArgs.Data.ToList();
//do something with theActualMessage here...
}
}
I want save users's IPs and activity in a table named logPublic,I want when a unAthenticated user try to access a speacial folder e.g Admin folder i can add a record in logpublic table that it have some fields for e,g : ID,IP,Activity,datetime .after that unathenticated user will be lock utomatically
I am use below code in Load_Page Event of masterpage in Admin folder:
$public partial class Admin : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Session["IsBlocked"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
HttpContext.Current.Session["Activity"] = HttpContext.Current.Request.Url;
HttpContext.Current.Session["DateTime"] = System.DateTime.Now;
}
else
{
if(! HttpContext.Current.User.IsInRole("Admin"))
{
Session["BlockUser"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
}
}
}
}
$namespace StoreProject.Data
{
public class CustomSecurityModule :IHttpModule
{
storedbEntities StoreEnt = new storedbEntities();
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
//throw new NotImplementedException();
context.BeginRequest += new EventHandler(this.app_DoSecuriy);
}
private void app_DoSecuriy(object sender, EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
storedbEntities StoreEnt = new storedbEntities();
if (context.Session["BlockUser"]!= null && Convert.ToBoolean(context.Session["BlockUser"])== true)
{
logPrivate Log = new logPrivate()
{
Username = context.User.Identity.Name,
IP = context.Session["UserIP"].ToString(),
Enter = System.DateTime.Now,
};
StoreEnt.logPrivates.AddObject(Log);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
//ublock != null && bool.TryParse(ublock.ToString(),out isblocked) && isblocked
else if ( context.Session["BlockPublick"] != null
&& System.Convert.ToBoolean(context.Session["BlockPublick"]) == true)
{
LogPublic newLog = new LogPublic()
{
IP = context.Session["UserIP"].ToString(),
Activity = context.Session["Activity"].ToString(),
Enter = Convert.ToDateTime(context.Session["DateTime"])
};
StoreEnt.LogPublics.AddObject(newLog);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
}
}
}
but when i run my application website ,i get an error from httpmodule :Object reference not set to an instance of an object. error in below line
if (context.Session["BlockUser"]!= null
&& Convert.ToBoolean(
context.Session["BlockUser"])== true)
i dont have any record in LogPublic table or logPrivate table when i want visit a page in Admin Folder
please guide me
thanks
Module's BeginRequest is too early to access the Session object as it hasn't been yet created by the ASP.NET Pipeline. You'd have to move your logic to one of later events in the processing pipeline (after PostAcquireRequestState)
http://msdn.microsoft.com/en-us/library/ms178473.aspx