The ContinuousProcessing parameter is no longer supported.NPGSQL - c#

I just upgraded my npgsql from 2.5.5 to 3.1.1 and i am getting this runtime error.
My DbConnection class
public static string ServerConnectionString()
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
Host = ConfigurationManager.AppSettings["Server"],
Username = ConfigurationManager.AppSettings["UserId"],
Database = "postgres",
Password = ConfigurationManager.AppSettings["Password"],
CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["CommandTimeout"]),
ApplicationName = EverestEnums.ConnectionApplicationName.EverestServerChecker.ToString(),
// MaxPoolSize = 200,
// SyncNotification = true,
KeepAlive = 1,
ConnectionLifeTime = 1,
// MinPoolSize = 1,
Pooling = false
};
return connectionStringBuilder.ConnectionString;
}
Stack Trace
[NotSupportedException: The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
Npgsql.NpgsqlConnectionStringBuilder.set_ConnectionLifeTime(Int32 value) +62
Everest.Net.DatabaseLayer.DBFactory.DbConnection.ServerConnectionString() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\DBConnection.cs:13
Everest.Net.DatabaseLayer.DBFactory.DBOperations.IsServerAvailable() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\DBOperations.cs:216
Everest.Net.DatabaseLayer.DBFactory.ServerConnectivity.IsDbServerAvailable() in E:\Everest_PES\Everest.Net.DatabaseLayer\DBFactory\ServerConnectivity.cs:7
Everest.Net.BusinessLayer.DBFactory.ServerConnectivity.IsDbServerAvailable() in E:\Everest_PES\Everest.Net.BusinessLayer\DBFactory\ServerConnectivity.cs:12
Everest.Net.Web.Global.Application_Start(Object sender, EventArgs e) in E:\Everest_PES\Everest.Net.Web\Global.asax.cs:15
[HttpException (0x80004005): The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +544
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343
[HttpException (0x80004005): The ContinuousProcessing parameter is no longer supported. Please see http://www.npgsql.org/doc/3.1/migration.html]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +112
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +712
As it was working fine before.But there was some issue with connection pooling.And then i upgraded npgsql and this rumtime error.Any Help.

It looks like that exception is thrown when you get or set the ConnectionLifeTime property on the NpgsqlConnectionStringBuilder. The property is obsolete and replaced by the Connection Idle Lifetime property now (see http://www.npgsql.org/doc/migration.html). Try to use this instead:
public static string ServerConnectionString()
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
Host = ConfigurationManager.AppSettings["Server"],
Username = ConfigurationManager.AppSettings["UserId"],
Database = "postgres",
Password = ConfigurationManager.AppSettings["Password"],
CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["CommandTimeout"]),
ApplicationName = EverestEnums.ConnectionApplicationName.EverestServerChecker.ToString(),
// MaxPoolSize = 200,
// SyncNotification = true,
KeepAlive = 1,
ConnectionIdleLifetime = 1,
// MinPoolSize = 1,
Pooling = false
};
return connectionStringBuilder.ConnectionString;
}

Related

Exception while getting sAMAccountName from DirectroryEntry

I am using DirectorySearcher to get AD groups from LDAP. The below code works when I fetch the property "cn" from DirectoryEntry and it throws an exception when "sAMAccountName" is selected. The property does exist as you can see that I search based on sAMAccountName.
Exception is
"Exception Details: System.Runtime.InteropServices.COMException:
Unknown error (0x8000500c)"
[COMException (0x8000500c): Unknown error (0x8000500c)]
System.DirectoryServices.PropertyValueCollection.PopulateList()
+519959 System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry
entry, String propertyName) +119
System.DirectoryServices.PropertyCollection.get_Item(String
propertyName) +162
ASP._Page_app_tools_active_directory_cshtml.SearchADGroups(List1 Fields, String DomainName) in d:\inetpub\wwwroot\app\tools\active_directory.cshtml:371 ASP._Page_app_tools_active_directory_cshtml.Execute() in d:\inetpub\wwwroot\app\tools\active_directory.cshtml:154 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +252 System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable1
executors) +99 System.Web.WebPages.WebPage.ExecutePageHierarchy()
+182 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +107
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase
httpContext) +142
List<ADGroup> Groups = new List<ADGroup>();
using (DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + DomainName))
{
using (DirectorySearcher gSearch = new DirectorySearcher())
{
gSearch.SearchRoot = dEntry;
if(GroupName != "")
{
gSearch.Filter = String.Format("(&(objectClass=group)(samaccountname=*{0}*))", GroupName);
gSearch.SearchScope = SearchScope.Subtree;
gSearch.PropertiesToLoad.Add("sAMAccountName");
SearchResultCollection group_results = gSearch.FindAll();
foreach (SearchResult group_result in group_results)
{
if(group_result != null)
{
DirectoryEntry group_entry = group_result.GetDirectoryEntry();
group_entry.Properties["cn"].Value.ToString()
group_entry.Properties["sAMAccountName"].Value.ToString()
}
}
}
}
}
I expect the value for sAMAccountName

