Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

An exception occurred while iterating over the results of a query for context type Invalid operation. The connection is closed.

$
0
0

I am working in a project using generic repository.

This is my existing repository.

namespace OnlineLearning.Repository
{
  public interface IRepository<TModel> where TModel : class, IEntity
  {
    Task<PagedList<TModel>> GetPaginatedList(BaseParameter baseParameter);
    Task<IEnumerable<TModel>> GetAll();
    Task<TModel> GetById(Guid id);
    Task Insert(TModel entity);
    void Update(TModel entity);
    void Delete(Guid id);
  }
}

and later added method for bulk delete

namespace OnlineLearning.Repository
{
  public interface IRepository<TModel> where TModel : class, IEntity
  {
    Task<PagedList<TModel>> GetPaginatedList(BaseParameter baseParameter);
    Task<IEnumerable<TModel>> GetAll();
    Task<TModel> GetById(Guid id);
    Task Insert(TModel entity);
    void Update(TModel entity);
    void Delete(Guid id);

    void MultipleDelete(List<Guid> ids);
  }
}

Old methods are working as it is, but whenever i tried to update database using new methods i.e. MultipleDelete I am getting error.

Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (56ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT [s].[Id], [s].[Active], [s].[Address], [s].[ContactNumber], [s].[CreatedAt], [s].[CreatedByUserId], [s].[EmailAddress], [s].[IPAddress], [s].[LogoLocation], [s].[ModifiedAt], [s].[ModifiedByUserId], [s].[Name], [s].[SchoolCode] FROM [Schools] AS [s] WHERE [s].[Active] = N'Active'

Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'OnlineLearning.EntityFramework.Context.ApplicationDatabaseContext'.
System.InvalidOperationException: Invalid operation. The connection is closed.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.InvalidOperationException: Invalid operation. The connection is closed.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'OnlineLearning.EntityFramework.Context.ApplicationDatabaseContext'.
System.InvalidOperationException: Invalid operation. The connection is closed.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

System.InvalidOperationException: Invalid operation. The connection is closed.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)


Want to display edit link Button in front of Gridview

$
0
0

Hlo Professionals!

I want to display edit link button in front of gridview and also when i click on edit gridview row to be display in above textboxes.

here is my code

Web design

<div><%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Package.aspx.cs" Inherits="WebApplication14.Package" %></div> <div><asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server"></div><div></asp:Content></div> <div><asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server"></div> <div></asp:Content></div> <div><asp:Content ID="Content3" ContentPlaceHolderID="body" runat="server"></div><div>     <div style="margin-top:30px; margin-left:20px"></div> <div>        </div> <div>         <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager></div> <div>         <asp:UpdatePanel ID="UpdatePanel1" runat="server">         </div> <div>       <ContentTemplate></div> <div> </div> <div>                    <table></div> <div>               </div> <div>                 <tr></div> <div>                   <td colspan="4"><h1><strong style="color:black">Package</strong></h1>    </div> <div>                   <hr /></div> <div> </div> <div>                    </td></div> <div>                  </div> <div>                 </tr></div> <div>            </div> <div>     <tr></div> <div>                    <td><span style="color:black">Package Name</span><br /></div> <div>                   <asp:TextBox ID ="tb_name"  runat="server" Width="200px"   /><br /></div> <div>        </div> <div>      </div> <div>                    </td></div> <div> </div> <div>                  <td><span style="margin-left:25px; color:black">Reward<br /></span></div> <div>                    <span style="margin-left:25px"><asp:TextBox ID="tb_reward" runat="server"  Width="200px" /></span> <br /></div> <div>      </div><div>                   </td></div> <div>                     </div> <div>                    <td><span style=" margin-left:25px; color:black">Remarks</><br /></span></div> <div>                    <span style="margin-left:25px"><asp:TextBox ID="tb_remarks" runat="server" Width="410px" /></span> <br /></div> <div>      </div> <div>                    </td></div> <div>                  </div> <div>         </tr></div> <div> </div><div>                          </div> <div>     <tr>   <td>      <br /></div> <div>         <asp:Button ID="BT_submit" runat="server"  Text="Submit" style="border-radius:5px" Height="35px" Width="80px"   OnClick="BT_submit_Click" BackColor="#3366CC" BorderColor="#3366CC" ForeColor="White"  /></div> <div>       </div> <div>        <asp:Button ID="BT_update" runat="server"   Text="Update" style="border-radius:5px" Height="35px" Width="80px"   OnClick="BT_update_Click" BackColor="#3366CC" BorderColor="#3366CC" ForeColor="White" /></div> <div>      </td></div> <div>         </tr>          </div> <div>          </div> <div>         </table>          </div> <div>          </div> <div>    </div> <div> </div> <div> </div> <div>       <br /><asp:GridView runat="server" AutoGenerateColumns="False"     ID="Gv8" Width="80%" GridLines="Both" </div> <div>                          </div> <div>                           </div> <div>                            DataKeyNames="tbl_id" BackColor="White"   > </div> <div>                            <AlternatingRowStyle HorizontalAlign="Justify" Wrap="False" /></div> <div>                        <Columns></div> <div>                        </div> <div>                            </div> <div>                            </div> <div> </div><div>                          <asp:BoundField DataField="package_name" HeaderText="Package Name" /> </div> <div>                          <asp:BoundField DataField="reward" HeaderText="Reward" /> </div> <div>                         <asp:BoundField DataField="remarks" HeaderText="Remarks" /> </div> <div> </div> <div>                         <asp:TemplateField></div> <div>                                <ItemTemplate></div> <div>                                   <asp:LinkButton ID="Button1"  runat="server" Text="Edit" OnClick="Button1_Click" ></asp:LinkButton></div> <div> </div> <div>                                </ItemTemplate></div> <div> </div><div>                            </asp:TemplateField></div> <div> </div> <div>                         </Columns></div> <div> </div> <div>           </div> <div>                </div><div>                             </asp:GridView></div> <div>               </div> <div>            </ContentTemplate></asp:UpdatePanel>       </div> <div>    </div></div> <div> </div> <div>                  </div> <div> </div> <div></asp:Content></div>

