Fluent Configuration Exception - c#

if (_cacheSessionFactory == null)
{
Configuration config = null;
_cacheSessionFactory = ReadOrBuildConfiguration().ExposeConfiguration(
cfg =>
{
SetSessionContext(cfg);
cfg.SetListener(ListenerType.Flush, new PostFlushFixEventListener());
ConfigureValidator(cfg);
if (EnversConfiguration != null)
{
cfg.SetEnversProperty(ConfigurationKey.StoreDataAtDelete, true);
cfg.IntegrateWithEnvers(EnversConfiguration);
}
}).ExposeConfiguration(cfg => { config = cfg; }).BuildSessionFactory();
using (_cacheSessionFactory.OpenSession())
{
BuildSchema(config);
}
}
UPDATED stack trace
FluentNHibernate.Cfg.FluentConfigurationException was unhandled by user code
HResult=-2146233088
Message=An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
* Database was not configured through Database method.
* No mappings were configured through the Mappings method.
Source=FluentNHibernate
StackTrace:
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
at NhibDataAccess.NhibernateSetup.CreateSessionFactory() in d:\Jorell\PROJECTS\NhibDataAccess\NhibernateSetup.cs:line 105
at NhibDataAccess.NhibernateSetup.get_SessionFactory() in d:\Jorell\PROJECTS\NhibDataAccess\NhibernateSetup.cs:line 67
at NhibDataAccess.UnitOfWork.LongRunningUnitOfWork.get_SessionFactory() in d:\Jorell\PROJECTS\NhibDataAccess\UnitOfWork\LongRunningUnitOfWork.cs:line 63
at Web.Global.Application_EndRequest(Object sender, EventArgs e) in d:\Jorell\PROJECTS\Web\Global.asax.cs:line 54
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
InnerException: System.NullReferenceException
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=NHibernate.Validator
StackTrace:
at NHibernate.Validator.Engine.SystemTypeExtensions.ShouldNeedValidation(Type clazz)
at NHibernate.Validator.Engine.ValidatorEngine.GetClassValidator(Type entityType)
at NHibernate.Validator.Engine.ValidatorEngine.AddValidator(Type entityType, IValidatableSubElementsInspector inspector)
at NHibernate.Validator.Event.ValidatePreInsertEventListener.Initialize(Configuration cfg)
at NHibernate.Event.EventListeners.InitializeListeners(Configuration cfg, Object[] list)
at NHibernate.Event.EventListeners.InitializeListeners(Configuration cfg)
at NHibernate.Cfg.Configuration.GetInitializedEventListeners()
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
InnerException:
when i try to add any Audit<> in EnversConfiguration this exception is thrown. i have a similar application and this doesn't happen. any clue or information as to why this problem occurs?

the problem in my code was already addressed before i even knew it.
please visit the site for more information
https://nhibernate.jira.com/browse/NHV-117

Related

Azure.Search.Documents throws error while adding CORS to the Index (Programmatically)