DotNet Activity in Azure Data Factory version 1 (ADF1) failing to load from atlas.microsoft.com

I have the following issue using Azure Data Factory version 1 (ADF1).
I have a DotNetActivity which I use to load info from atlas.microsoft.com.
Since two days ago the activity is failing returning the following message:
Error in Activity: Unknown error in module: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Wen.Logging.Http.HttpClientExtensions.Send(HttpClient client, HttpMethod method, String url, HttpContent data, Dictionary`2 headers)
at Wen.Logging.Http.HttpClientExtensions.Get(HttpClient client, String url, Dictionary`2 headers)
at Delfos.CodeActivities.Activities.AzureMapClient.GetTimeZonesIds() in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMapClient.cs:line 52
at Delfos.CodeActivities.Activities.AzureMaps.LoadTimeZones.AdjustTimeZones(String connectionString) in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMaps\LoadTimeZones.cs:line 39
at Delfos.CodeActivities.Activities.AzureMaps.LoadTimeZones.Execute(IEnumerable`1 linkedServices, IEnumerable`1 datasets, Activity activity, IActivityLogger logger) in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMaps\LoadTimeZones.cs:line 32
at Microsoft.Azure.Management.DataFactories.Runtime.ActivityExecutor.Execute(Object job, String configuration, Action`1 logAction)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.ReflectingActivityWrapper.Execute()
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.JobWrapper.RunJob()
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.Launcher.Main(String[] args)..
This is my Dot Net Activity:
using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.Azure.Management.DataFactories.Runtime;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
namespace Delfos.CodeActivities.Activities.AzureMaps
{
public class LoadTimeZones : IDotNetActivity
{
private readonly DateTime startDate = new DateTime(2012, 1, 1);
public IDictionary<string, string> Execute(IEnumerable<LinkedService> linkedServices,
IEnumerable<Dataset> datasets,
Activity activity,
IActivityLogger logger)
{
var odsStagingSqlInputDataset = datasets
.Where(dataset => dataset.Name == "dim-date-staging")
.First();
var odsStagingSqlInputLinkedService = linkedServices.Where(
linkedService =>
linkedService.Name ==
odsStagingSqlInputDataset.Properties.LinkedServiceName).First().Properties.TypeProperties
as AzureSqlDatabaseLinkedService;
AdjustTimeZones(odsStagingSqlInputLinkedService.ConnectionString);
return new Dictionary<string, string>();
}
public void AdjustTimeZones(string connectionString)
{
var transitionsYears = DateTime.Now.AddYears(1).Subtract(startDate).Days / 365;
var timeZonesIds = AzureMapClient.GetTimeZonesIds();
var usTimeZonesIds = timeZonesIds.Where(zone => zone.Id.StartsWith("US/") && zone.Id != "US/Arizona");
var timeZoneTable = CreateTimeZoneDataTable();
var marked = new Dictionary<string, bool>();
foreach (var zoneId in usTimeZonesIds)
{
var timeZone = AzureMapClient.GetTimeZone(zoneId.Id, startDate, transitionsYears);
if (marked.ContainsKey(timeZone.Names.Generic))
continue;
marked.Add(timeZone.Names.Generic, true);
timeZone.TimeTransitions.ForEach(t => timeZoneTable.Rows.Add(
timeZone.Names.Generic,
t.UtcStart,
t.UtcEnd,
t.StandardOffset.Add(t.DaylightSavings).Hours,
t.DaylightSavings.Hours > 0 ? true : false
));
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
Util.ExecuteUpsertStoredProcedure("ods_ui.LoadTimeZones", "TimeZones", timeZoneTable, connection);
}
}
private DataTable CreateTimeZoneDataTable()
{
var table = new DataTable();
table.Columns.Add("TimeZone", typeof(string));
table.Columns.Add("StartDate", typeof(DateTime));
table.Columns.Add("EndDate", typeof(DateTime));
table.Columns.Add("UTCdifferenceHours", typeof(int));
table.Columns.Add("IsDaylightSavings", typeof(bool));
return table;
}
}
}
and this is the class I use as helper:
using Delfos.CodeActivities.Models.AzureMaps;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using Wen.Logging.Http;
namespace Delfos.CodeActivities.Activities
{
public static class AzureMapClient
{
private const string atlasUrl = "https://atlas.microsoft.com";
private const string subscriptionKey = "<replaced_actual_value>";
public static Models.AzureMaps.TimeZone GetTimeZone(string zone,
DateTime transitionsFrom,
int transitionsYears = 1,
string options = "all")
{
var baseUrl = new Uri(atlasUrl);
var endpoint = $#"timezone/byId/json?subscription-key={subscriptionKey}&api-version=1.0&options={options}&query={zone}&transitionsFrom={transitionsFrom.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")}&transitionsYears={transitionsYears}";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
var response = client.Get(baseUrl.AbsoluteUri + endpoint);
if (!response.IsSuccessStatusCode)
return new Models.AzureMaps.TimeZone();
var respContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var timeZonesContent = JObject.Parse(respContent).SelectToken("TimeZones").ToString();
var timeZones = JsonConvert.DeserializeObject<List<Models.AzureMaps.TimeZone>>(timeZonesContent);
return timeZones.FirstOrDefault();
}
}
public static List<TimeZoneId> GetTimeZonesIds()
{
var baseUrl = new Uri(atlasUrl);
var endpoint = $"timezone/enumIana/json?subscription-key={subscriptionKey}&api-version=1.0";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
var response = client.Get(baseUrl.AbsoluteUri + endpoint);
if (!response.IsSuccessStatusCode)
return new List<TimeZoneId>();
var respContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var timeZonesIds = JsonConvert.DeserializeObject<List<TimeZoneId>>(respContent);
return timeZonesIds;
//return new List<TimeZoneId>();
}
}
}
}
this line:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
was my last try, since I found that enforcing SecurityProtocol to TLS1.2 allowed me to run the whole code from my local project, but once in the cloud failures continued.

entity type ApplicationUser is not part of the model for the current context

I have an web application in Asp.net with Entity Framework 6 and database first. I'm having issue when it come for the user to connect.Here's my code:
Web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;User Id=XXX;Password=XXXX" providerName="System.Data.SqlClient" />
<add name="Cliniciel_WebRV_MasterEntities" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Master.csdl|res://*/Models.Entities.Cliniciel_WebRV_Master.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Master.msl;provider=System.Data.SqlClient;provider connection string="data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;user id=XXX;password=XXXX;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="Cliniciel_WebRV_Entities" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Entities.csdl|res://*/Models.Entities.Cliniciel_WebRV_Entities.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Entities.msl;provider=System.Data.SqlClient;provider connection string="data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_DEV;user id=XXX;password=XXXX;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="Cliniciel_WebRV_Oauth" connectionString="metadata=res://*/Models.Entities.Cliniciel_WebRV_Oauth.csdl|res://*/Models.Entities.Cliniciel_WebRV_Oauth.ssdl|res://*/Models.Entities.Cliniciel_WebRV_Oauth.msl;provider=System.Data.SqlClient;provider connection string="data source=MyServer\MyDataBase;initial catalog=Cliniciel_WebRV_Master;user id=XXX;password=XXXX;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Here I use the connection string "Cliniciel_WebRV_Oauth" for my identity authentification.
I configure my oauthToken on startup
Startup.cs
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
//// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
//app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
#if DEBUG
AllowInsecureHttp = true,
#endif
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat("http://localhost:55555/")
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "http://localhost:55555/";
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
ApplicationDBContext.cs
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
using WebRV.Models.Entities;
namespace WebRV.Infrastructure
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> //DOIT CREER APPLICATION USER.
{
public ApplicationDbContext()
: base("Cliniciel_WebRV_Oauth", throwIfV1Schema: false)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
[WebMethod(EnableSession = true)]
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
CustomOAuthProvider.cs
using System;
using System.Linq;
using WebRV.Infrastructure;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;
using System.Web.Mvc;
using WebRV.Models.Entities;
using System.Net;
using System.Web.Http;
namespace WebRV.Providers
{
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
[ValidateAntiForgeryToken]
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
}
else
{
//if (!user.EmailConfirmed)
//{
// context.SetError("invalid_grant", "User did not confirm email.");
// return;
//}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
}
}
}
Here's the error i got:
The ApplicationUser entity type is not part of the model for the
current context.
here's the trace:
Ligne 32 : var userManager =
context.OwinContext.GetUserManager(); Ligne 33
: Ligne 34 : ApplicationUser user = await
userManager.FindAsync(context.UserName, context.Password); Ligne 35 :
Ligne 36 : if (user == null)
Fichier source : c:\Users\aboucher\Desktop\WebRV-2016-05-12 -
Copie\Cliniciel_WebRV\WebRV\WebRV\Providers\CustomOAuthProvider.cs
Ligne : 34
Trace de la pile:
[InvalidOperationException: Le type d'entité ApplicationUser ne fait
pas partie du modèle pour le contexte actuel.]
System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type
entityType) +4479799
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType) +37
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
+16 System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
+39 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
source, Expression1 predicate, CancellationToken cancellationToken)
+154 System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1
source, Expression1 predicate) +163
Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>d__6c.MoveNext()
+807 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
+28 Microsoft.AspNet.Identity.CultureAwaiter1.GetResult() +123 Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +601
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
+28 WebRV.Providers.d__0.MoveNext() in c:\Users\aboucher\Desktop\WebRV-2016-05-12 -
Copie\Cliniciel_WebRV\WebRV\WebRV\Providers\CustomOAuthProvider.cs:34
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.Owin.Security.OAuth.d__3f.MoveNext()
+863 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
+28 Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>d__22.MoveNext()
+2336 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.Owin.Security.OAuth.<InvokeAsync>d__0.MoveNext() +1733 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
+28 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +664 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext()
+287 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
+26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()
+272 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult
ar) +150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult
ar) +42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+380 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
where is your ApplicationUserManager Method
you need to configure Application UserManager Like this by passing DbContext
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
most important is to write this line(First Line in Create method)
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>()));

UserPrincipal with context that uses SSL

I have a PrincipalContext that uses SSL. This works fine when using a method like Context.ValidateCredentials(). But when I need to find a user using UserPrincipal.FindByIdentity() I get the following error:
System.Runtime.InteropServices.COMException: The server is unwilling to process the request.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_SchemaEntry()
at System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry de)
at System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry ctxBase, Boolean ownCtxBase, String username, String password, ContextOptions options)
at System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry)
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
--- End of inner exception stack trace ---
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
My method:
public List<string> GetUserInfo(string user) {
var list = new List<string>();
using (var context = new PrincipalContext(ContextType.Domain, "xxxx.xxxx.xxxx:636", "DC=xxxx,DC=xxxx,DC=xxxx", ContextOptions.SimpleBind | ContextOptions.Sealing | ContextOptions.SecureSocketLayer)) {
var uP = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user);
//Do stuff with uP
return list;
}
But this is working fine:
public bool ValidateCredentials(string username, string password) {
using (var context = new PrincipalContext(ContextType.Domain, "xxxx.xxxx.xxxx:636", "DC=xxxx,DC=xxxx,DC=xxxx", ContextOptions.SimpleBind | ContextOptions.Sealing | ContextOptions.SecureSocketLayer)) {
return context.ValidateCredentials(username, password);
}
}
How come I cant work with UserPrincipal using the Context with SSL? If I remove SSL it works fine..
I changed my ContextOptions to Negotiate and SSL. Then it worked
Unfortunately there are not enough code examples that show how to configure PrincipalContext or DirectoryEntry to use LDAPS (SSL Active Directory). I have found these solutions for this issue:
Configure PrincipalContext to use LDAPS:
var path = "test.domainName.local:636";
ContextOptions options = ContextOptions.Negotiate | ContextOptions.SecureSocketLayer;
using (var context = new PrincipalContext(ContextType.Domain, path, "DC=xyz,DC=local", options))
{
pr("Name: " + context.Name);
pr("ConnectedServer: " + context.ConnectedServer);
pr("Container: " + context.Container);
pr("UserName: " + context.UserName);
}
Configure DirectoryEntry to use LDAPS:
string path = "LDAP://test.domainName.local:636";
var dic = new DirectoryEntry(path);
pr("Name: " + dic.Name);
pr("Path: " + dic.Path);
pr("AuthenticationType: " + dic.AuthenticationType);
pr("SchemaClassName: " + dic.SchemaClassName);
pr("Username: " + dic.Username);

Google Calendar API Error 405

I was trying out the Google Calendar API from this sample code but I am getting the following error:
Execution of authentication request returned unexpected result: 405
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Google.GData.Client.GDataRequestException: Execution of authentication request returned unexpected result: 405
Stack Trace:
Stack Trace:
[GDataRequestException: Execution of authentication request returned
unexpected result: 405]
_2.BusinessLogicLayer.LogicClasses.LeaveLogic.AddToGoogleCalendar() in C:\Users\Samsung\Desktop\Development\Ticketing
system\2.BusinessLogicLayer\LogicClasses\LeaveLogic.cs:375
_1.PresentationLayer.WebPages.LeaveRequest.tstbtn_Click(Object sender, EventArgs e) in C:\Users\Samsung\Desktop\Development\Ticketing
system\1.PresentationLayer\WebPages\LeaveRequest.aspx.cs:403
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Code:
string sGoogleUserName = "******#gmail.com";
string sGooglePassword = "*****";
Uri oCalendarUri = new Uri("http://www.google.com/calendar/feeds/" + sGoogleUserName + "/private/full");
//Initialize Calendar Service
CalendarService oCalendarService = new CalendarService("CalendarSampleApp");
oCalendarService.setUserCredentials(sGoogleUserName, sGooglePassword);
//Use Proxy
GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
oWebProxy.Credentials = CredentialCache.DefaultCredentials;
oWebProxy.UseDefaultCredentials = true;
oRequestFactory.Proxy = oWebProxy;
//Set Event Entry
EventEntry oEventEntry = new EventEntry();
oEventEntry.Title.Text = "Test Calendar Entry From .Net";
oEventEntry.Content.Content = "Hurrah!!! I posted my first Google calendar event through .Net";
//Set Event Location
Where oEventLocation = new Where();
oEventLocation.ValueString = "New Zealand";
oEventEntry.Locations.Add(oEventLocation);
//Set Event Time
When oEventTime = new When(new DateTime(2011, 5, 31, 9, 0, 0), new DateTime(2011, 5, 31, 9, 0, 0).AddHours(1));
oEventEntry.Times.Add(oEventTime);
//Set Additional Properties
ExtendedProperty oExtendedProperty = new ExtendedProperty();
oExtendedProperty.Name = "SynchronizationID";
oExtendedProperty.Value = Guid.NewGuid().ToString();
oEventEntry.ExtensionElements.Add(oExtendedProperty);
// CalendarService oCalendarService = GAuthenticate();
//Prevents This Error
//{"The remote server returned an error: (417) Expectation failed."}
System.Net.ServicePointManager.Expect100Continue = false;
//Save Event
oCalendarService.Insert(oCalendarUri, oEventEntry);
Comment the Proxy part it should work:
////Use Proxy
//GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
//WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
//oWebProxy.Credentials = CredentialCache.DefaultCredentials; //oWebProxy.UseDefaultCredentials = true;
//oRequestFactory.Proxy = oWebProxy;

Categories

Resources