I know this has been asked before, but no solution I've tried has worked for me. I need to insert X number of images from a multiple media picker into a a carousel element.

Currently I merely extract each image using a hardcoded index.

<div class="active item" data-slide-number="0"> <img src='@(Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>("sommerhusBilleder").ToList()[0].Url)'></div>

But this doesn't work when the client should be able to insert any number of images. I need to iterate over each image with this markup, while also changing the data-slide-number each time, so that it matches to the thumbnails I have associated with it.

How can I iterate over X amount of images and extract their URL's to use in my carousel?

So This is my div and the for loop creates a new list item and based on the id of the ticket in the database it displays all the states the ticket was in i.e open, In Progress , closed, etc.

 <div id="Child" style="display:inline-block;" class="box">
            <ul id="first-list">
                <!--Foreach Goes Here-->
                @foreach (var item in Model)
                {
                <li>
                    <span></span>
                    <div class="title">
                        @Html.DisplayFor(model => item.Description)
                    </div>
                    <div class="info">@Html.DisplayFor(model => item.ActivityContent).</div>
                    <div class="info">@Html.DisplayFor(model => item.Subject) <a href=@Url.Action("EditActivity", "Home", new { area = "EditActivity", Id = item.TicketId , TypeId = item.ActivityTypeId }) data-toggle="modal" data-target="#editModal" data-modal="edit"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a></div>
                    <div class="name">- @Html.DisplayFor(model => item.CreatedByUser)</div>
                    <div class="time">
                        @if(item.ModifiedDateTime != null)
                        {
                            <span>@(item.ModifiedDateTime == null ? "" : Convert.ToDateTime(item.ModifiedDateTime).ToString("MMMM dd, yyyy"))</span>
                        }
                        else
                        {
                            <span>@(item.CreatedDateTime == null ? "" : Convert.ToDateTime(item.CreatedDateTime).ToString("MMMM dd, yyyy"))</span>
                        }
                        @if(item.ModifiedDateTime != null)
                        {
                            <span style="padding-left:35px;">@(item.ModifiedDateTime == null ? "" : Convert.ToDateTime(item.ModifiedDateTime).ToShortTimeString())</span>
                        }
                        else
                        {
                            <span style="padding-left:35px;">@(item.CreatedDateTime == null ? "" : Convert.ToDateTime(item.CreatedDateTime).ToShortTimeString())</span>
                        }
                    </div>
                </li>
                }
            </ul>
        </div> 

What I would like to do is add a different color for each state. such as green when the state is open and red when closed. Anyone have a good way to approach this? I am setting the color for the div in a class called box which looks like this...

.box ul li {
            margin: 30px 60px 60px;
            position: relative;
            padding: 5px 5px 5px 5px;
            background: #e56565;
            color: #fff;
            border-radius: 10px;
            line-height: 20px;
            width: 55%
        }

Thanks in advance for any help with this issue.

After upgrading to Net Core 2.0 my 1.1 web application will not run. I get the error message indicated above. After checking the output I found references to the RZ3007 error which I believe is related to the Razor compiler. The View is not compiling. Any direction anyone can provide will be helpful.

Home/Index.cshtml:

@model LayoutViewModel
<div></div>

Views/Shared/_Layout.cshtml

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - GLCoderConfiguration</title>

    <environment names="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css?" />
    </environment>
    <environment names="Staging,Production">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css?" asp-append-version="true" />

   </environment>
</head>
<body>
    <nav class="navbar navbar-default navbar-form " >

        <div class="navbar-header" style="margin-top:10px;margin-bottom:15px;">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">SCM - NCMain</a>
        </div>


        <div class="collapse navbar-collapse vcenter" id="bs-example-navbar-collapse-1" style="margin-top:10px;margin-bottom:0px;">

      </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2017 - England Logisitics - SCM</p>
        </footer>
    </div>

    <environment names="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment names="Staging,Production">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>


    </environment>

    @RenderSection("Scripts", required: false)
  </body>
</html>

I had a couple of view components (LoginStatus and MenuItems) but removed them to try to get this working.