C# Code

<div> </div> <div>using System;</div> <div>using System.Collections.Generic;</div> <div>using System.Linq;</div> <div>using System.Web;</div> <div>using System.Web.UI;</div> <div>using System.Web.UI.WebControls;</div> <div>using System.Data;</div> <div>using System.Data.SqlClient;</div> <div> </div> <div>namespace WebApplication14</div> <div>{</div> <div>    public partial class Package : System.Web.UI.Page</div> <div>    {</div> <div>        SqlCommand cmd = new SqlCommand();</div> <div>        SqlConnection con = new SqlConnection();</div> <div>        string connection = System.Configuration.ConfigurationManager.AppSettings["con"].ToString();</div> <div> </div> <div>        public void EstablishConnection(string storeprocedure)</div> <div>        {</div> <div>           con.ConnectionString = connection;</div> <div>            cmd.Connection = con;</div> <div>            cmd.Connection.Open();</div> <div>            cmd.CommandType = CommandType.StoredProcedure;</div> <div>           cmd.CommandText = storeprocedure;</div> <div>        }</div> <div> </div> <div>        public void CloseConnection()</div> <div>        {</div> <div>            cmd.Connection.Close();</div><div>            cmd.Connection.Dispose();</div> <div>            con.Close();</div> <div>        }</div> <div> </div> <div>        </div> <div>        public void Fillgridview()</div><div>        {</div> <div>            SqlDataAdapter adp = new SqlDataAdapter("select * from package", connection);</div> <div>            adp.SelectCommand.CommandType = CommandType.Text;</div> <div>            DataTable DT = new DataTable();</div> <div>            adp.Fill(DT);</div> <div> </div> <div>            Gv8.DataSource = DT;</div> <div>            Gv8.DataBind();</div> <div> </div><div>            </div> <div> </div> <div>        }</div> <div> </div> <div>        </div> <div> </div> <div> </div> <div>        protected void Page_Load(object sender, EventArgs e)</div> <div>        {</div> <div>            if (!Page.IsPostBack)</div> <div>            {</div> <div>                Fillgridview();</div> <div>                BT_update.Visible = false;</div> <div> </div> <div> </div> <div>            }</div> <div>        }</div> <div>        protected void Button1_Click(object sender, EventArgs e)</div> <div>        {</div><div>            LinkButton btn = (LinkButton)sender;</div> <div>            GridViewRow gvr = (GridViewRow)btn.NamingContainer;</div> <div>            tb_name.Text = gvr.Cells[0].Text;</div> <div>            tb_reward.Text = gvr.Cells[1].Text;</div> <div>            tb_remarks.Text = gvr.Cells[2].Text;</div> <div> </div> <div>            BT_update.Visible = true;</div> <div>            BT_submit.Visible = false;</div><div>        }</div> <div>        protected void BT_submit_Click(object sender, EventArgs e)</div> <div>        {</div> <div> </div> <div> </div> <div>            EstablishConnection("sp_insert_package");</div><div>            cmd.Parameters.Add("@package_name", SqlDbType.VarChar, 100).Value = tb_name.Text;</div> <div>            cmd.Parameters.Add("@reward", SqlDbType.VarChar, 255).Value = tb_reward.Text;</div> <div>            cmd.Parameters.Add("@remarks", SqlDbType.VarChar, 100).Value = tb_remarks.Text;</div> <div>            cmd.Parameters.Add("@date_time", SqlDbType.VarChar, 100).Value = System.DateTime.Now.ToString();</div> <div>            cmd.Parameters.Add("@By_whom", SqlDbType.VarChar, 100).Value = Session["username"].ToString();</div> <div>            cmd.Parameters.Add("@Status", SqlDbType.VarChar, 100).Value = "1";</div> <div> </div> <div> </div> <div> </div> <div>           try { cmd.ExecuteNonQuery(); }</div> <div>            catch (Exception ex1) { Response.Write("<script language=javascript>alert('" + ex1.Message.ToString() + ".')</script>"); }</div> <div> </div> <div>           Fillgridview();</div> <div> </div> <div>            CloseConnection();</div> <div> </div> <div>            </div> <div> </div> <div>        }</div> <div> </div><div>        </div> <div>        protected void BT_update_Click(object sender, EventArgs e)</div> <div>        {</div> <div>            decimal Tbl_id = Convert.ToDecimal(Gv8.DataKeys[0].Value.ToString());</div><div>            </div> <div> </div> <div>            EstablishConnection("sp_update_package");</div> <div>            cmd.Parameters.Add("@package_name", SqlDbType.VarChar, 100).Value = tb_name.Text;</div><div>            cmd.Parameters.Add("@reward", SqlDbType.VarChar, 255).Value = tb_reward.Text;</div> <div>            cmd.Parameters.Add("@remarks", SqlDbType.VarChar, 255).Value = tb_remarks.Text;</div> <div>            cmd.Parameters.Add("@tbl_id", SqlDbType.VarChar, 255).Value = Tbl_id.ToString();</div> <div> </div> <div> </div> <div> </div> <div>            try { cmd.ExecuteNonQuery(); }</div> <div>            catch (Exception ex1) { Response.Write("<script language=javascript>alert('" + ex1.Message.ToString() + ".')</script>"); }</div> <div> </div> <div>            Fillgridview();</div> <div> </div> <div>            CloseConnection();</div><div> </div> <div> </div> <div> </div> <div> </div> <div>        }</div> <div> </div> <div>       </div> <div> </div> <div>       </div> <div>   }</div> <div> </div> <div>}</div>

