Index Out of Range Exception - Active Directory Adapter - asp.net-mvc

I understand what an Index Out of Range Exception is, however, I can't seem to figure out what is going on in the Stack Trace below.
This is an asp.net website, and it has been working without issue for the past few years. I have checked with the System Administrator and they noted nothing has changed on the server hosting the website or dc. Currently at a stand still, any ideas as to where to look or begin diagnosing?
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target, IntPtr[] pSids) +1507
System.DirectoryServices.AccountManagement.SidList..ctor(SID_AND_ATTR[] sidAndAttr) +142
System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) +220
System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() +50
PayDirectory.Classes.ActiveDirectoryAdapter.IsUserAllowed(String username, IList`1 allowedgroups) in C:\Users\johndoe\Documents\Visual Studio 2010\Projects\PayDirectory\PayDirectory\Classes\ActiveDirectoryAdapter.cs:35
PayDirectory.Controllers.AccountController.CheckUser(String sessionid) in C:\Users\johndoe\Documents\Visual Studio 2010\Projects\PayDirectory\PayDirectory\Controllers\AccountController.cs:42
lambda_method(Closure , ControllerBase , Object[] ) +108
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +29
Etc.
That is the beginning of the Stack Trace, I can post the entire trace if necessary.
Basically, the application takes the session id of a user logged into Joomla, checks ad to see if that user is in a particular group (Principals) and allows them to view certain content, otherwise it will state Access is Denied.
EDIT
Adding source code for "IsuserAllowed" in ActiveDirectoryAdapter class
public Boolean IsUserAllowed(string username, IList<string> allowedgroups)
{
PrincipalContext domain = new PrincipalContext(ContextType.Domain, "Redmond");
UserPrincipal user = UserPrincipal.FindByIdentity(domain, username);
List<GroupPrincipal> groups = new List<GroupPrincipal>();
if (user != null)
{
PrincipalSearchResult<Principal> authGroups = user.GetAuthorizationGroups();
foreach (Principal p in authGroups)
{
if (p is GroupPrincipal)
{
groups.Add((GroupPrincipal)p);
}
}
}
string groupstring = string.Join(",", (object[])groups.ToArray());
string[] groupnames = groupstring.Split(',');
for (int i = 0; i < allowedgroups.Count; i++)
{
if (groupnames.Contains(allowedgroups[i]))
{
return true;
}
}
return false;
}

Related

IO Error when Uploading to Azure Blob Storage from Azure Web App

After spending some hours searching for an answer, I've concluded that the question needs to be refocused on the Azure storage connection string
<add key="yadayadayada_AzureStorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=yadayada;AccountKey=yoyoyoyo==;EndpointSuffix=core.windows.net" />
and the use of ImageResizer and AzureReader2 which also has a connection string. The settings for that are:
<resizer>
<pipeline defaultCommands="autorotate.default=true" />
<plugins>
<add name="AzureReader2" connectionString="DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=acctkey==" endpoint="http://acctnumber.blob.core.windows.net/" prefix="~/azure" />
</plugins>
As I change the endpoints, I get different errors. When I change the azure prefix to "~/" it crashes.
Here is the original question, but I'm asking with more certainty what should the storage connection strings be to authorize upload to my azure website.
Here's the original question: Uploading from my development machine to Azure blob storage works fine. However, uploading from the deployed (on Azure) asp.net mvc app gets this error: System.IO.FileNotFoundException: Could not find file 'D:\Windows\system32\
Do I need to establish write permission for the app, and if so how?
Or is there something wrong with my code?
private CloudBlobContainer GetCloudBlobContainer()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("accountidhere_AzureStorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("FOLDER NAME HERE");
return container;
}
public async Task<ActionResult> AddAnnouncementPhotos(AddPhotosViewModel vm, FormCollection fcoll)
{
if (ModelState.IsValid)
{
int theID = vm.ThePost.PostId;
foreach (string fileName in Request.Files)
{
HttpPostedFileBase fb = Request.Files[fileName];
string caption = fileName.Replace("File", "Photo");
var phostring = caption + ".PhotoCaption";
if (fb != null && fb.ContentLength > 0 && fb.ContentType.StartsWith("image"))
{
string path = fb.FileName;
string ext = path.Substring(path.LastIndexOf("."));
string newname = Guid.NewGuid() + ext;
CloudBlobContainer container = GetCloudBlobContainer();
CloudBlockBlob blob = container.GetBlockBlobReference(newname);
blob.Properties.ContentType = fb.ContentType;
using (var fileStream = System.IO.File.OpenRead(path))
{
blob.UploadFromStream(fileStream);
}
Adding the Stack Trace:
FileNotFoundException: Could not find file 'D:\Windows\system32\DSC02724.JPG'.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +519
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +829
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +65
swIndWorkshop.Controllers.<AddAnnouncementPhotos>d__14.MoveNext() in C:\Users\JHstandard\Documents\aspnetProjects\swIndWorkshop\swIndWorkshop\Controllers\AnnouncementsController.cs:420
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.<>c__DisplayClass285_0.<ExecuteStepImpl>b__0() +24
System.Web.StepInvoker.Invoke(Action executionStep) +100
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +17
Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) +64
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +54
System.Web.StepInvoker.Invoke(Action executionStep) +84
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +100
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
You don't specify the whole path used in var fileStream = System.IO.File.OpenRead(path), so it's current directory by default.
On Azure the process current working directory is D:\Windows\system32\, where we have no access to write and the uploaded file can't be there either.
Update
Recommand to use InputStream, so we don't have to save file on web server.
Just replace System.IO.File.OpenRead(path) with fb.InputStream.
To use System.IO.File.OpenRead(path), need some modification in your if segment.
if (fb != null && fb.ContentLength > 0 && fb.ContentType.StartsWith("image"))
{
string path = fb.FileName;
// add these two line to save file on web app server
var wholePath = Path.Combine(Server.MapPath("~/"), path);
fb.SaveAs(wholePath);
.....
using (var fileStream = System.IO.File.OpenRead(wholePath))
{
blob.UploadFromStream(fileStream);
}
....
}

SimpleInjector and System.Web.Mvc.Async threads

I asked before a question here, and I read this question/answers about multi-threading and I know those solutions. But today I get a new problem. When we are using commands (or where we can access the original code to manage and modify it) the async-decorator that suggested in above answers works. But when MVC creates a new thread itself, what can we do? e.g. I have a custom role provider (works with DbContext), and I get this error:
The operation cannot be completed because the DbContext has been disposed.
And here is stack trace:
[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed() +67
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +34
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +22
System.Linq.Queryable.Any(IQueryable1 source, Expression1 predicate) +265
MyProject.MyRoleProvider.IsUserInRole(String username, String roleName) in ...
System.Web.Security.Roles.IsUserInRole(String username, String roleName) +263
MyProject.MyPrincipal.IsInRole(String role) in ...
System.Linq.Enumerable.Any(IEnumerable1 source, Func2 predicate) +146
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +200
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
As you can see, MyProject.MyRoleProvider.IsUserInRole invoked asynchronously, which I did not start it and its invoking async by MVC itself. So I have not any control on it. My provider ctor is:
public MyRoleProvider() {
_context = MyIoCWrapper.GetService();
}
It seems when MyRoleProvider instantiated, HttpContext is not null, and when IsInRole called, HttpContext is null.
If I want to start a new life scope, it will be used just once, and if MVC starts a new thread, I will have a new DbContext too. I confused to finding a solution. Have you any one?
How can I start a new life scope for all background threads -I start them or MVC starts them?
Your problem is in fact unrelated to running controllers asynchronously, but is a general problem of controlling the lifetime of objects.
You probably registered your MyRoleProvider in the web.config of the application, or perhaps registered it through code. Eitherway, the MyRoleProvider is a singleton, there is just a single instance of that class during the lifetime of the application.
The MyRoleProvider however depends on a DbContext which has a lifestyle that is shorter (Per Web Request or hybrid in your case), which means you can't cache that DbContext during the lifetime of your MyRoleProver, since that would 'promote' the lifestyle of that DbContext to singleton as well. The _context = MyIoCWrapper.GetService(); line seems to indicate that you are caching that DbContext.
In this case you will have to resolve the DbContext instance on each method call. So instead, your IsUserInRole would look something like this:
public bool IsUserInRole(String username, String roleName)
{
var context = MyIoCWrapper.GetService();
return context.Roles
.Any(r => r.Name == roleName && r.User.Name == username);
}

Setting up AIML in asp.net MVC (FormatException error)

Total noob when it comes to using AIML and having a really hard time getting this set up for an asp.net mvc webpage. I have a basic view setup that the user can enter a message in a textbox and I'm trying to get the chatbot to return a response. I've gotten that interaction to work with my text case so I know the function is correctly getting the users response and that I can send back a response and show it in the chatbox, my problem is trying to setup the chatbot to create dynamic responses. Right now in my controller I have:
String filePath = Server.MapPath("~/aimlBot/aiml/");
ChatBot catbot = new ChatBot(filePath);
string ReturnText = catbot.GetOutput(text); //text is just a string no html or fancy stuff in it
and my ChatBot class
Public class ChatBot : Bot
{
private Bot myBot;
private User myUser;
public ChatBot(string filepath)
{
myBot = new Bot();
myUser = new User("Human", myBot);
Initialize(filepath);
}
private void Initialize(string filepath)
{
AIMLbot.Utils.AIMLLoader loader = new AIMLbot.Utils.AIMLLoader(this.myBot);
myBot.isAcceptingUserInput = false;
loader.loadAIML(filepath);
myBot.isAcceptingUserInput = true;
}
public String GetOutput(String input)
{
Request r = new Request(input, myUser, myBot);
Result res = myBot.Chat(r); //breaks here
string response = "Bot: " + res.Output;
return (response);
}
}
the problem I'm getting is at the
Result res = myBot.Chat(r);
the program throws a FormatException
System.FormatException was unhandled by user code
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Convert.ToDouble(String value)
at AIMLbot.Bot.get_TimeOut()
at AIMLbot.Utils.Node.evaluate(String path, SubQuery query, Request request, MatchState matchstate, StringBuilder wildcard)
at AIMLbot.Bot.Chat(Request request)
at Ira.aimlBot.ChatBot.GetOutput(String input) in C:\Users\Ira\Documents\Visual Studio 2010\Projects\Ira\Ira\aimlBot\ChatBot.cs:line 36
at Ira.Controllers.ARGController.Speak(String text) in C:\Users\Ira\Documents\Visual Studio 2010\Projects\Ira\Ira\Controllers\ARGController.cs:line 35
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
I have No idea what is wrong with my code. I've tried even changing it from the variable string to just a hardcode case like "Hello how are you" which still caused the same exception.
You have everything perfect except the loadSettings function. Please refer the below snippet to clear your problem!
public ChatBot(string filepath)
{
myBot = new Bot();
myBot.loadSettings(); // <----- You have to insert this line to fix the error!
myUser = new User("Human", myBot);
Initialize(filepath);
}

To read an Excel file with ASP.Net Excel must be installed on the server?

I read an Excel file from ASP: NET MVC to localhost without problems. But when you publish the site on error. On the server is not installed the office or any Excel library. Could this be the problem?? Or could it be??.
Thanks for your answers
*Do not use any library, read the Excel file through a connection OleDbConnection. My code is is the following:
//the error occurs here, but only published on the website:
strConex = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
/**strConex = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:copia.xlsx;
Extended Properties='Excel 12.0;HDR=YES;'"**/
OleDbConnection connection = new OleDbConnection(strConex);
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
command.Connection = connection;
connection.Open();
DataTable dtschema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String nameSheet = dtschema.Rows[0]["TABLE_NAME"].ToString();
connection.Close();
connection.Open();
command.CommandText = "SELECT * From [" + nameSheet + "]";
adapter.SelectCommand = command;
adapter.Fill(dt);
connection.Close();
The result in the following exception:
System.NullReferenceException: Object reference not set to an instance of an object. at BusinessServices.RetentionAgentService.CreateRetentionsByAgentExcel(String path, String idcard, String user, DataTable dtError, DateTime initialDate, DateTime endDate, Guid& masterId) in C:\Corp\PublicAriManagua\BusinessServices\RetentionAgent\RetentionAgentService.cs:line 342 at PublicARI.Controllers.AgentRetentionController.SaveRetentions(HttpPostedFileBase file, RetentionAgentDeclaration retAgent) in C:\Corp\PublicAriManagua\PublicARI\Controllers\AgentRetentionController.cs:line 496 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Just check that the dll for the reading of excel is also going up to the server bin folder. What are you using to read btw?
I am using EPPlus, it's really good, here is the example of method that exports excel sheet to DataTable:
/// <summary>
/// exports XLSX sheet to DataTable
/// </summary>
/// <param name="excelFile">Excel file</param>
/// <param name="sheetName">Sheet for export</param>
/// <param name="firstRowIsHeader">Excel first row is header</param>
/// <returns>DataTable with selected sheet data</returns>
private DataTable XlsxToDataTable(FileInfo excelFile, string sheetName, bool firstRowIsHeader)
{
ExcelPackage ePack = new ExcelPackage(excelFile);
ExcelWorksheet ws = ePack.Workbook.Worksheets[sheetName];
DataTable result = new DataTable();
/// header
for (int xx = 1; xx <= ws.Dimension.End.Column; xx++)
{
string data = "";
if (ws.Cells[1, xx].Value != null)
data = ws.Cells[1, xx].Value.ToString();
string columnName = firstRowIsHeader ? data : "Column" + xx.ToString();
result.Columns.Add(columnName);
}
/// data
int first = firstRowIsHeader ? 2 : 1;
for (int excelRow = first; excelRow <= ws.Dimension.End.Row; excelRow++)
{
DataRow rw = result.NewRow();
result.Rows.Add(rw);
for (int excelCol = 1; excelCol <= ws.Dimension.End.Column; excelCol++)
{
string data = "";
if (ws.Cells[excelRow, excelCol].Value != null)
data = ws.Cells[excelRow, excelCol].Value.ToString();
rw[excelCol-1] = data;
}
}
return result;
}

How to configure mvc mini profiler with Linq to SQL?

I have configured mini profiler with asp.net mvc application. I also want to profile my db so I hooked it with L2S datacontext as in this example.
It is working fine for some queries but on other queries I find null reference exception. When I attached the source code to debug I found out that
internal void AddSqlTiming(SqlTiming stats)
{
Head.AddSqlTiming(stats);
}
Head Property in above method is null in MiniProfiler.cs at line 198. Any idea why?
EDIT: Following method returns me the datacontext object
public static EvoletDataContext Get()
{
var connection = ProfiledDbConnection.Get(new SqlConnection(ConfigurationManager.ConnectionStrings["evoletworksConnectionString"].ToString()));
//var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["evoletworksConnectionString"].ToString());
//return new EvoletDataContext(connection);
return DataContextUtils.CreateDataContext<EvoletDataContext>(connection);
}
And below is the query on which miniprofiler crashes for the first time
public sysModule GetModuleHead(string actionName)
{
var val = (from mod in db.sysModules
where
mod.ModuleActionResult.ToLower().Equals(actionName.ToLowerInvariant())
select mod).SingleOrDefault();
return val;
}
For more detail, please see this question as well. I tried but failed to reproduce problem in demo project.
Edit 2: Here is the stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
MvcMiniProfiler.MiniProfiler.AddSqlTiming(SqlTiming stats) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.cs:241
MvcMiniProfiler.SqlTiming..ctor(DbCommand command, ExecuteType type, MiniProfiler profiler) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlTiming.cs:66
MvcMiniProfiler.SqlProfiler.ExecuteStartImpl(DbCommand command, ExecuteType type) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:50
MvcMiniProfiler.SqlProfilerExtensions.ExecuteStart(SqlProfiler sqlProfiler, DbCommand command, ExecuteType type) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:95
MvcMiniProfiler.Data.ProfiledDbCommand.ExecuteDbDataReader(CommandBehavior behavior) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbCommand.cs:149
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +724
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +189
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +659
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +59
System.Linq.Queryable.SingleOrDefault(IQueryable`1 source) +265
UserManagement.Models.FilterRepository.GetModuleHead(String actionName) in D:\Evolet\UserManagement\UserManagement\Models\FilterRepository.cs:14
UserManagement.Models.DummyAttrib.OnAuthorization(AuthorizationContext filterContext) in D:\Evolet\UserManagement\UserManagement\Models\Filters.cs:30
Glimpse.Net.Plumbing.GlimpseAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) +157
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +149
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +135
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +140
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +61
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +690
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194
This used to happen if you had a ProfiledDbConnection in play and the actual profiler was set to null.
In general we avoid serving our internal consumers a ProfiledDbConnection if the current request is not profiled ... this means everything is just a bit faster.
Unfortunately, this can be sometimes tricky to do with EF and L2S. To overcome this I just checked in a change that allows you to use the Profiling bespoke objects even if no profiler is in play.
Nonetheless, my recommendation remains that you should be using raw connections where possible when you are not profiling.
Looks like this issue has finally been fixed in the latest commit:
https://github.com/SamSaffron/MiniProfiler/commit/bcea578dd47d7f9ccf1f495cf67c360cdece5f2a

Resources