Output from run:

    Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException: One or more compilation failures occurred:
(0,0): Error RZ3007: Targeted tag name cannot be null or whitespace.
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(String normalizedPath)
--- 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 Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.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.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__19.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.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.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.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.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.AspNetCore.Builder.RouterMiddleware.<Invoke>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.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.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.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.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.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

.CSProj

    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>
        <TargetFramework>netcoreapp2.0</TargetFramework>
        <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
        <MvcCompileViews>true</MvcCompileViews>
        <PreserveCompilationContext>true</PreserveCompilationContext>
        <AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
        <StartupObject>GLCoderConfiguration.Program</StartupObject>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="FluentValidation" Version="7.1.1" />
        <PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.TagHelpers" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Razor.Runtime" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Session" Version="2.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
        <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.0.0" />
        <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
        <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
        <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
        <PackageReference Include="Microsoft.NETCore.Platforms" Version="2.0.0" />
        <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.0.0" />
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
        <PackageReference Include="NETStandard.Library" Version="2.0.0" />
        <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.4.0" />
      </ItemGroup>

      <ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
      <ItemGroup>
        <ProjectReference Include="..\..\SCMEnumerations\SCMEnumerations.csproj" />
        <ProjectReference Include="..\..\TMainModel\TMainModel.csproj" />
        <ProjectReference Include="..\..\ViewHelperFunctions\ViewExtensions.csproj" />
      </ItemGroup>

    </Project>

Trying to render dynamically buttons and place 3 buttons in each row but they appear on the screen all in a separate row?

 <div class="row">
<div class="container sports-container col-md-12">

    @foreach (var sport in Model.Aggregator.SportsRepository.List().Where(x => x.ParentSportId == null))
    {
        <div class="col-md-4">
            <a class="btn btn-outline-info">@sport.Description</a>
        </div>
    }


</div>

<style>
.sports-container {
    background-color: whitesmoke;
    margin-top: 20px;
}
</style>

i have a listbox selection in my view ,i need to hold the ctrl key for select multiple items , i am using the following code :

    @Html.ListBoxFor(
     m => m.SelectedSkills ,
     new MultiSelectList( listItems, "Id", "Name", @Model.SelectedSkills ),
     new { Multiple = "multiple" }
    )

i want to put a checkbox infront of each list item,user can check/uncheck the checkbox to select/deselect an item ,and when it post the form,only the selected checkboxes values should be passed in controller action , How can i acheive this...

We are building a REST web app with a C# asp.net webapi and an Angular4 front-end app. In this app we are trying to implement a progress bar of a server side calculation progress in the Angular app.

We are looking for :

  • The best way to implement this function, we tried to use SignalR with ng2-signalr but with no success. What would be in your opinion the best technical option for this problem?
  • The heart of the problem is that the progressbar depends of a huge variable stored in session. We can't access it in SignalR. We hesitate between make a HttpRequest that calls a hub function, but how to send data to the right user then ? Or invoke a server method and pass the session variable through a static variable, but if many users want to access it simultaneously?

Thanks in advance

I have two projects in one solution. I know how to copy files from client to server file system. How can I copy files from client system using admin project and send into client project file system.

I am trying to bind data in radio button list, but Selected value and Selected item showing wrong result when there is any duplicate record present in the Binding source.

This is How i am trying to bind the RadioButtonList:

    List<object> _source = new List<object>(){
   new{Id=1,Client_Name="ABC",DBConfigName="ABC"},
   new{Id=1,Client_Name="ABC1",DBConfigName="ABC"},
   new{Id=1,Client_Name="ABC2",DBConfigName="ABC"},
   };
    rdMappedClientList.DataSource = _source;
    rdMappedClientList.DataTextField = "Client_Name";
    rdMappedClientList.DataValueField = "DBConfigName";
    rdMappedClientList.DataBind();

as you can see the dataSource _source holding duplicate record for DBConfigName. In this case if i tried to execute _SelectedIndexChanged event then it'll return wrong result.

There is no documentation for RadioButtonList class that It's Value field should not contains duplicate value.

If i changed the value field for this to Id it'll work perfectly.