How to handle data in resource files programmatically?

$
0
0

Hi

I'm totally new at multilingual apps. I've applied this topic for multilingual core 2.1 mvc web app. successfully:

https://medium.com/swlh/step-by-step-tutorial-to-build-multi-cultural-asp-net-core-web-app-3fac9a960c43

But with creating and filling strings in resource files manually. But how to let the end-user to fill it by a form?

I searched a lot and thought I found the suitable topic:

https://docs.microsoft.com/en-us/dotnet/framework/resources/working-with-resx-files-programmatically

Am I right? or can you provide me other suitable topics please?

redirect to login page after session timeout

$
0
0

Hi,

I have set up the application to not be usable after a session time out:

Startup.cs

publicvoid ConfigureServices(IServiceCollection services)
{
     services = configureMiniProfiler(services);
     services.Configure<CookiePolicyOptions>(options =>
         {
               // This lambda determines whether user consent for non-essential cookies is needed for a given request.
       
options.CheckConsentNeeded = context =>true;
       
options.MinimumSameSitePolicy = SameSiteMode.None;
         });

      services.AddMvc()
                 .AddSessionStateTempDataProvider();

      services.AddSession(options =>
                   {
                          options.IdleTimeout = TimeSpan.FromSeconds(10);
                          options.Cookie.HttpOnly =true;
            
options.Cookie.Name =".ToolsAppSession";
          });

 services.ConfigureApplicationCookie(options =>
                 {
                        // Cookie settings
           
options.Cookie.HttpOnly =true;
           
options.ExpireTimeSpan = TimeSpan.FromSeconds(20);
                       options.LoginPath ="/Account/Login";
           
options.LogoutPath ="/Account/Login";
           
options.AccessDeniedPath ="/Account/AccessDenied";
           
options.SlidingExpiration =true;
          
options.Cookie.Name =".ToolsApp";
         
});

}

When the session time reaches expire time, any requests after that submits to the controller and hangs.

[Authorize]
publicclassInventoryController : BaseController
{

}

Is there a way I can redirect to login page after time out or on the request after time out?

Thanks,

tinac99

HttpClient and Core

$
0
0

I am trying to get an image size from a web site using HttpClient on Core Ver2.0.

I am doing :

private static readonly string browserVer = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36";
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", browserVer);
HttpResponseMessage response = await httpClient.gets(url); 

but when i check the Content-Length header but it not exist.

should i add some settings for the request.

RestAPI return fields under sppecific condition

$
0
0

I have a class which I return as per request

public class OutputModel
    {

        public string Id { get; set; }
        public int Status{ get; set; }
        public int Error{ get; set; }
       
    }

I want to return the Error property only in specific cases, else the user will get only the Id and Status.

is this possible?

Unable to cast object of type 'System.Byte' to type 'System.Int32' problems

$
0
0

I have a .NetCore Blazor App, morphed from the stock weather forecast service that comes with it, whereas I have players who log their play info, but once a player logs in and wants to look at their info via the stock “Fetch Data” link, the user cannot proceed as an Unable to cast object of type ‘System.Byte’ (not sure from what model property this stems from ) to type ‘System.Int32’. The user, upon registering , and logging in, is able to create/post a record (as it inserts into the database), but coming back to view their post, renders the Unhandled Exception.

In my wagtrakservice.cs class, I have the lineup intact:

///////

publicasync Task<List<Wagtrak>>

GetForecastAsync(string strCurrentUser)

{

// Get Weather Forecasts – player records

returnawait _context.Wagtrak

// Only get entries for the current logged in user

/// UserName is weatherforecast version, put Username inside Wagtrak table

.Where(x => x.UserName == strCurrentUser)

// Use AsNoTracking to disable EF change tracking

// Use ToListAsync to avoid blocking a thread

.AsNoTracking().ToListAsync();

}