I'm using azure cognitive search to index my data. I've upgraded to the latest Azure.Search.Documents (version 11) package. Previously I was using Microsoft.Azure.Search
When I added CORS programmatically (Line No 5) I get the below error.
Console.WriteLine("Creating Index...");
FieldBuilder fieldBuilder = new FieldBuilder();
var searchFields = fieldBuilder.Build(typeof(Hotel));
var searchIndex = new SearchIndex("hotels", searchFields);
searchIndex.CorsOptions = new CorsOptions(new List<string> { "*" });
Error:
System.InvalidOperationException
HResult=0x80131509
Message=The requested operation requires an element of type 'Number', but the target element has type
'Null'.
Source=System.Text.Json
StackTrace:
at System.Text.Json.JsonDocument.TryGetValue(Int32 index, Int64& value)
at System.Text.Json.JsonElement.GetInt64()
at Azure.Search.Documents.Indexes.Models.CorsOptions.DeserializeCorsOptions(JsonElement element)
at Azure.Search.Documents.Indexes.Models.SearchIndex.DeserializeSearchIndex(JsonElement element)
at Azure.Search.Documents.IndexesRestClient.CreateOrUpdate(String indexName, SearchIndex index,
Nullable`1 allowIndexDowntime, String ifMatch, String ifNoneMatch, CancellationToken
cancellationToken)
at Azure.Search.Documents.Indexes.SearchIndexClient.CreateOrUpdateIndex(SearchIndex index, Boolean
allowIndexDowntime, Boolean onlyIfUnchanged, CancellationToken cancellationToken)
at AzureSearch.SDKHowTo.Program.<Main>d__0.MoveNext() in C:\Users\dk25\Downloads\search-dotnet-
getting-started-master\search-dotnet-getting-started-master\DotNetHowToIndexers\Program.cs:line 56
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AzureSearch.SDKHowTo.Program.<Main>(String[] args)
This exception was originally thrown at this call stack:
[External Code]
AzureSearch.SDKHowTo.Program.Main(string[]) in Program.cs
[External Code]
So from my trial and error methods, I found that you will have to set the MaxAgeInSeconds
Slight modification to the code which worked for me :
var cors_option = new CorsOptions(new List<string> { "*" });
cors_option.MaxAgeInSeconds = 300;
searchIndex.CorsOptions = cors_option;
When I had commented to the MaxAgeInSeconds, was provided with the same error you were :

Error when calling method on web api controller - .Net Core 1.1 / EF 1.1

A few hours ago I posted a question, but in my haste to post the question before going to a meeting, I posted the wrong thing. I have deleted it, and here is the correct version:
I am developing a .Net Core 1.1 Web API using EF Core 1.1, which connects to a MySQL database using Pomelo.
It connects properly, but when I try to read a certain record:
http://localhost:50082/api/houses/3
I get the following error:
An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index System.ThrowHelper.ThrowArgumentOutOfRange_IndexException()
Here is what my controller looks like:
private readonly InspectionsContext _context;
// GET: api/Houses/5
[HttpGet("{id}")]
public async Task<IActionResult> GetHouse([FromRoute] int? id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var house = await _context.Houses.SingleOrDefaultAsync(m => m.HouseId == id);
if (house == null)
{
return NotFound();
}
return Ok(house);
}
The error happens on this line:
var house= await _context.Houses.SingleOrDefaultAsync(m => m.HouseId == id);
House is just a standard class matching the corresponding table in the database. And there IS a house - and only one house - in the database with ID = 3.
Any ideas why I'm getting this error?
UPDATE:
Here is the full StackTrace of the error:
at System.ThrowHelper.ThrowArgumentOutOfRange_IndexException() at
System.SZArrayHelper.get_Item[T](Int32 index) at
lambda_method(Closure , ValueBuffer ) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalMixedEntityEntry..ctor(IStateManager
stateManager, IEntityType entityType, Object entity, ValueBuffer
valueBuffer) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryFactory.NewInternalEntityEntry(IStateManager
stateManager, IEntityType entityType, Object entity, ValueBuffer
valueBuffer) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryFactory.Create(IStateManager
stateManager, IEntityType entityType, Object entity, ValueBuffer
valueBuffer) at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTrackingFromQuery(IEntityType
baseEntityType, Object entity, ValueBuffer valueBuffer, ISet1
handledForeignKeys) at
Microsoft.EntityFrameworkCore.Query.Internal.EntityTrackingInfo.StartTracking(IStateManager
stateManager, Object entity, ValueBuffer valueBuffer) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.StartTracking(Object
entity, EntityTrackingInfo entityTrackingInfo) at
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.<>c__DisplayClass16_02.<_TrackEntities>b__0(TOut
result) at
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.SelectAsyncEnumerable2.SelectAsyncEnumerator.<MoveNext>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at
InspectionsWebApi.Controllers.HousesController.d__4.MoveNext()
in
C:\Users\fabsr\Source\Repos\InspectionsWebApi\InspectionsWebApi\Controllers\HousesController.cs:line
46
You have to instantiate your context object. Try making your SingleOrDefault call like:
using (var _context = new InspectionsContext())
{
var house = await _context.Houses.SingleOrDefaultAsync(m => m.HouseId == id);
}
Ok, it looks like it was some column that - most probably Pomelo - didn't like. I deleted all columns and kept only 3 basic columns (and int, a bool and a varchar) and it works. I'll have to try figure out which column it was... As soon as I figure it out, I'll post... Thanks everyone for your help

IIS Directory Services

I am trying to get the website id from IIS on Windows Server 2012 R2. I want to fetch the Id, then add a website pointer for the website in IIS. I'm not sure where to grant the permissions for the code to work and at the same time, not leaving my web server vulnerable.
Here is my code for fetching Id
string result = "-1";
DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", "localhost"));
foreach (DirectoryEntry site in w3svc.Children)
{
if (site.Properties["ServerComment"] != null)
{
if (site.Properties["ServerComment"].Value != null)
{
if (string.Compare(site.Properties["ServerComment"].Value.ToString(),
"website.com", true) == 0)
{
result = site.Name;
break;
}
}
}
}
return result;
This is the error that is thrown:
Access is denied.
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: System.Runtime.InteropServices.COMException: Access
is denied.
Source Error:
Line 22: DirectoryEntry w3svc = new
DirectoryEntry(string.Format("IIS://{0}/w3svc", serverName));
Line 23:
Line 24: foreach (DirectoryEntry site in w3svc.Children)
Line 25: {
Line 26: if (site.Properties["ServerComment"] != null)
Source File: c:\inetpub\wwwroot\DNS_IIS\DNS.aspx.cs Line: 24
Stack Trace:
[COMException (0x80070005): Access is denied.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
+597561
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_IsContainer() +42
System.DirectoryServices.DirectoryEntries.GetEnumerator() +49
DNS.GetWebSiteId(String serverName, String websiteName) in c:\inetpub
\wwwroot\DNS_IIS\DNS.aspx.cs:24
DNS.btnDNS_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot
\DNS_IIS\DNS.aspx.cs:85
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+3804
It was a simple thing to sort out.
So I just changed the Identity of the ApplicationPool to LocalSystem and it worked 100%.

Merging WCF webservice to my web application returns an exception

I would like to add an reference for WCF weather forecast webservice in my application.The thing is I have done everything correctly,but i am lacking somewhere else.It throws an Exception.The Exception message is in the bottom of this post.Somebody out there please help me to fix this.Unles or until fixing this i couln't move to the next phase.
My Source Code is here:
public partial class Testing : System.Web.UI.Page
{
weather.WeatherForecastServiceClient ws = new weather.WeatherForecastServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
SortedDictionary<string, string> objDic = new SortedDictionary<string, string>();
foreach (CultureInfo ObjectCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo objRegionInfo = new RegionInfo(ObjectCultureInfo.Name);
if (!objDic.ContainsKey(objRegionInfo.EnglishName))
{
objDic.Add(objRegionInfo.EnglishName, ObjectCultureInfo.Name);
}
}
foreach (KeyValuePair<string, string> val in objDic)
{
Country.Items.Add(new ListItem(val.Key, val.Value));
}
}
protected void callwebservice_Click(object sender, EventArgs e)
{
Result.Text = "Result" + ws.GetForecastByCity(City.SelectedItem.ToString(), Country.SelectedItem.ToString());
}
protected void Country_SelectedIndexChanged(object sender, EventArgs e)
{
string[] cities = ws.GetCitiesByCountry(Country.SelectedItem.ToString());
City.DataSource = cities;
City.DataBind();
}
}
This is my Exception
Server Error in '/' Application.
**The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
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: System.ServiceModel.FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Source Error:
Line 310:
Line 311: public testing.weather.Weather GetForecastByCity(string City, string Country) {
Line 312: return base.Channel.GetForecastByCity(City, Country);
Line 313: }
Line 314: }
Source File: E:\***\WeatherForecast\testing\Service References\weather\Reference.cs Line: 312
Stack Trace:
[FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9442991
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
testing.weather.IWeatherForecastService.GetForecastByCity(String City, String Country) +0
testing.weather.WeatherForecastServiceClient.GetForecastByCity(String City, String Country) in E:\sasi\WeatherForecast\testing\Service References\weather\Reference.cs:312
testing.Testing.callwebservice_Click(Object sender, EventArgs e) in E:\sasi\WeatherForecast\testing\Testing.aspx.cs:40
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
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) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272**
You have implemented the service correctly. You can confirm this by running GetCitiesByCountry (it will return a list of cities). It is just that the method GetForecastByCity does not currently work.
Try any of these APIs instead.

Problems in aspnet membership provider

I am using asp.net memebership
I log out the applcation by writting this code for log out
if (Membership.GetUser(HttpContext.Current.User.Identity).IsOnline) ;
{
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.LoginUrl);
}
Response.Redirect("loginpage.aspx");
After then I started the application and gettig the error in code block of authetication .below I am writtng a code and error message
else if (User.Identity.IsAuthenticated == true && Membership.GetUser( Membership.FindUsersByName(User.Identity.Name)).IsOnline==true)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
MembershipUser currUser = null;
string gt = null;
if (HttpContext.Current.User != null)
{
currUser = Membership.GetUser(true);
gt = currUser.Email;
}
/// string temp = User.Identity.GetProfile().ID;
//string query = "Insert into user_tbl(MemberID)(" + temp + ")";
//Response.Redirect("UserPanel.aspx");
//return;
}
here Membership.FindUsersByName(User.Identity.Name)).IsOnline==true) I am getting this error
[ArgumentException: The provider user key supplied is invalid. It
must be of type System.Guid. Parameter name: providerUserKey]
I am unable to find what to do , I debug the application and found User.Identity.Name as a hash value
Stack Trace
Exception Details: System.ArgumentException: The provider user key supplied is invalid. It must be of type System.Guid.
Parameter name: providerUserKey
Source Error:
Line 86: }
Line 87:
Line 88: else if (User.Identity.IsAuthenticated == true && Membership.GetUser( Membership.FindUsersByName(User.Identity.Name)).IsOnline==true)
Line 89: {
Line 90:
Source File: d:\31 May 2012\Demo\LoginPage.aspx.cs Line: 88
Stack Trace:
[ArgumentException: The provider user key supplied is invalid. It must be of type System.Guid.
Parameter name: providerUserKey]
System.Web.Security.SqlMembershipProvider.GetUser(Object providerUserKey, Boolean userIsOnline) +2242996
System.Web.Security.Membership.GetUser(Object providerUserKey, Boolean userIsOnline) +40
System.Web.Security.Membership.GetUser(Object providerUserKey) +6
LoginPage.Page_Load(Object sender, EventArgs e) in d:\31 May 2012\Demo\LoginPage.aspx.cs:88
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +36
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Or you could also use Request.IsAuthenticated which dosent get the whole user object and just checks authentication.
According to Visual Studio, Membership.FindUsersByName returns MembershipUserCollection. You pass that object to the Membership.GetUser method, which does accept a parameter of the object type, but that object is supposed to be a user's ID (a GUID in ASP.NET). So, the exception is quite expected: you're trying to pass a collection of users, while the method expects a single user ID.
If you need to check whether a user is currently logged in, you can simply do this:
if (Membership.GetUser() != null)
See this MSDN Library article for more information on the method.

Categories