Note:

no compile time or run time error
No documentation mentioning for Unique values for Value field

So, i am not able to understand this.

I just migrated an ASP.Net Core 1.1 application to the new 2.0 version that was just released. Now I get the following exception:

System.BadImageFormatException: 'Could not load file or assembly 'dotnet-aspnet-codegenerator-design' or one of its dependencies. An attempt was made to load a program with an incorrect format.'

The exception is thrown on the following line (AddMvc):

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    ...
    services.AddMvc(options =>
        {
            options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline)));
        })
        .AddJsonOptions(options =>
        {
            // Maintain property names during serialization. See:
            // https://github.com/aspnet/Announcements/issues/194
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        })
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();
}

nasty exception screenshot

I'm targeting the .Net Framework 4.7, using AnyCPU target platform. I'm using the win10-x64 RID if this is of any help. Every Nuget package is up to date etc.

Any idea? I've got no luck by googling.

I am struggling with being able to create a file with its data based on the byte array returned from the WebAPI. The following is my code for making the call to the web api

 using (var http = new WebClient())
            {
                string url = string.Format("{0}api/FileUpload/FileServe?FileID=" + fileID, webApiUrl);
                http.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
                http.Headers[HttpRequestHeader.Authorization] = "Bearer " + authCookie.Value;
                http.DownloadDataCompleted += Http_DownloadDataCompleted;
                byte[] json = await http.DownloadDataTaskAsync(url);



            }

The api code is

[HttpGet]
    [Route("FileServe")]
    [Authorize(Roles = "Admin,SuperAdmin,Contractor")]
    public async Task<HttpResponseMessage> GetFile(int FileID)
    {
        using (var repo = new MBHDocRepository())
        {
            var file = await repo.GetSpecificFile(FileID);
            if (file == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var stream = File.Open(file.PathLocator, FileMode.Open);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.FileType);
            return response;
        }
    }

I receive a byte array as a response however am unable to create the corresponding file from that byte array. I have no idea how to convert the byte array into the relevant file type (such as jpg, or pdf based on file type in the web api). any help will be appreciated.

I started using HangFire to process a task every X minutes/hours and I need to add recurring jobs. In console application I managed to do it just fine but on asp.net I can only get it to work once, through the BackgroundJob.Enqueue method.

public class Global : HttpApplication
{
    private static string LigacaoBD = myConn;
    private static ApiMethods sportRadar = new ApiMethods();
    private static Jogo jogo = new Jogo(LigacaoBD);
    private static List<SportRadar.ClassesCliente.Jogo> jogos;
    private static List<SportRadar.ClassesCliente.Competicao> competicoes;

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        GlobalConfiguration.Configuration.UseSqlServerStorage(LigacaoBD);

        using (var connection = JobStorage.Current.GetConnection())
        {
            foreach (var recurringJob in connection.GetRecurringJobs())
            {
                RecurringJob.RemoveIfExists(recurringJob.Id);
            }
        }

        using (var server = new BackgroundJobServer())
        {
            // This works just fine
            var id=BackgroundJob.Enqueue(() => Actualizacoes());
            // This does not.
            // I even checked the DB for job queue or something but couldn't find anything
            RecurringJob.AddOrUpdate(id, () => Actualizacoes(), Cron.Minutely);
        }
    }



    public void Actualizacoes()
    {
        // Stuff I need to do regularly
    }
}

I thought I got it right but evidently I got something wrong here. Where do you think the problem might be at?

I'm developing a web application and I want to be able to access currently logged in user through my IUserContext interface. It looks like so:

public interface IUserContext
{
    int UserId { get; }
    string UserName { get; }
}

This interface can be consumed in my command handlers and query handlers.

Web application uses ASP.NET Identity library version 2.2.1. So, I want to implement the interface using IOwinContext. I have three layers where I need access to owin context:

  • ASP.NET Web Forms pages
  • ASP.NET MVC 5 actions
  • Signalr hub

For web forms pages and MVC actions, I can write custom middleware to populate IUserContext properties (using code from this doc):