public Task<Wagtrak>

CreateForecastAsync(Wagtrak objWagtrak)

{

_context.Wagtrak.Add(objWagtrak);

_context.SaveChanges();

return Task.FromResult(objWagtrak);

}

public Task<bool>

UpdateForecastAsync(Wagtrak objWagtrak)

{

var ExistingWagtrak =

_context.Wagtrak

.Where(x => x.WID == objWagtrak.WID)

.FirstOrDefault();

if (ExistingWagtrak != null)

{

ExistingWagtrak.Gamedate =

objWagtrak.Gamedate;

ExistingWagtrak.TeamH =

objWagtrak.TeamH;

ExistingWagtrak.TeamV =

objWagtrak.TeamV;

ExistingWagtrak.ptsHome =

objWagtrak.ptsHome;

ExistingWagtrak.ptsVisitor =

objWagtrak.ptsVisitor;

ExistingWagtrak.LinePlay =

objWagtrak.LinePlay;

ExistingWagtrak.DaPlay =

objWagtrak.DaPlay;

ExistingWagtrak.LineClose =

objWagtrak.LineClose;

ExistingWagtrak.Payout =

objWagtrak.Payout;

ExistingWagtrak.Summary =

objWagtrak.Summary;

_context.SaveChanges();

}

////////

DDL for the SQL table:

CREATETABLE [dbo].[Wagtrak](

[WID] [int]IDENTITY(1,1)NOTNULL,

[UserName] [varchar](50)NULL,

[Gamedate] [date]NULL,

[ptsHome] [tinyint]NULL,

[ptsVisitor] [tinyint]NULL,

[LinePlay] [numeric](18, 1)NULL,

[TotalPlay] [numeric](18, 1)NULL,

[Payout] [int]NULL,

[Summary] [nvarchar](max)NULL,

[TeamH] [varchar](20)NULL,

[TeamV] [varchar](20)NULL,

[DaPlay] [varchar](20)NULL

///////////

the context class has this lineup with appears to be correct assigns from model to Entity properties:

///////////

protectedoverridevoid OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.HasAnnotation("ProductVersion","2.2.0-rtm-35687");

modelBuilder.Entity<Wagtrak>(entity =>

{

/* see endtoendcontext.cs endtoend2 pjc for carinventorysho to mirror how we call

the primary key (WID) in this case */

entity.HasKey(e => e.WID);

entity.Property(e => e.WID).HasColumnName("WID");

entity.Property(e => e.Gamedate).HasColumnType("datetime");

entity.Property(e => e.TeamH).HasMaxLength(20)

.IsUnicode(false);

entity.Property(e => e.TeamV).HasMaxLength(20)

.IsUnicode(false);

entity.Property(e => e.ptsHome).HasColumnType("int")

.IsUnicode(false);

entity.Property(e => e.ptsVisitor).HasColumnType("int")

.IsUnicode(false);

entity.Property(e => e.LineClose).HasColumnType("decimal(18, 0)")

.IsUnicode(false);

entity.Property(e => e.LinePlay).HasColumnType("decimal(18, 0)")

.IsUnicode(false);

entity.Property(e => e.Payout).HasColumnType("int")

.IsUnicode(false);

entity.Property(e => e.DaPlay).HasMaxLength(20)

.IsUnicode(false);

/// HasColumnType entity.Property(e => e.Summary).HasMaxLength(1000);

entity.Property(e => e.Summary).HasColumnType("nvarchar(max)")

.IsUnicode(false);

entity.Property(e => e.UserName).HasMaxLength(50);

});

OnModelCreatingPartial(modelBuilder);

}

//////////

..since the Summary column is a nvarchar(max) , I believe this is how it should be assigned …

Thanks in advance

Ned

Date control is not showing value from model

$
0
0

I have this code

    [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Captura este campo")]
        public DateTime? BirthDate { get; set; }
<div class="form-group"><label asp-for="BirthDate" class="control-label"></label><input asp-for="BirthDate"  asp-format="{0:dd/MM/yyyy}" value="@Model.BirthDate" class="form-control" /><span asp-validation-for="BirthDate" class="text-danger"></span></div>

Im sure model is retrieving value in the right format , but is not showing in the control, so everytime i am updating the object, i must to select date again.


Field not rendering across 3 table relationship

$
0
0

Hi So I am using ASP.NET Core 2.2 with EF Core with SQL Server DB. I got a database that looks like this. So I have 3 tables in SQL Server. tblJobs, tblResults and tblProblems and others I omitted as they are not part of the problem.

Entity Relationship Diagram and gif demo of problem

I am attempting to read related data across these three tables. I am using Eager Loading to read the model field "Job.JobTitle" in the "ProblemsController.Index" method with this tutorial. https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-2.2

I decided to manually insert in a query window into Result table the JobID matching the JobTitle I wanted with the ProblemID. It has now rendered the correct JobTitle in the Problem Index view record which is the value of "Pitcher". But that's only because I manually inserted it in tblResult which doesn't really help the end user. I'm wondering what's a way of them getting past that manual insertion.

Here is the my TeamContext class.

using Pitcher.Models;
using Microsoft.EntityFrameworkCore;
using Pitcher.Models.TeamViewModels;

namespace Pitcher.Data
{
    public class TeamContext : DbContext
    {
        public TeamContext(DbContextOptions<TeamContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Registration> Registrations {get;set;}
        public DbSet<Job> Jobs {get;set;}     

        public DbSet<Problem> Problems { get; set; }   

        public DbSet<Result> Results {get;set;}
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("tblUser");
            modelBuilder.Entity<Registration>().ToTable("tblRegistration");
            modelBuilder.Entity<Job>().ToTable("tblJob");
            modelBuilder.Entity<Problem>().ToTable("tblProblem");
            modelBuilder.Entity<Chat>().ToTable("tblChat");
            modelBuilder.Entity<Result>().ToTable("tblResult");

            modelBuilder.Entity<Result>()
                .HasKey(bc => new { bc.JobID, bc.ProblemID });
            modelBuilder.Entity<Result>()
                .HasOne(bc => bc.Job)
                .WithMany(b => b.Results)
                .HasForeignKey(bc => bc.JobID);
            modelBuilder.Entity<Result>()
                .HasOne(bc => bc.Problem)
                .WithMany(c => c.Result)
                .HasForeignKey(bc => bc.ProblemID);
        }        
    }
}

Here are the 3 models.

Job model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Job
    {        
        
        public int ID { get; set; }

        [Required]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Job Title must be bettween 3 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Job Title")]
        [Column("JobTitle")]
        public string JobTitle { get; set; }

        [StringLength(200, MinimumLength = 3, ErrorMessage = "Job Description must be bettween 200 to 3 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Description")]
        [Column("JobDescription")]
        public string JobDescription { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = " Start Date")]
        [Column("JobStartDate")]
        public DateTime JobStartDate {get;set;}

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Deadline Date")]
        [Column("JobDeadlineDate")]
        public DateTime JobDeadline {get;set;}

        [Display(Name = "Job Is Complete?")]
        [Column("JobIsComplete")]
        public bool JobIsComplete{get;set;}

        public ICollection<Registration> Registrations {get;set;}

        public ICollection<Result> Results {get;set;}
    }
}

