Why am I getting 'Process is terminated due to StackOverflowException' in PM Console when I try and run my 'update-database' - sql

Everytime I try and update my SQL Db I am getting an error 'Process is terminated due to StackOverflowException' directly in the PM console. I think it's something being redundant and I believe it's related to an ApplicationDbContext<> statement but I have also referenced another students code and it seems to be identical. All Db sets are present as far as I can tell nothing has been changed with db names and the connection string looks correct.
my connection string in my config:
</connectionStrings>```
...and here is my seed method for roles (and my only one currently implemented)
protected override void Seed(ApplicationDbContext context)
{
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
if (!roleManager.RoleExists(RoleNames.ROLE_ADMINISTRATOR))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_ADMINISTRATOR));
}
if (!roleManager.RoleExists(RoleNames.ROLE_PROJECTMANAGER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_PROJECTMANAGER));
}
if (!roleManager.RoleExists(RoleNames.ROLE_DEVELOPER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_DEVELOPER));
}
if (!roleManager.RoleExists(RoleNames.ROLE_USER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_USER));
}
ApplicationUser userA = userManager.FindByEmail("ashortnm88#gmail.com");
if (userA == null)
{
userA = new ApplicationUser()
{
UserName = "ashortnm88#gmail.com",
Email = "ashortnm88#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userA, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userA.Id, RoleNames.ROLE_ADMINISTRATOR);
}
}
ApplicationUser userB = userManager.FindByEmail("DemoPM#gmail.com");
if (userB == null)
{
userB = new ApplicationUser()
{
UserName = "DemoPM#gmail.com",
Email = "DemoPM#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userB, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userB.Id, RoleNames.ROLE_PROJECTMANAGER);
}
}
ApplicationUser userC = userManager.FindByEmail("DemoDev#gmail.com");
if (userC == null)
{
userC = new ApplicationUser()
{
UserName = "DemoDev#gmail.com",
Email = "DemoDev#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userC, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userC.Id, RoleNames.ROLE_DEVELOPER);
}
}
ApplicationUser userD = userManager.FindByEmail("DemoUser#gmail.com");
if (userD == null)
{
userD = new ApplicationUser()
{
UserName = "DemoUser#gmail.com",
Email = "DemoUser#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userD, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userD.Id, RoleNames.ROLE_USER);
}
}
//TICKET STASUES
context.TicketStatus.AddOrUpdate(
t => t.Name,
new TicketStatus { Name = "New" },
new TicketStatus { Name = "Open" },
new TicketStatus { Name = "Resolved" },
new TicketStatus { Name = "Archived" });
//TICKET TYPES
context.TicketTypes.AddOrUpdate(
t => t.Name,
new TicketType { Name = "A" },
new TicketType { Name = "B" },
new TicketType { Name = "C" },
new TicketType { Name = "D" });
//TICKET PRIORITY
context.TicketPriorities.AddOrUpdate(
t => t.Name,
new TicketPriority { Name = "High"},
new TicketPriority { Name = "Low" },
new TicketPriority { Name = "Medium" });
//TICKET
context.SaveChanges();
}
public class RoleNames
{
public const string ROLE_ADMINISTRATOR = "Administrator";
public const string ROLE_PROJECTMANAGER = "Project Manager";
public const string ROLE_DEVELOPER = "Developer";
public const string ROLE_USER = "Submittee";
}
}

Related

When I sign in with SignInAsync in ASP.NET Core Identity, RedirectToLocal is not authenticated

When I sign in with SignInAsync in ASP.NET Core Identity, RedirectToLocal is not authenticated.
If I log in without returning Url or go to allow anonymous action, it works fine, but when I redirect authenticate action return to the login page like the user never signs in. Still, I go to allow anonymous action and see the user sign in everything is okay.
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWithSms(string userId, string code, string returnUrl)
{
if (userId == null)
{
throw new ArgumentNullException(nameof(userId));
}
if (code == null)
{
throw new ArgumentNullException(nameof(code));
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
throw new ApplicationException(string.Format(ErrorConstant.UnableToLoadUser, userId));
}
var result = await _userManager.ConfirmEmailAsync(user, code);
if (!result.Succeeded)
{
return View("AccountError", this.GetErrorVm(AccountConstant.Persian.ConfirmSms, ErrorConstant.Persian.CodeWrong));
}
if (!user.PhoneNumberConfirmed)
{
user.PhoneNumberConfirmed = true;
_context.Users.Update(user);
_context.SaveChanges();
}
await _signInManager.SignInAsync(user, true);
await _setUserActivityLog.SetLogAsync(user.Id, AccountConstant.Persian.LoginToProfile);
return RedirectToLocal(string.IsNullOrEmpty(returnUrl) ? AccountConstant.Routes.ReturnUrlManageIndex : returnUrl);
}
redirect action:
[HttpGet]
[ActionDetail(menuCode: MenuConstant.ManageService.Code, name: "پاسخ دادن به تیکت")]
public async Task<IActionResult> TicketAnswer(long id)
{
var baseTicket = await _context.Tickets.Include(t => t.TicketType).Include(t => t.TicketRecords)
.ThenInclude(tr => tr.Person)
.SingleOrDefaultAsync(t => t.Id == id);
if (baseTicket == null)
{
return NotFound();
}
var vm = new ManageVm<TicketAnwserVm>
{
Entity = new TicketAnwserVm
{
QuickResponses = _context.QuickResponses.OrderBy(qr => qr.Title).Select(qr => new QuickResponseVm
{
Id = qr.Id,
Title = qr.Title
}),
Ticket = new TicketDisplayVm(baseTicket.StartDate)
{
Id = baseTicket.Id,
PersonId = baseTicket.PersonId,
State = baseTicket.State,
Subject = baseTicket.Subject,
TicketTypeName = baseTicket.TicketType.Name,
TicketRecords = baseTicket.TicketRecords.Join(_context.Users, tr => tr.PersonId,
u => u.PersonId,
(tr, u) => new TicketRecordVm(tr.Date)
{
Id = tr.Id,
PersonName = tr.Person.Name,
UserId = u.Id,
Content = tr.Content,
IsOwner = tr.IsOwner,
TicketId = tr.TicketId,
Status = tr.IsOwner ? TicketStatus.Out : TicketStatus.In
})
}
}
};
return View(vm);
}

Sqflite Database flutter

i've been trying to create database for signup/login for my app but i failed to do so , my problem is when i try to click register, nothing happen. This is my db code. As for sql i understand it really well because i use to work with mySQL but for flutter and sqflite I still in the process to learn it , really appreciate if you can help me , thank you.
class DbHelper {
static const String DB_Name = 'test.db';
static const String Table_User = 'user';
static const int Version = 1;
static const String _Email = 'email';
static const String _Password = 'password';
static const String _Name = 'name';
static Database? _db;
Future<Database?> get db async {
if (_db != null) {
return _db;
}
_db = await initDb();
return _db;
}
initDb () async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join (documentsDirectory.path, DB_Name);
var db = await openDatabase(path , version: Version, onCreate: _onCreate);
return db;
}
_onCreate (Database db, int intVersion) async {
await db.execute("CREATE TABLE $Table_User ("
"$_Email TEXT ,"
"$_Password TEXT ,"
"$_Name TEXT ,"
" PRIMARY KEY ($_Email)"
" )");
}
Future<int> saveData(UserModel user) async{
var dbClient = await db;
var res = await dbClient!.insert(Table_User, user.toMap());
return res;
}
Future<UserModel?> getLoginUser(String email, String password) async {
var dbClient = await db;
var res = await dbClient!.rawQuery("SELECT * FROM $Table_User WHERE "
"$_Email = '$email' AND "
"$_Password = '$password'");
if (res.length > 0) {
return UserModel.fromMap(res.first);
}
return null;
}
}
and this is my sign up function
signUp() async {
final form = _formKey.currentState;
String uEmail = _Email.text;
String password = _Password.text;
String cpassword = _CPassword.text;
String uname = _Name.text;
if(form != null && !form.validate ()){
if (password != cpassword) {
alertDialog(context, "Password Mismatch");
}
else{
_formKey.currentState?.save();
UserModel uModel = UserModel(uEmail, password, uname);
await dbHelper.insert(uModel).then((userData) {
alertDialog(context, "Success");
Navigator.push(context, MaterialPageRoute(builder: (_) => LoginForm()));
}).catchError((error){
print(error);
alertDialog(context, "Error: Data Save Fail");
});
}
}
}
form.validate() return true when there are no validation errors.
Just change !form.validate() to form.validate()

windows phone 7 app for Salesforce

I want to develop windows phone 7 app for doing crud(Create, Retrieve, Update, Delete) operations from salesforce. I'm successfully done an sample app in windows 8 and 8.1 using developerforce toolkit. But for windows phone 7 i'm not getting even toolkit also. Please any one help me for moving forward in developing windows phone 7 app. Thanks in advance.
Using
developerforce/Force.com-Toolkit-for-NET
You can try the libraries immmediately by installing the following DeveloperForce NuGet packages.
Install-Package DeveloperForce.Force
Install-Package DeveloperForce.Chatter
Username-Password Authentication Flow:-
Simply provide your consumer key, consumer secret, username, and password.
var auth = new AuthenticationClient();
await auth.UsernamePasswordAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURUSERNAME", "YOURPASSWORD");
Web-Server Authentication Flow:-
var url =
Common.FormatAuthUrl(
"https://login.salesforce.com/services/oauth2/authorize", // if using sandbox org then replace login with test
ResponseTypes.Code,
"YOURCONSUMERKEY",
HttpUtility.UrlEncode("YOURCALLBACKURL"));
await auth.WebServerAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURCALLBACKURL", code);
Creating the ForceClient or BulkForceClient:-
var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;
var client = new ForceClient(instanceUrl, accessToken, apiVersion);
var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);
Example:-
var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;
var client = new ForceClient(instanceUrl, accessToken, apiVersion);
var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);
```
### Sample Code
Below you'll find a few examples that show how to use the toolkit.
#### Create
You can create with the following code:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var account = new Account() { Name = "New Account", Description = "New Account Description" };
var id = await client.CreateAsync("Account", account);
```
You can also create with a non-strongly typed object:
```
var client = new ForceClient(_consumerKey, _consumerSecret, _username, _password);
var account = new { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);
```
#### Update
You can update an object:
```
var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);
account.Name = "New Name 2";
var success = await client.UpdateAsync("Account", id, account);
```
#### Delete
You can delete an object:
```
var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.Create("Account", account);
var success = await client.DeleteAsync("Account", id)
```
#### Query
You can query for objects:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var accounts = await client.QueryAsync<Account>("SELECT id, name, description FROM Account");
foreach (var account in accounts.records)
{
Console.WriteLine(account.Name);
}
```
### Bulk Sample Code
Below are some simple examples that show how to use the ```BulkForceClient```
**NOTE:** The following features are currently not supported
* CSV data type requests / responses
* Zipped attachment uploads
* Serial bulk jobs
* Query type bulk jobs
#### Create
You can create multiple records at once with the Bulk client:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var accountsBatch1 = new SObjectList<Account>
{
new Account {Name = "TestStAccount1"},
new Account {Name = "TestStAccount2"}
};
var accountsBatch2 = new SObjectList<Account>
{
new Account {Name = "TestStAccount3"},
new Account {Name = "TestStAccount4"}
};
var accountsBatch3 = new SObjectList<Account>
{
new Account {Name = "TestStAccount5"},
new Account {Name = "TestStAccount6"}
};
var accountsBatchList = new List<SObjectList<Account>>
{
accountsBatch1,
accountsBatch2,
accountsBatch3
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Insert, accountsBatchList);
```
The above code will create 6 accounts in 3 batches. Each batch can hold upto 10,000 records and you can use multiple batches for Insert and all of the operations below.
For more details on the Salesforce Bulk API, see [the documentation](https://resources.docs.salesforce.com/196/latest/en-us/sfdc/pdf/api_asynch.pdf "Salesforce Bulk API Docs").
You can also create objects dynamically using the inbuilt SObject class:
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Name" = "TestDyAccount1"}
},
new SObject
{
{"Name" = "TestDyAccount2"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Insert, accountsBatchList);
```
#### Update
Updating multiple records follows the same pattern as above, just change the ```Bulk.OperationType``` to ```Bulk.OperationType.Update```
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Id" = "YOUR_RECORD_ID"},
{"Name" = "TestDyAccount1Renamed"}
},
new SObject
{
{"Id" = "YOUR_RECORD_ID"},
{"Name" = "TestDyAccount2Renamed"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Update, accountsBatchList);
```
#### Delete
As above, you can delete multiple records with ```Bulk.OperationType.Delete```
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Id" = "YOUR_RECORD_ID"}
},
new SObject
{
{"Id" = "YOUR_RECORD_ID"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Delete, accountsBatchList);

Google calendar - Insert events from azure not working

I have a requirement where I need to update a user's google calendar when an event is inserted in the application's fullcalendar. I am using the peleyal's example for ASP.Net MVC and OAuth for Google API (using GoogleAuthorizationCodeFlow and AuthorizationCodeMvcApp) to handle this. I believe I have set up the credentials right in the google developer console as well.
I am able to create events on the google calendar locally without a problem. But from the azure deployed site I am not able to create the event. There are no exceptions/errors either. Is there anything that needs to be done from azure side to be able to create events and to use Google API?
var finalREsult = System.Threading.Tasks.Task.Run(async () =>
{
try
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetaData()).AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "****"
});
var startDate = patientappointment.DateScheduled.Value.ToUniversalTime();
var endDate = patientappointment.DateScheduled.Value.AddMinutes(patientappointment.AppointmentLengthMinutes).ToUniversalTime();
var myEvent = new Event
{
Summary = string.Format("{0}/{1}/{2} - {3}", patientappointment.CurrentUserName, patientappointment.LocationName, patientappointment.RoomName, patientappointment.Notes),
Location = "Ireland",
Start = new EventDateTime
{
DateTime = new DateTime(startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute, 0),
TimeZone = "(GMT+01:00) Dublin"
},
End = new EventDateTime
{
DateTime = new DateTime(endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute, 0),
TimeZone = "(GMT+01:00) Dublin"
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" }
// Attendees = new List<EventAttendee> { new EventAttendee { Email = "**0#gmail.com" } },
};
EventsResource.InsertRequest request = service.Events.Insert(myEvent, "******#group.calendar.google.com");
request.Execute();
}
}
catch (Exception ex)
{
throw ex;
}
Looking at the requests information, I dont see the request being sent to first autheticate and get the auth code from the deployed site.
internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public ForceOfflineGoogleAuthorizationCodeFlow
(AuthorizationCodeFlow.Initializer initializer)
: base((GoogleAuthorizationCodeFlow.Initializer)initializer) { }
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
{
ResponseType = "code",
ClientId = ClientSecrets.ClientId,
Scope = string.Join(" ", Scopes),
RedirectUri = redirectUri,
AccessType = "offline",
ApprovalPrompt = "force",
State = ""
};
}
};
public class AppFlowMetaData : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow = new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = ConfigurationManager.AppSettings["ClientId"],
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"]
},
Scopes = new[] { CalendarService.Scope.Calendar },
DataStore = null
});
public override string GetUserId(System.Web.Mvc.Controller controller)
{
return "user1";
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}

Worklight Security WorkLightAuthLoginModule

I'm using the WorkLightAuthenticator to validate User login.
But I need to return some parameters like userName, organozationID, among others. What would be the correct way to return this data?
I believe that would be the method createIdentity as exemple down. And to retrieve the data on the client?
/*Worklight Adapter*/
public class LoginModule implements WorkLightAuthLoginModule {
private String USERNAME;
private String PASSWORD;
public void init(Map<String, String> options) throws MissingConfigurationOptionException {
}
#SuppressWarnings("unchecked")
public boolean login(Map<String, Object> authenticationData) {
USERNAME = (String) authenticationData.get("username");
PASSWORD = (String) authenticationData.get("password");
InvocationResult invocationResult = callLoginAdapter(USERNAME, PASSWORD);
JSONObject jsonObject = invocationResult.toJSON();
HashMap<String, String> result = (HashMap<String, String>) jsonObject.get("result");
if(result != null){
return true;
} else {
HashMap<String, String> fault = (HashMap<String, String>) jsonObject.get("Fault");
String detail = fault.get("Detail");
throw new RuntimeException(detail);
}
}
public UserIdentity createIdentity(String loginModule) {
HashMap<String, Object> customAttributes = new HashMap<String, Object>();
customAttributes.put("AuthenticationDate", new Date());
customAttributes.put("userName", userExample);
customAttributes.put("organizationID", 1);
UserIdentity identity = new UserIdentity(loginModule, USERNAME, null, null, customAttributes, PASSWORD);
return identity;
}
public void logout() {
USERNAME = null;
PASSWORD = null;
}
public void abort() {
USERNAME = null;
PASSWORD = null;
}
#Override
public LoginModule clone() throws CloneNotSupportedException {
return (LoginModule) super.clone();
}
public InvocationResult callLoginAdapter(String user, String password){
DataAccessService service = WorklightBundles.getInstance().getDataAccessService();
String parameters = "['"+user+"','"+password+"']";
ProcedureQName procedureQName = new ProcedureQName("LoginAdapter", "getUserByLogin");
return service.invokeProcedure(procedureQName, parameters);
}
}
And AuthenticatorRealmChallengeHandler in client-side
/*AuthenticatorRealmChallengeHandler.js*/
var customAuthenticatorRealmChallengeHandler = WL.Client.createChallengeHandler("AuthenticatorRealm");
customAuthenticatorRealmChallengeHandler.isCustomResponse = function(response) {
console.log("**********************");
console.log(response.responseJSON);
if (!response || !response.responseJSON) {
return false;
}
if (response.responseJSON.authStatus)
return true;
else
return false;
};
customAuthenticatorRealmChallengeHandler.handleChallenge = function(response){
var authStatus = response.responseJSON.authStatus;
if (authStatus == "required"){
if (response.responseJSON.errorMessage){
currentPage.loginFail(response.responseJSON.errorMessage);
}
} else if (authStatus == "complete"){
currentPage.loadMaster();
customAuthenticatorRealmChallengeHandler.submitSuccess();
}
};
customAuthenticatorRealmChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = customAuthenticatorRealmChallengeHandler.isCustomResponse(response);
if (isLoginFormResponse){
customAuthenticatorRealmChallengeHandler.handleChallenge(response);
}
};
$('#loginButton').bind('click', function () {
var reqURL = '/auth_request_url';
var options = {};
options.parameters = {
username : $('#userTextField').val(),
password : $('#passwordTextField').val()
};
options.headers = {};
customAuthenticatorRealmChallengeHandler.submitLoginForm(reqURL, options, customAuthenticatorRealmChallengeHandler.submitLoginFormCallback);
});
var attributes = WL.Client.getUserInfo("AuthenticatorRealm", "attributes");