public interface IOwinContextAccessor
{
    IOwinContext CurrentContext { get; }
}

public class CallContextOwinContextAccessor : IOwinContextAccessor
{
    public static AsyncLocal<IOwinContext> OwinContext = new AsyncLocal<IOwinContext>();
    public IOwinContext CurrentContext => OwinContext.Value;
}

public class OwinUserContext : IUserContext
{
    public int UserId => CallContextOwinContextAccessor.OwinContext.Value.Authentication.User.Identity.GetUserId<int>();
    public string UserName => CallContextOwinContextAccessor.OwinContext.Value.Authentication.User.Identity.Name;
}

    // inside my Startup.cs Configuration method
    app.Use(async (context, next) => {
        CallContextOwinContextAccessor.OwinContext.Value = context;
        await next();
    });

For signalr hub I can create HubPipelineModule which will populate CallContextOwinContextAccessor.OwinContext:

public class OwinContextPipelineModule : HubPipelineModule
{
    protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context)
    {
        var owinContext = context.Hub.Context.Request.GetHttpContext().GetOwinContext();
        CallContextOwinContextAccessor.OwinContext.Value = owinContext;
        return base.OnBeforeIncoming(context);
    }
}

Questions:

  1. Is this the correct way of accessing logged in user in ASP.NET Identity?
  2. Is it safe to reuse CallContextOwinContextAccessor inside middleware and hub pipeline module? I've read documentation about AsyncLocal type and it seems like variable's value persists across methods calls down the call stack. I worry about possible race conditions when one user calls MVC action and at the same time another user calls signalr hub method or vice versa.

This question already has an answer here:

I am trying to change the date format of date retrieved from database to Aug 21, 2017 11:31 AM format in view.

But on execution of project it throws

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Below is my code in view

@Html.DisplayFor(modelitem => item.postedon.ToString("MMM d, yyyy  h:mm tt"))

I want to display a header logo on my master template.

So far I have this code:

<h1 class="brand_name">
    <a href="/"><img width="320px" 
       src='@(Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>
       ("headerLogo").Url)'>
    </a>
</h1>

When i run the page i receive this error message:

http://i.imgur.com/4RaL947.png

I'm not sure what causes this error, as the formatting looks fine to me. The mediapicker property editor for the header logo is defined in a language document type, which has the master as its template.

I am trying to connect the WebApp (GMCMS) in azure to the WebApi(GMMobileService) in Azure.

I have created the active directory and configured it like this :

[Properties tab]

Name: GMMobileService

App ID URI: https://MYNAMEhotmail.onmicrosoft.com/GMMobileService

Home page URL: http://gmcms.azurewebsites.net

Application ID: 467d1f26-2975-47c6-b6c8-13a40f241d8f

[Required permissions tab]

i added the GMCMS WebApp there with DELEGATED PERMISSIONS,
REQUIRES ADMIN, NO, Access GMCMS

And in the Web.config mobile service (web api) i added the following

<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="ida:Tenant" value="MYNAMEhotmail.onmicrosoft.com" />
  <add key="ida:Audience" value="https://MYNAME.onmicrosoft.com/GMMobileService" />
</appSettings>

Then in the GMMobileService page i went to the settings section and clicked the Authentication / Authorization and changed the Action to take when request is not authenticated and changed it to "Log in with Azure Active Directory" and i clicked the Azure ective directoy tab to configure.

I used Express and connected the Azure AD App: GMMobileService; APP NAME: GamesMafiaMobileService CLIENT ID: 467d1f26-2975-47c6-b6c8-13a40f241d8f

So now i configured the web.config of the GMCMS page:

 <appSettings>   
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="todo:TodoListBaseAddress" value="https://localhost:44321" />
    <add key="ida:ClientId" value="e72812f0-ab50-479e-a495-03708c1f5645" />
    <add key="ida:AppKey" value="/aIHbl2NrhZBD6N4jQtXj8Zi8K0s8A1uHCvlD4+8Oec=" />
    <add key="ida:Tenant" value="MYNAME.onmicrosoft.com" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
    <add key="ida:RedirectUri" value="https://localhost:44322/" />
 </appSettings>