Result model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Pitcher.Models
{
    public class Result
    {        
        public int JobID {get;set;}
        
        public int ProblemID {get;set;}
        public Job Job {get;set;}
        public Problem Problem {get;set;}

    }
}

Problem model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Problem
    {
        public int ID {get;set;}
        
        [Required]
        [StringLength(180, MinimumLength = 2, ErrorMessage = "Problem Title must be bettween 2 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Problem Title")]
        [Column("ProblemTitle")]
        public string ProblemTitle {get;set;}

        [Required]
        [StringLength(int.MaxValue, MinimumLength = 5, ErrorMessage = "Problem Title must be at least 5 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Problem Description")]
        [Column("ProblemDescription")]
        public string ProblemDescription {get;set;}

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = " Problem Start Date")]
        [Column("ProblemStartDate")]
        public DateTime ProblemStartDate {get;set;}

        [DataType(DataType.Upload)]
        [Display(Name = " Upload file")]
        [Column("ProblemFileAttachments")]
        public string ProblemFileAttachments {get;set;}

        [Required]
        [Display(Name = "Problem Severity")] 
        [Range(1,5, ErrorMessage
             = "Problem Severity value for {0} must be between {1} and {2}.")]       
        [Column("ProblemSeverity")]
        public int ProblemSeverity {get;set;}

        [Display(Name = "Problem Complete")]        
        [Column("ProblemComplete")]        
        public bool ProblemComplete {get;set;}
        public ICollection<Result> Result {get;set;}

        public ICollection<Chat> Chat {get;set;}
    }
}

Here are the 2 Controllers I'm using with their Index methods only.

Job Index controller method:

        public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["JobTitleSortParm"] = sortOrder == "JobStartDate" ? "JobTitle_desc" : "JobStartDate";
            ViewData["JobStartDateSortParm"] = sortOrder == "JobStartDate" ? "JobStart_date_desc" : "JobStartDate";
            ViewData["JobDeadlineDateSortParm"] = sortOrder == "JobDeadlineDate" ? "JobDeadline_date_desc" : "JobDeadlineDate";
            ViewData["CurrentFilter"] = searchString;
            var jobs = from j in _context.Jobs
                        select j;

            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }


            if (!String.IsNullOrEmpty(searchString))
            {
                jobs = jobs.Where(j => j.JobTitle.Contains(searchString)
                                    || j.JobDescription.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "JobTitle_desc":
                    jobs = jobs.OrderByDescending(j => j.JobTitle);
                    break;
                case "JobStartDate":
                    jobs = jobs.OrderBy(j => j.JobStartDate);
                    break;
                case "JobStart_date_desc":
                    jobs = jobs.OrderByDescending(j => j.JobStartDate);
                    break;
                case "JobDeadline_date_desc":
                    jobs = jobs.OrderByDescending(j => j.JobDeadline);
                    break;
                case "JobDeadlineDate":
                    jobs = jobs.OrderBy(j => j.JobDeadline);
                    break;
                //By default JobTitle is in ascending order when entity is loaded. 
                default:
                    jobs = jobs.OrderBy(j => j.JobTitle);
                    break;                    
            } 

            int pageSize = 20;
            return View(await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), pageNumber ?? 1, pageSize));
        }

