I want to be able to change an existing connection string in web.config with the user input so that only people who have SQL Server logins can access their corresponding database.
This is the code I've tried but once I logged in it says the user id is empty
Session["UserID"] = obj.UserID.ToString();
Session["Gebruikersnaam"] = obj.Gebruikersnaam.ToString();
var database = db.UserDatabases
.Where(a => a.DatabaseID.Equals(obj.DatabaseID))
.FirstOrDefault();
string DatabaseCon = database.DatabaseNaam.ToString();
string username = obj.Gebruikersnaam.ToString();
string password = obj.Wachtwoord.ToString();
HoefSmidDbEntities HoefSmidDb = new HoefSmidDbEntities();
var entityConStringBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["HoefSmidDbEntities"].ConnectionString);
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(entityConStringBuilder.ProviderConnectionString);
connectionStringBuilder.InitialCatalog = DatabaseCon;
connectionStringBuilder.UserID = username;
connectionStringBuilder.Password = password;
HoefSmidDb.Database.Connection.ConnectionString = connectionStringBuilder.ConnectionString;
return RedirectToAction("../Home/Index");
Related
How can I create a Cognito user with the account status confirmed using c#? After a user is created the account status displays FORCE_CHANGE_PASSWORD. Another thing is I need to create user without email address.
AmazonCognitoIdentityProviderClient cognitoProvider =
new AmazonCognitoIdentityProviderClient(region);
string userName = "user";
string tempPassword = "Temp#3434";
string newPassword = "RealPass#2019";
AdminCreateUserRequest adminUserCreateRequest = new AdminCreateUserRequest()
{
UserPoolId = poolId,
Username = userName,
TemporaryPassword = tempPassword
};
AdminCreateUserResponse signUpResponse = await cognitoProvider.AdminCreateUserAsync(adminUserCreateRequest);
Admin InitiateRequest
Dictionary<string, string> initialParams = new Dictionary<string, string>();
initialParams.Add("USERNAME", userName);
initialParams.Add("PASSWORD", tempPassword);
AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest()
{
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
AuthParameters = initialParams,
ClientId = appClientId_tenantApi,
UserPoolId = poolId
};
AdminInitiateAuthResponse resInitAuth = await cognitoProvider.AdminInitiateAuthAsync(initialRequest);
InitiateAuthRresponse has email as a required attribute.
{[requiredAttributes, ["userAttributes.email"]]}
But the documentation doesn't say so.
For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), PASSWORD (required), DEVICE_KEY
Admin Respond to challenge
var authParameters = new Dictionary<string, string>();
authParameters.Add("USERNAME", userName);
authParameters.Add("NEW_PASSWORD", newPassword);
AdminRespondToAuthChallengeRequest adminAuthRequest = new AdminRespondToAuthChallengeRequest()
{
UserPoolId = poolId,
ClientId = appClientId_tenantApi,
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
ChallengeResponses = authParameters,
Session = session
};
cognitoProvider.AdminRespondToAuthChallengeAsync(adminAuthRequest);
I am thinking I may missed some user settings in Cognito to avoid email. Any one have similar experience ? or is this not possible to create user without email ?
During the creation of the user pool, under general settings;attributes as in the photocognito creation on aws one is required to choose the attributes that must be present, i believe in your case the email was selected by default hence the challenge request response you got.
The admin create user request requires the client to confirm the email for purposes of verification that the user owns the email.
A hack for the same would be to allow users to sign themselves up on your cognito configuration, then sign someone up then follow with a username and password, then proceed to confirm them as an admin
var signup = await cognitoClient.SignUpAsync(new SignUpRequest
{
Username = person.Username,
ClientId = cognitoOptions.ClientId,
Password = person.IdNumber,
});
var confirm = await cognitoClient.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest
{
Username = person.Username,
UserPoolId = cognitoOptions.UserPoolId
});
In case if anyone still looking for answer
Initalize Provider.
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient("*************", "************", Amazon.RegionEndpoint.USWest);
Create user
AdminCreateUserResponse adminCreateUserResponse = await provider.AdminCreateUserAsync(new AdminCreateUserRequest
{
Username = "TestUser",
TemporaryPassword = "TempPassword#1",
UserPoolId = "us-west-**********"
});
Authenticate user
CognitoUserPool userPool = new CognitoUserPool("us-west-***", "***", provider);
CognitoUser user = new CognitoUser("TestUser", "******", userPool, provider, "**********");
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = "TempPassword#1"
};
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
Vaidate user authentication result and get the user AccessToken
if (authResponse.AuthenticationResult == null)
{
if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
{
//Console.WriteLine("Enter your desired new password:");
string newPassword = "NewPWD#1";// Console.ReadLine();
Dictionary<string, string> att = new Dictionary<string, string>();
att.Add("userAttributes.email", "testemail#xyz.com");
user.Attributes.Add("preferred_username", "TestUser1");
And update the new password using Accesstoken ( post update the User status will be confirmed)
authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
{
SessionID = authResponse.SessionID,
NewPassword = newPassword,
},att);
accessToken = authResponse.AuthenticationResult.AccessToken;
}
I'm writing a method that set all of database connection string with it.The method has some parameters like connection string and cookie domain (for single sign on state) , ...
I can get Membership and role Information with specified connection string that send as a parameter.
//membership
System.Web.Security.SqlMembershipProvider mp = new System.Web.Security.SqlMembershipProvider();
System.Collections.Specialized.NameValueCollection config_Membership = new System.Collections.Specialized.NameValueCollection();
config_Membership.Add("connectionString", connectionstring);
config_Membership.Add("applicationName", "/");
mp.Initialize("SQL_test_Membership", config_Membership);
var u = mp.GetUser(username, false);
int TotalRecords = 0;
var p = mp.GetAllUsers(0, 1, out TotalRecords);
//login
bool valid = mp.ValidateUser(username, password);
System.Web.Security.SqlRoleProvider rp = new System.Web.Security.SqlRoleProvider();
System.Collections.Specialized.NameValueCollection config_Role = new System.Collections.Specialized.NameValueCollection();
config_Role.Add("connectionString", connectionstring);
config_Role.Add("applicationName", "/");
rp.Initialize("SQL_test_Role", config_Role);
var roles = rp.GetRolesForUser(username);
I want to get ProfileBase Information like above code
https://technet.microsoft.com/nl-nl/library/system.web.profile.profilebase.initialize(v=vs.85).aspx
and I found below code:
System.Web.Profile.ProfileBase pro = new System.Web.Profile.ProfileBase();
System.Collections.Specialized.NameValueCollection config_profile = new System.Collections.Specialized.NameValueCollection();
config_profile.Add("connectionString", connectionstring);
config_profile.Add("applicationName", "/");
pro.Initialize(?????)
but I dont know how to send parameter to pro.Initialize(), can any one help me? Thanks.
My problem solved. My code was changed :
//login
bool valid = mp.ValidateUser(username, password);
if (valid)
{
System.Web.Profile.ProfileBase pro = new System.Web.Profile.ProfileBase();
System.Collections.Specialized.NameValueCollection config_profile = new System.Collections.Specialized.NameValueCollection();
config_profile.Add("connectionString", connectionstring);
config_profile.Add("applicationName", "/");
pro.Initialize(username, true);
string Name = pro.GetPropertyValue("Name").ToString();
string Family = pro.GetPropertyValue("Family").ToString();
string phone = pro.GetPropertyValue("Phone").ToString();
string address = pro.GetPropertyValue("Address").ToString();
}
I recently deployed Parse Server to Amazon which is working fine when I connect and create users from iOS but doesn't work when I try to connect from Unity3D and there are no logs aswell. Is there any specific setting or something for Unity?? What am I missing? Below is the code for both platforms;
Unity Code (Not working)
// Initialization
string serverUrl = "http://myserverip.amazonaws.com:80/parse/";
ParseClient.Initialize(new ParseClient.Configuration {ApplicationId = "MYAPPID", WindowsKey = "MYCLIENTKEY", Server = serverUrl});
// User Creation
ParseUser user = new ParseUser ();
user.Username = "myname";
user.Password = "mypass";
user.SignUpAsync ().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled){
Debug.Log("Faliled" + t.IsFaulted);
}
else{
Debug.Log("Success");
var userId = ParseUser.CurrentUser.ObjectId;
print (userId);
}
});
iOS Code (working)
// Initialization
[Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> _Nonnull configuration) {
configuration.applicationId = #"MYAPPID";
configuration.clientKey = #"MYCLIENTKEY";
configuration.server = #"http://myinstanceIP.amazonaws.com:80/parse";
configuration.localDatastoreEnabled = YES;
}]];
// User Creation
PFUser *user = [PFUser user];
user.username = #"my name2";
user.password = #"my pass";
user.email = #"email2#example.com";
[user signUp];
You have to set appID and client key in ParseInitializeBehaviour before calling ParseClient.Initialize. Which is pretty weird because ParseClient.Initialize also takes appID and client key but I got it working this way.
Also add "/" at the end of your server url.
ParseInitializeBehaviour _script = new GameObject("ParseInitializeBehaviour").AddComponent<ParseInitializeBehaviour> ();
_script.applicationID = "APPID";
_script.dotnetKey = "CLIENTKEY";
ParseClient.Initialize (new ParseClient.Configuration ()
{
WindowsKey = "APPID",
ApplicationId = "CLIENTKEY",
Server = serverUrl
});
Everything else i.e signup, signin etc. works normally after this.
I have two sub-sites in my sharepoint site,SampleSite1 and SampleSite2 under Parentsite called MainSite.
http://xyz.sharepoint.com/sites/MainSite/ - SiteUrl
http://xyz.sharepoint.com/sites/MainSite/SampleSite1 - Subsite1's Url
http://xyz.sharepoint.com/sites/MainSite/SampleSite2 - Subsite2's Url
Each of the Sites have two groups superUser and NormalUser respectively.
The credential uses SiteUrl of MainSite.
SecureString password = new SecureString();
string pwd = "Pass123";
string UserName = "abc#xyz.com";
password = convertToSecureString(pwd);
ClientContext clientContext = new ClientContext("http://xyz.sharepoint.com/sites/MainSite/");
clientContext.Credentials = new SharePointOnlineCredentials(UserName, password);
Incase of adding user to subsite's groups like NormalUser,Can we use the same sharepoint context with above siteUrl to access and perform operations(add/remove user) in groups present under subsites?
If Yes,how can we do it?I already have built code to add or remove user from a sharepoint site group based on some requirement.
public void AddUserToDMSite(string useremail, string securityGroupName)
{
GroupCollection collGroup = SPContext.Web.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
For subsites you can proceed as follows:
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
AddUserToDMSite(useremail, securityGroupName, orWebSite)
}
and change AddUserToDMSite to work with either sites and subsites as:
public void AddUserToDMSite(string useremail, string securityGroupName, Web aWeb)
{
GroupCollection collGroup = aWeb.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0