An Application Connect with Multiple database and set Membership cookies - c#

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();
}

Related

Edit a web.config connection string in a controller (ASP.NET MVC)

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");

ONVIF api capture image in C#

I have an ONVIF ip camera.
I want to to capture an image from the camera so that I can process that image and save it to the file system.
I found out that there is an onvif api which provides a method GetSnapshotUri which should provide me with an image snapshot:
http://www.onvif.org/onvif/ver10/media/wsdl/media.wsdl
I managed to import this api in visual studio by adding a service reference to it:
How do I construct a client to call GetSnapshotUri from this service?
So, after lots of searching I managed to capture an image from the camera.
The first Problem was that I have used "Add Service Reference->Advanced->Add Web reference" instead of typing the service address directly in the "Add Service Reference" box.
Here, I added the address: http://www.onvif.org/onvif/ver10/media/wsdl/media.wsdl
Then I could use the MediaClient class, correctly pointed out by pepOS in a comment, and the final code looks like:
var messageElement = new TextMessageEncodingBindingElement();
messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();
httpBinding.AuthenticationScheme = AuthenticationSchemes.Basic;
CustomBinding bind = new CustomBinding(messageElement, httpBinding);
EndpointAddress mediaAddress = new EndpointAddress("http://192.168.1.168:10001/onvif/Media");
MediaClient mediaClient = new MediaClient(bind, mediaAddress);
mediaClient.ClientCredentials.UserName.UserName = "admin";
mediaClient.ClientCredentials.UserName.Password = "admin";
Profile[] profiles = mediaClient.GetProfiles();
string profileToken = profiles[1].token;
MediaUri mediaUri = mediaClient.GetSnapshotUri(profileToken);
The uri of the image could then be fount at the MediaUri.Uriaddress
The GetSnapshotUri returns a uri for downloading an image using HTTP get.
So in theory you just need to call this function, and use the returned uri in the function shown in this Stackoverflow article:
https://stackoverflow.com/a/3615831/4815603
I am using onvif device manager dll here. To implement this method camera's IP, username and password must be known.
// Onvif ODM
using onvif.services;
using odm.core;
using onvif.utils;
using utils;
public string GetSnapshotUrl()
{
try
{
string camera_ip = "http://" + camIp + "/onvif/device_service";
Uri Camuri = new Uri(camera_ip);
NvtSessionFactory sessionFactory = new NvtSessionFactory(account);
INvtSession session = sessionFactory.CreateSession(Camuri);
Profile[] Profiles = session.GetProfiles().RunSynchronously();
var snapshotlink = session.GetSnapshotUri(Profiles[0].token).RunSynchronously(); // taking snapshot on the first profile of the camera
return snapshotlink.uri;
}
catch (Exception ex)
{
return null;
}
}
For me basic authentication didn't work. The following code works for me and downloads the image:
string username = "username";
string password = "password";
string cameraIP = "";
var messageElement = new TextMessageEncodingBindingElement()
{
MessageVersion = MessageVersion.CreateVersion(
EnvelopeVersion.Soap12, AddressingVersion.None)
};
HttpTransportBindingElement httpBinding = new HttpTransportBindingElement()
{
AuthenticationScheme = AuthenticationSchemes.Digest
};
CustomBinding bind = new CustomBinding(messageElement, httpBinding);
MediaClient mediaClient = new MediaClient(bind, new EndpointAddress($"http://{cameraIP}/onvif/device_service"));
mediaClient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
mediaClient.ClientCredentials.HttpDigest.ClientCredential.UserName = username;
mediaClient.ClientCredentials.HttpDigest.ClientCredential.Password = password;
Profile[] profiles = mediaClient.GetProfiles();
string profileToken = profiles[0].token;
MediaUri mediaUri = mediaClient.GetSnapshotUri(profileToken);
WebClient webCl = new WebClient()
{
Credentials = new NetworkCredential(username, password)
};
webCl.DownloadFile(mediaUri.Uri, #"D:\test.jpg");

Code connect to Google Analytics API with C# error

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

WebConsumer.ProcessUserAuthorization returns null

I use DotNetOpenAuth.
So.. I am getting looking good response which has state Authenticated.
That is fine.
Now I want to get user profile info but always getting NULL.
Here is the code.
private ServiceProviderDescription GetServiceDescription()
{
string ValidateTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateTokenEndPointUrl"];
string ValidateAuthorizationHeaderEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateAuthorizationHeaderEndPointUrl"];
string AccessTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
bool UseVersion10A = Convert.ToBoolean(ConfigurationManager.AppSettings["identityOAuthUseVersion10a"]);
string RequestTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestTokenURL"];
string UserAuthStr = ConfigurationManager.AppSettings["identityOAuthAuthorizeUserURL"];
string AccessTokenStr = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
string InvalidateTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestInvalidateTokenURL"];
return new ServiceProviderDescription
{
AccessTokenEndpoint = new MessageReceivingEndpoint(AccessTokenStr, HttpDeliveryMethods.PostRequest),
RequestTokenEndpoint = new MessageReceivingEndpoint(RequestTokenStr, HttpDeliveryMethods.PostRequest),
UserAuthorizationEndpoint = new MessageReceivingEndpoint(UserAuthStr, HttpDeliveryMethods.PostRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
ProtocolVersion = DotNetOpenAuth.OAuth.ProtocolVersion.V10a
};
}
void GetUserProfile()
{
var tokenManager = TokenManagerFactory.GetTokenManager(TokenManagerType.InMemoryTokenManager);
tokenManager.ConsumerKey = ConfigurationManager.AppSettings["identityOAuthConsumerKey"];
tokenManager.ConsumerSecret = ConfigurationManager.AppSettings["identityOAuthConsumerSecret"];
var serviceDescription = GetServiceDescription();
var consumer = new WebConsumer(serviceDescription, tokenManager);
var result = consumer.ProcessUserAuthorization(response);
if (result != null) // It is always null
{
}
Well I checked 10 times and I am pretty sure that all URLs to create ServiceProviderDescription are correct.
Any clue?
Well
finally check your web.config app keys
add key="identityOAuthConsumerKey" value="put here correct data!!!"
add key="identityOAuthConsumerSecret" value="put here correct data!!!"
and if you use hosts file you have to put correct sitename as well
127.0.0.1 site1.host1.com

.net google analytics v3.0 and oauth 2.0

Here is what im trying to do , i got a webpage with signin page with cresedentials from our database , then once is logged in it should redirect you to main page where you should see the data in charts.
The problem is I used gdata v2.4 but every time i want make a request i have to set the cresedentials again, then v3.0 with oauth 2.0 it said we don't need to this anymore by access token.
I managed to make it work but the problem is if the user been asked to login with gmail account and the email and password doesnt match the profile id of the request it gives the 403 error (forbidden access) this is the code . i tried to use service account no chance , any one knows whats the problem?
log4net.Config.XmlConfigurator.Configure();
//string Scope = AnalyticsService.Scopes.Analytics.ToString().ToLower();
//string scopeUrl = "https://www.google.com/analytics/feeds/" + Scope;
string Scope = "https://www.google.com/analytics/feeds/";
const string ServiceAccountId = "xxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxx#developer.gserviceaccount.com";
string key = string.Empty;
foreach (string keyname in Directory.GetFiles(Server.MapPath("/"), "*.p12", SearchOption.AllDirectories))
{
key = keyname;
}
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(key, "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = Scope,
ServiceAccountId = ServiceAccountUser//,ServiceAccountUser = ServiceAccountUser
};
WebServerClient myWebServerClient = new WebServerClient(GoogleAuthenticationServer.Description);
myWebServerClient.ClientIdentifier = this.ClientID;
myWebServerClient.ClientSecret = this.ClientSecret;
OAuth2Authenticator<WebServerClient> authenticator = new OAuth2Authenticator<WebServerClient>(myWebServerClient, GetAuthorization);
AnalyticsService service = new AnalyticsService(authenticator);
string profileId = Session["_ProfileID"].ToString() ;
string startDate = StartDate;
string endDate = EndDate;
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
request.StartIndex = 1;
request.MaxResults = 500;
GaData data = request.Fetch();
return data;
dont bother anymore , i got it right with offline access . Thanks for showing the SUPPORT

Categories