Problem Index controller method:

public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["ProblemIDSortParm"]  = sortOrder == "ProblemID" ? "ProblemID_desc" : "ProblemID";
            ViewData["ProblemTitleSortParm"] = sortOrder == "ProblemTitle" ? "ProblemTitle_desc" : "ProblemTitle";
            ViewData["ProblemStartDateSortParm"] = sortOrder == "ProblemStartDate" ? "ProblemStartDate_desc" : "ProblemStartDate";
            ViewData["ProblemSeveritySortParm"] = sortOrder == "ProblemSeverity" ? "ProblemSeverity_desc" : "ProblemSeverity";
            ViewData["ProblemCompleteSortParm"] = sortOrder == "ProblemComplete" ? "ProblemComplete_desc" : "ProblemComplete";          
            ViewData["CurrentFilter"] = searchString;
            //READ RELATED DATA HERE
            var problems = from p in _context.Problems 
                            .Include(p => p.Result)
                                .ThenInclude(j => j.Job)                                                     
                                select p;
            //END OF READ RELATED DATA
            if(searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            if(!String.IsNullOrEmpty(searchString))
            {
                problems = problems.Where(p => p.ProblemTitle.Contains(searchString)
                                            || p.ProblemDescription.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "ProblemID_desc":
                    problems = problems.OrderByDescending(p => p.ID);
                    break;
                case "ProblemTitle_desc":
                    problems = problems.OrderByDescending(p => p.ProblemTitle);
                    break;
                case "ProblemTitle":
                    problems = problems.OrderBy(p => p.ProblemTitle);
                    break;
                case "ProblemStartDate":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemStartDate_desc":
                    problems = problems.OrderByDescending(p => p.ProblemStartDate);                    
                    break;
                case "ProblemSeverity":
                    problems = problems.OrderBy(p => p.ProblemSeverity);
                    break;
                case "ProblemSeverity_desc":
                    problems = problems.OrderByDescending(p => p.ProblemSeverity);
                    break;   
                case "ProblemComplete":
                    problems = problems.OrderBy(p => p.ProblemComplete);
                    break;
                case "ProblemComplete_desc":
                    problems = problems.OrderByDescending(p => p.ProblemComplete);
                    break; 
                default:
                    problems = problems.OrderBy(p => p.ID);
                    break;                 
            }

            int pageSize = 20;            
            return View(await PaginatedList<Problem>.CreateAsync(problems.AsNoTracking(), pageNumber ?? 1, pageSize));
        }

And the Index view for Problem:

@model PaginatedList<Pitcher.Models.Problem>

@{
    ViewData["Title"] = "Problems";
}<h1>Problems</h1><p><a asp-action="Create">Create New</a></p>
 @*COPY AND PASTE THIS TAG HELPER METHOD TEXTBOX CUSTOMIZATION INTO OTHER VIEWS TO ENABLE SEARCHING.*@<form asp-action="Index" method="get"><div class="form-actions no-color"><p>
            Find by name: <input type="text" name="SearchString" value="@ViewData["currentFilter"]" /><input type="submit" value="Search" button type="button" class="btn btn-primary" /> |<a asp-action="Index">Back to Full List </a></p></div></form><table class="table table-hover"><thead><tr><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemIDSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem ID</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemTitleSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Title</a></th><th>
                Description</th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemStartDateSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Start Date</a></th><th>
                Problem File Attachments</th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemSeveritySortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemSeverity</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemCompleteSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemComplete</a></th><th>
                Job Title</th><th></th></tr></thead><tbody>
@foreach (var item in Model) {<tr><td>
                @Html.DisplayFor(modelItem => item.ID)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemTitle)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemDescription)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemStartDate)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemFileAttachments)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemSeverity)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemComplete)</td><td>
                @foreach (var title in item.Result)
                {
                    @Html.DisplayFor(modelItem => title.Job.JobTitle)<br />
                }</td><td><a asp-action="Edit" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block" >Edit</a> <a asp-action="Details" asp-route-id="@item.ID" button type="button" class="btn btn-info btn-block">Details</a> <a asp-action="Delete" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block">Delete</a></td></tr>}</tbody></table>
@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}<a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex - 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @prevDisabled"
   button type="button">
    Previous</a><a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex + 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @nextDisabled"
   button type="button">   
    Next</a>

Kind regards,

Jordan Nash

Controller export to .csv failed for IE

$
0
0

Hi,

Why IE can't pop up the file csv to save?


//Download the CSV file.

Response.Clear();

Response.Buffer =true;

Response.AddHeader("content-disposition","attachment; filename="+ module.Replace(" ","_") +".csv");

Response.Charset ="";

Response.ContentType ="text/csv"; 

StringBuilder sb =new StringBuilder();
:
:

Response.Output.Write(sb.ToString());

Response.Flush();

Response.End();

Please advise.

Thanks

Regards,