The request i made directly from angular:

    $scope.getProducts = function () {

        $http({
            method: 'Get',
            url: "https://gmmobileservice.azurewebsites.net/Api/AllProducts"
        })
           .success(function (data) {
               console.log(data)

           })
           .error(function (data) {
               $scope.message = 'Unexpected Error';
           });

    }

And what i get out now is that is says Authorized, before it did not but the give me a 302 status, found? And the 'live data from your app shows' that there is actually a request made but in the console.log i get information out like a webpage, like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="nl">
<head>

<script type="text/javascript">//<![CDATA[
etc. etc.

what am i doing wrong and do i need to change to get a status 200 OK?

I have asp.net mvc application uses asp.net identity , Entity framework and data access layer using repository pattern, Autofac is used in asp.net mvc for dependency injection We need to make this app work for multi-tenant separate database approach how Could I Achieve that .I used General DB that contain Tenants and Tenants-users that contain Tenant Connection-string that my application will login to it and manipulate with.

I am building an application with an integrated audio upload, though now I have the problem that my application is running into System.Web.HttpException: Maximum request length exceeded when uploading audio files over 10MB, as I have configured in my web.config

<httpRuntime maxRequestLength="10485">

I know about the possibility to increase the request limits in order to prevent this exception, but instead of allowing larger files I want to catch those and prevent their HTTP request.

It may be possible to validate the size client side, but as the client side validation can be bypassed I am looking for a server side validation that doesn't requires me to increase the limits.

In the previous version,I have used Server.MapPath() method to get the physical path. Now in the core ,I can't do it ,I have used IHostingEnvironment, but it can only get wwwroot path .

I have this Razer page:

@using System
@{
    ViewData["Title"] = "Home Page";
}
@model Conference.Models.Profile

<h1>Profile</h1>
<div class="row">
    <div class="col-md-4">
        Name: @Model.Name
        @if (!String.IsNullOrEmpty(Model.AvatarPath)) {
            <img src="/uploads/@Model.AvatarPath" class="img-thumbnail" />
        }
    </div>
</div>
<a asp-controller="Profile" asp-action="Edit">Edit Profile</a>

I'm struggling with @model Conference.Models.Profile. The class model exists with the relevant data, but it's not resolving the dependency: The type or namespace name 'Profile' does not exist in the namespace 'Conference.Models' (are you missing an assembly reference?). If I try and resolve Conference.Models.User, it resolves just fine. Here is the model:

namespace Conference {
    public class Profile {
        public string Name { get; set; }
        public string AvatarPath { get; set; }
    }
}

I started with the ASP.NET Core Web Application template in Visual Studio, using ASP.NET Core 2.0. I am new to ASP.NET and learning how to add file uploads to the base application, I'm following this sample and learning how to implement it.

We have an CMS project, we will publish the project for deploying to PROD server, However we found that if we changed aspx file content in published project, e.g. Modify label control text, an error will error.

Error ScreenCap

Is there are any contraint for pubsliehd .aspx and .dll? Can we just just modify aspx file without re-publish and deploy it again?

Any help is appreciated.

Im working on an Mvc app and im still a newbie..and im trying to experiment something but its not working

is it correct to loop my "using()" so that it can store a data in every loop

this is my post code here

 [HttpPost]
    public ActionResult Index(EntityFramework.Table1 a,Class1 b)
    {
        b.Letter1 = new Boolean[3];
        for (int x = 0; x <= 3; x++)
        {
            if (b.Letter1[x] == true)
            {
                a.checkAnswers = "correct";
                b.sum = b.sum + 1 ;
            }
            else
            {
                a.checkAnswers = "wrong";
                b.sum = b.sum + 0;

            }
            a.Total = b.sum;
            using (var c = new EntityFramework.Database1Entities1())
            {
                c.Table1.AddObject(a);
                c.SaveChanges();
            }
        }
        return RedirectToAction("Index");
    }

it says an error to c.Table1.AddObject(a); :The EntityKey property can only be set when the current value of the property is null.

i think its updating instead of adding..am i doing it wrong?