Micheale

Unable to Access ViewData to another Action result

$
0
0

Hi All,

I am unable to Access ViewData["RegionData"] to another actionResult, Below is my code using ASP.NET Core 3.1 MVC

 [Route("DataUpload/[Controller]/{id}")]
        public async Task<IActionResult> Index(int id)
        {            
            IEnumerable<Entity> se;

            HttpClient client = _api.GetRegionMeter();

            HttpResponseMessage responseTask = await client.GetAsync("webscrape/" + id);


            if (responseTask.IsSuccessStatusCode)
            {
                var readTask = responseTask.Content.ReadAsAsync<IList<Entity>>();              
                readTask.Wait();
                se = readTask.Result;
                ViewData["RegionData"] = se;


            }
            else
            {
                se = Enumerable.Empty<Entity>();
                ModelState.AddModelError(string.Empty, "Error");
            }

            
        
            return View(se);


        }




        [HttpPost]
        public IActionResult Upload()
        {
            if(ViewData["RegionData"] != null)
            {
                Entity entity = (Entity)ViewData["RegionData"];
            }

            return View("Index");
        }

ViewData["RegionData"] is coming as Null

CSHTML

@using (Html.BeginForm("Upload", "RegionMeter", FormMethod.Post, new { enctype = "multipart/form-data"}))
 {<div class="row"><div class="col-6"><div class="page-title-box"><h4 class="page-title">Region Meter</h4></div></div><div class="col-6"><button id="newAlertBtn" type="submit"
                class="btn btn-success waves-effect waves-light float-right mt-3">
            Upload</button></div></div>
}

Thanks,

Shabbir

Azure AD Authentication Back Button Issues

$
0
0

I am trying to resolve an issue with ASP.NET in regards to how it facilitates authentication against Azure AD.  Overall I am able to successfully authenticate, however there are seemingly unavoidable issues when the user presses the back button.  Specifically, the user eventually sees a series of error related pages as described further below.

The steps below are what can be taken to replicate the issue, followed by the error pages themselves.

1) Visual Studio 2019 16.5.4 > Create New Project > ASP.NET Core Web Application > [Provide details such as project name] > Create > .NET Core, ASP.NET Core 3.1, Web Application, Authentication configured for Work or School Accounts and Cloud - Single Organization> Create.

2) All items in Startup.cs, appsettings.json, and the Azure Active Directory App Registration are all kept at their respective defaults.  I have provided the Startup.cs code further below if that is of any interest.

3) Run application (debugging or not), authenticate, arrive at default page.  Pressing the back button repeatedly results in the following:
First, Document Expired Browser page
Second, Accepts POST requests only Azure page
Third, Application error page (technically this can be handled by defining custom error event handling code demonstrated further below).

My question is whether or not there is a means of avoiding the error related pages.  Ideally, when the user presses the back button they would avoid being returned to any authentication related pages and the browser will take them to whatever page they may have been on prior to the authentication process beginning.  Part of what amplifies the issue is that users are sometimes unable to simply keep pressing the back button in order to get to the pre-authentication related pages due to being automatically redirected to the authentication process.

Also note that I am trying to avoid manually redirecting users to a specific page given users may come from a variety of locations.  For example, some users may initially come from a home page that doesn't require authentication, whereas others may be at entirely different location by the use of bookmarks.

Finally, the exact error related pages that display will vary based on the browser used.  For this demonstration I am using FireFox.  Chrome has similar issues.

Thanks

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ASPNETFormAuthenticationDemoDotNetCore
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
				.AddAzureAD(options => Configuration.Bind("AzureAd", options));

			services.AddRazorPages().AddMvcOptions(options =>
			{
				var policy = new AuthorizationPolicyBuilder()
					.RequireAuthenticatedUser()
					.Build();
				options.Filters.Add(new AuthorizeFilter(policy));
			});
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseExceptionHandler("/Error");
				// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
				app.UseHsts();
			}

			app.UseHttpsRedirection();
			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthentication();
			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapRazorPages();
				endpoints.MapControllers();
			});
		}
	}
} 


Startup.cs Error Event Handling

	services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
	{
		options.Events = new OpenIdConnectEvents
		{
			OnAuthenticationFailed = context =>
			{
                           ...
			},

			OnRemoteFailure = context =>
			{
                           ...
			}
		};
         });

Validation not showing in Jquery Modal Popup

$
0
0

I am using .net core but my validation is not showing in my popup I use the same dialog for new and edit so need to be carefull it works the same

<div><form id="myForm"><div class="panel-body bootstrap-padding-overide">
            @Html.ValidationSummary(false, null, new { @id = "ValidationSummary", @class = "validationErrorBox" })</div>

        @Html.HiddenFor(m => m.Id)
        @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @placeholder = "Name" })<span asp-validation-for="Name" class="text-danger"></span>


        @Html.TextBoxFor(model => model.Resitance, new { @class = "form-control", @placeholder = "Address" })<span asp-validation-for="Resitance" class="text-danger"></span>

        @Html.TextBoxFor(model => model.Passed, new { @class = "form-control", @placeholder = "Passed" })<span asp-validation-for="Passed" class="text-danger"></span><select asp-for="CirtcutType"
                asp-items="@Html.GetEnumSelectList(typeof(ElectricalSurvey.DAL.Models.CircuitModel.CirtcutTypes))"
                class="form-control"></select><div class="modal-footer"><button type="submit" id="btnSubmit" class="btn btn-primary" data-save="modal">@if (Model.Id > 0) {<span>Update</span> } else {<span>Save</span>} </button><button type="button" class="btn btn-default" data-dismiss="modal">lose</button></div></form><div style="text-align:center;display:none" id="loaderDiv"><img src="~/Content/InternetSlowdown_Day.gif" width="150" /></div></div>

The form displays fine but its not showing the validation tags its just closing the model

<script>$(document).ready(function () {$("#btnSubmit").click(function () {$("#loaderDiv").show();
            var myformdata = $("#myForm").serialize();$.ajax({

                type: "POST",
                url: "/Electrician/SaveCircuit",
                data: myformdata,
                success: function () {$("#loaderDiv").hide();$("#MyEditUpateModal").modal("hide");
                    window.location.href = "/Electrician/Index";

                }

            })
        })

    })


</script>

My Validation Scripts Partial has the following references 

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"
integrity="sha256-F6h55Qw6sweK+t7SiOJX+2bpSAa3b/fnlrVCJvmEj1A="
crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.9/jquery.validate.unobtrusive.min.js"
integrity="sha256-paoxpct33kY9fpQlvgC8IokjGq8iqYaVFawgFPg8oz0="
crossorigin="anonymous"></script>



Cannot retrieve image which has http in its url.

$
0
0

Hi, guys, I'm new to asp.net core. I want to show some images on my site but the images are over unsecured connection for examplehttp://image.png . If I write this absolute link inside image tag asp.net make a request to HTTPS instead of HTTP thus returning 402 error. How can i solve this?

Return Not Found From Controller

$
0
0

Hi,
in startup.cs i use this code to manage errors (404 , 500 , ...)
and its worked correctly when i search a action thats not found and go to error action .

  app.UseStatusCodePagesWithReExecute("/"+CultureInfo.CurrentCulture.Name+"/errors/{0}");




but in controller when a id is not exsist i use this code

return NotFound();

but its not work i want when i use NotFound its return to error action 


Create Customize NotFound Method

$
0
0

Hi 
i want create methods for my customize example : 


return NotFound();


i write this method but i cant call it in other controller just i cant use in own  controller 

 public IActionResult NotFound1()
        {
            return View("NotFound");
        }




how to create public method (exmaple : return Notfound()) ?

Difference in running Asp.net Core app in docker vs iis

$
0
0

I just created a sample api project and ran it inside of a container using docker commands and even created a custom image of the sample app. I am a beginner and am a bit confused right now as how is my app running inside of a container that contains just the runtime and dotnet specific images but no IIS. I used to think that Asp.net core web app requires a server and that could be either IIS or Kestrel but in my case I didn't have any of those. I ran my app in both Linux and Windows container. While in Linux container, I thought maybe behind the scenes Kestrel would be running but that shouldn't be the case in Windows container or maybe I am wrong all together.

So I just want to know how are the thing running in containers without a server? Also if possible can you please point me to articles explaining difference in performance as well

Solving the problem of slow query in my efcore.

$
0
0

So I built an inventory application. I occasionally experience slow queries when retrieving data. This got me worried cos the client is complaining.

So I would paste one of the major query returning slow data.

 public async Task<IEnumerable<Customer>> Getcustomers()
        {
            var customers = await this.context.Customers.Include(item => item.Customercategory).Include(item=>item.Customercontact).Include(item=>item.Sex).ToListAsync<Customer>();

            return customers;
        }

It takes close to 10 seconds to return data.

Please how do I speeding up my queries when displaying or pulling data from the database. I experience this on just a 100 records.

Thanks alot.

List inside another list

$
0
0

Hi,

How to pass a list of data inside another list in the DAL o the stored procedure in c#

how can I add important master data if not record there while running the application

$
0
0

Hi

How  to insert the  record automatically into the master tables automatically  if there is no record while running the application.  At the moment I am doing given way but it only works while running database migration time.  I want to fill the record into master table for necessary drop down list .the record should be inserted only if there is no any record exist on the table VehicleStatus,VehicleType. Please  help

public VehicleDBContext(DbContextOptions<VehicleDBContext> options) : base(options)
        {

        }
        public DbSet<Vehicles> Vehicles { get; set; }
        public DbSet<VehicleStatus> VehicleStatus { get; set; }
        public DbSet<VehicleType> VehicleType { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<VehicleStatus>()
                .HasData(new
                {
                    Id = 1,
                    Status = "Active"
                }, new
                {
                    Id = 2,
                    Status = "Sold"
                }, new
                {
                    Id = 3,
                    Status = "Scrapped"
                });


            builder.Entity<VehicleType>()
                .HasData(new
                {
                    Id = 1,
                    Category = "Car"

                }, new
                {
                    Id = 2,
                    Category = "Van"
                }, new
                {
                    Id = 3,
                    Category = "SUV"
                });
        }

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>