Subscribe: Web Forms
http://forums.asp.net/rss.aspx?ForumID=18
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
add  ado net  app  calendar  cookie  database  model  net  new  public  string  system web  system  web system  web 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Web Forms

All Forums



All Forums



Last Build Date: Sat, 29 Apr 2017 00:22:08 -0700

 



local storage with mvc 5

2017-04-28T02:09:50.73-07:00

hi,

I require to use the local storage and I want to use it in my MVC5 application. 

https://github.com/marcuswestin/store

guidance ?




External login error ASP Identity C#

2017-04-29T06:50:46.833-07:00

 I have a standard ASP web app using standard ASP Identity. I cannot seem to authenticate with facebook I keep getting this error: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. My Startup.Auth public partial class Startup { // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext(ApplicationUserManager.Create); app.CreatePerOwinContext(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); app.UseFacebookAuthentication( appId: "My APP ID", appSecret: "My Secret" ); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); } } The OAuth redirect URI I use in my facebook app is as follows: http://exampledomain.com/account/externalcallback The External Callback method is the standard version from asp identity: // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this exter[...]



[MVC Core] BaseControoler: Header + Footer

2017-04-27T21:59:52.133-07:00

Hello guys,

Thank you for your help, I am starting to learn ASP.NET Core. :)

I started my web application without ASP.NET Core, but right now I prefer to upgrade to Visual Studio 2017 + Core.

I am facing one single problem: All my pages should inherit my header and footer views. And both of them have Models, and their Models aren't just text (for example, in the header I need to show notifications to the user).

In the current project - working like a charm - I have this BaseController:

 public class BaseController : Controller
  {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var model = filterContext.Controller.ViewData.Model as BaseViewModel;

            if (model != null)
            {
                model.HeaderModel = this.getHeaderModel();
                model.FooterModel = this.getFooterModel();
            }
        }

        protected HeaderModel getHeaderModel()
        {
            HeaderModel model = new HeaderModel()
            {
                //...
            };
            return model;
        }

        protected FooterModel getFooterModel()
        {
            FooterModel model = new FooterModel()
            {
                //...
            };
            return model;
        }
}

My BaseViewModel:

    public class BaseViewModel
    {
        public HeaderModel HeaderModel { get; set; }
        public FooterModel FooterModel { get; set; }
    }

My Controllers inherit BaseController and return some View(model) [model inherit BaseViewModel].

With that in mind, I can populate my header and footer views.

@model Dashboard.Models.Dashboard.BaseViewModel




....



    
@{ Html.RenderPartial("_Header", Model.HeaderModel); } @RenderBody() @{ Html.RenderPartial("_Footer", Model.FooterModel); }

In ASP.NET Core I can not use:

            var model = filterContext.Controller.ViewData.Model as BaseViewModel;

What are your advice? Do you have any example I can follow?

Best regards,
Nelson.

EDIT: I am interested in following the best practises.




Dynamically Add a User Control to a Dynamically Created PlaceHolder

2017-04-26T03:36:01.79-07:00

I have the following code in which I can add multiple placeholder to the page and then each button click will add the user control to these placeholder based on number of button clicks. But, this is not the way I want it to be since there could be unknown number of button clicks and I may not have enough placeholders already in place.

How do I get this done dynamically and then read data from the controls in each user control?

protected void Button1_Click(object sender, EventArgs e)
        {
            LiteralControl lit = new LiteralControl("Test Literal Control");
            Page.Controls.Add(lit);
            PlaceHolder ph_grid = new PlaceHolder();
            Page.Controls.Add(ph_grid);

            ucWebApp myControl = (ucWebApp)Page.LoadControl("~/ucWebApp.ascx");
            PlaceHolder2.Controls.Add(myControl);

            ucWebApp myControl = (ucWebApp)Page.LoadControl("~/ucWebApp.ascx");
            PlaceHolder3.Controls.Add(myControl);

        }
protected void Page_Load(object sender, EventArgs e)
        {
            ucWebApp myControl = (ucWebApp)Page.LoadControl("~/ucWebApp.ascx");
            //myControl.Location = new Point(25, 25);
            PlaceHolder1.Controls.Add(myControl);
        }






SSRS report connection credentials

2017-04-29T05:32:07.177-07:00

Hi
Here's my problem:
I have an application in ASP.net using VB, it contains a SSRS report that I build and deploy it to the SSRS Server at our provider.
The report is working perfectly.
The problem is the first time I try to access the Report it asks for the Server Credentials, if I enter the username + password (wich is not logical), it will go after that each time I access it, if I use the link directly or from the application.
I'm accessing the report from my code:

Dim strReportAddress As String = "http://xxx.xxx.xxx.xxx/Reports/Pages/ReportViewer.aspx?/myReports/ClientOrder&rc:Parameters=false&rs:Command=Render&Item=1"
Response.Write("")

HELP...




Help Delete Cookie

2017-04-29T05:05:00.603-07:00

My cookie is not deleting. Here is my code

private void ReadCookie()
    {
        try
        {
            HttpCookie Cookie = new HttpCookie("sg_art_pack");
            Cookie = Request.Cookies["sg_art_pack"];

            if (Cookie != null)
            {
                _ArtPack = Request.Cookies["sg_art_pack"]["ArtPack"];
                _Business = Request.Cookies["sg_art_pack"]["Business"];
                _ItemName = Request.Cookies["sg_art_pack"]["ItemName"];
                _ItemID = Request.Cookies["sg_art_pack"]["ItemID"];
                _ItemAmount = Convert.ToDouble(Request.Cookies["sg_art_pack"]["ItemAmount"]);
            } 
        }
        catch(Exception ex)
        {

        }
    }

    private void CreateCookie()
    {
        try
        {
            HttpCookie Cookie = new HttpCookie("sg_art_pack");
            Cookie["ArtPack"] = _ArtPack;
            Cookie["Business"] = _Business;
            Cookie["ItemName"] = _ItemName;
            Cookie["ItemID"] = _ItemID;
            Cookie["ItemAmount"] = Convert.ToString(_ItemAmount);
            Cookie.Expires = DateTime.Now.AddDays(1d);
            Response.Cookies.Add(Cookie);
        }
        catch(Exception ex)
        {

        }
    }

    private void DeleteCookie()
    {
        try
        {
            if (Request.Cookies["sg_art_pack"] != null)
            {
                HttpCookie Cookie = new HttpCookie("sg_art_pack");
                Cookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(Cookie);
            }
        }
        catch(Exception ex)
        {

        }
    }




one form and multiple submit buttons

2017-04-28T00:43:08.71-07:00

Hi,

I have an application in MVC5.

I am facing an issue.

I have a form and in that form there are multiple buttons.

now when I click on any form field like textbox and press the enter button system prompts a dialog box every time. I am trying to fix it with less effort.

any guidance ?

  




WebGrid apply common style to all tables

2017-04-29T04:51:48.423-07:00

Borrowers Applied

@pg.GetHtml( tableStyle: "webgrid-table", headerStyle: "webgrid-header", footerStyle: "webgrid-footer", alternatingRowStyle: "webgrid-alternating-row", selectedRowStyle: "webgrid-selected-row", rowStyle: "webgrid-row-style", columns: pg.Columns( pg.Column(columnName: "Id", header: "Entry ID", format: (item) => item.GetSelectLink(item.Id.ToString())), pg.Column(columnName: "DateApplied", header: "Entry Date"), pg.Column(columnName: "FullName", header: "Full Name"), ) )

Borrowers Applied

@pg.GetHtml( tableStyle: "webgrid-table", headerStyle: "webgrid-header", footerStyle: "webgrid-footer", alternatingRowStyle: "webgrid-alternating-row", selectedRowStyle: "webgrid-selected-row", rowStyle: "webgrid-row-style", columns: pg.Columns( pg.Column(columnName: "ContactNumber", header: "Contact number"), pg.Column(columnName: "Gender") ) )

How can I simplify this code without repeating the general style classes?




MVC/Word press SSO

2017-04-29T04:21:53.647-07:00

I have an existing site that has implemented user management, and I am standing up a wordpress site for forums. I need Single Sign On (SSO) between the two sites. Researching WordPress it appears that OAUTH is my best bet for a SSO implementation. However, I can find plenty of examples of implementing OAUTH in asp.net/mvc to allow sign in with a third party, but I've not found any examples of how to be the third party.

I need my site to manage the users, and pass the required OAUTH data to WordPress, any one able/willing to point me in the right direction?

Thanks
Wayne




An unhandled win32 exception occurred in w3wp.exe

2017-04-19T09:34:31.603-07:00

Error: Visual Studio Just-In-Time Debugger An unhandled win32 exception occurred in w3wp.exe [xxxxx]. (xxxx is process id) Event Log: Error Faulting application name: w3wp.exe, version: 7.5.7601.17514, time stamp: 0x4ce7a5f8 Faulting module name: MSVCR80.dll, version: 8.0.50727.6195, time stamp: 0x4dcddbf3 Exception code: 0xc000000d Fault offset: 0x00008aa0 Faulting process id: 0x2f3c Faulting application start time: 0x01d2ac5bb8040b06 Faulting application path: C:\Windows\SysWOW64\inetsrv\w3wp.exe Faulting module path: C:\Windows\WinSxS\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_d09154e044272b9a\MSVCR80.dll Report Id: f8bce81f-184e-11e7-9e9d-5065f31c7987 Warn A process serving application pool 'MyAppPool' suffered a fatal communication error with the Windows Process Activation Service. The process id was 'xxxxx'. The data field contains the error number.IIS Debug Diagnostics Tool 2: In w3wp__MY_WEBSERVICE___PID__12168__Date__04_19_2017__Time_03_19_30PM__500__First chance exception 0XE06D7363.dmp the assembly instruction at KERNELBASE!RaiseException+58 in C:\Windows\System32\KERNELBASE.dll This exception originated from msvcr80!_CxxThrowException. has caused an unknown exception (0xe06d7363) on thread 25 This exception originated from msvcr80!_CxxThrowException+46. 
Thread 25 - System ID 8908
Entry point   mscorwks!Thread::intermediateThreadProc Create time   19/4/2017 15:19:28 Time spent in user mode   0 Days 00:00:00.109 Time spent in kernel mode   0 Days 00:00:00.000 This thread is not fully resolved and may or may not be a problem. Further analysis of these threads may be required.
.NET Call Stack [[HelperMethodFrame_1OBJ] (System.RuntimeTypeHandle._GetTypeByName)] System.RuntimeTypeHandle._GetTypeByName(System.String, Boolean, Boolean, Boolean, System.Threading.StackCrawlMarkByRef, Boolean) mscorlib_ni!System.RuntimeTypeHandle.GetTypeByName(System.String, Boolean, Boolean, Boolean, System.Threading.StackCrawlMark ByRef) mscorlib_ni!System.RuntimeType.PrivateGetType(System.String, Boolean, Boolean, Boolean, System.Threading.StackCrawlMark ByRef) mscorlib_ni!System.Type.GetType(System.String) System_ni!System.CodeDom.Compiler.CompilerInfo.get_IsCodeDomProviderTypeValid() System_Web_ni!System.Web.Compilation.CompilationUtil.GetRecompilationHash(System.Web.Configuration.CompilationSection) System_Web_ni!System.Web.Configuration.CompilationSection.get_RecompilationHash() System_Web_ni!System.Web.Compilation.BuildManager.CheckTopLevelFilesUpToDate2(System.Web.Compilation.StandardDiskBuildResultCache) System_Web_ni!System.Web.Compilation.BuildManager.CheckTopLevelFilesUpToDate(System.Web.Compilation.StandardDiskBuildResultCache) System_Web_ni!System.Web.Compilation.BuildManager.RegularAppRuntimeModeInitialize() System_Web_ni!System.Web.Compilation.BuildManager.Initialize() System_Web_ni!System.Web.Compilation.BuildManager.InitializeBuildManager() System_Web_ni!System.Web.HttpRuntime.HostingInit(System.Web.Hosting.HostingEnvironmentFlags) System_Web_ni!System.Web.Hosting.HostingEnvironment.Initialize(System.Web.Hosting.ApplicationManager, System.Web.Hosting.IApplicationHost, System.Web.Configuration.IConfigMapPathFactory, System.Web.Hosting.HostingEnvironmentParameters) [[GCFrame]] [[GCFrame]] [[ContextTransitionFrame]] [[GCFrame]] [[GCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[CustomGCFrame]] [[TPMethodFrame] (System.Web.Hosting.HostingEnvironment.Initialize[...]



How to use SetUp ADO.Net Configuration in Web Api

2017-04-29T02:51:21.67-07:00

Hi I am a noob in Web Api. I started Web Api recently.

I want to use Ado.net in Web Api for POST and PUT and DELETE.  Below are some of my questions.

1) Can I use ADO.net in Web API project which has added an Ado.net Entities DataModel?

2) In Ado.net Entities DataModel has define a SQL Connection in Web.Config.

   a) Do I need to  declare a sperate connection string in Web.Config for Ado.net ?

  b) How to use the SQL Connection in Web.Config when using Ado.net to handle tasks?  I am not sure, it seems there is ConfigurationManager to handle.

3)  Can I use Ado.net and EntityFramework together in handling a Task? For exmple, If EntityFx fails, I use ADo.net to try again?

4) For EntityFX, if insert successfully, it will return an object with ID. So, If I use Ado.Net, how canI get the UserId after insert successfully.

Can you give me some links for example or sample to learn from.

Thanks




Concurrency violation: the UpdateCommand affected 0 of the expected 1 records

2009-02-13T10:11:46.247-08:00

Hi,

 I have a very weird problem. i get the following error when i try to update to the database through an adapter.

Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

i get it at  this point : returncode = adapter.Update(dt)

what is happening is the change does get saved but it throws the above error.

In the datatable dt, i pass the values of a checkboxlist. in a given scenario, one can be checked and the others need not be. i.e only one row mite be changed at a given point of time. This dt, i am passing to the update command of the adapter.

The above scenario doesnt occur in all the systems. It occurs only on one system. In other testing and development environments, it works fine. So,  i dont think it is anything wrong with the code. i think it is a version problem or some other problem like that.

the other strange thing is, this issue occured on my local machine too but i recenlty reformatted my entire system and now the error doesnt come.

i am baffled as to what might cause this error. Any help on this would be much appreciated.

Thanks.

pushya.

 

 

 

 

 




How to group Northwind orders based on Customer ContactName

2017-04-28T12:25:06.137-07:00

Im using northwind database . U may see the attached files .My view displays all orders from the database without an order . I want to display orders based on contactname (customer) and alphabetically . For example contact name AVARIA and under it to display all orders of this costumer and so on .

Because this is showing me all the orders coming from the database without any order .

public ActionResult Index()
      {
           var orders = db.Orders.Include(o => o.Customer).Include(o => o.Employee).Include(o => o.Shipper);
            return View(orders.ToList());
         
 
 
      }



I want to display like this :

AVAIRA
ORDER 1 OF AVAIRA FROM DATABASE WITH ITS DETAILS 
ORDER 2 OF AVAIRA FROM DATABASE WITH ITS DETAILS  
ORDER 3 OF AVAIRA FROM DATABASE WITH ITS DETAILS  
 
BECUA
ORDER 1 OF BECUA FROM DATABASE WITH ITS DETAILS
ORDER 1 OF BECUA FROM DATABASE WITH ITS DETAILS  
 
AND SO ON 

 




EntityFramework unable to insert data into SQLServer table

2017-04-27T06:43:28.31-07:00

Hi, As above,

error Msg :

System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Customers' when IDENTITY_INSERT is set to OFF.

I created a Web Api Project and I added Ado.net Entities DataModel base on Database First approach.

I post the Json Data string in Fiddler to this Web Api Post.


in SQL Server table, I have setUp:

CustId
Is Identity yes, Identity Increment 1  Identity Seed 1


in the EDMX : I made following changes.

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

    public partial class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustId { get; set; }
        public string CustomerName { get; set; }
        public string CustomerPassword { get; set; }
        public string CustomerEmailAddr { get; set; }
        public string CustomerMobileNo { get; set; }
        public Nullable CreatedOn { get; set; }
    }
}

----Controller

 [HttpPost]
  public void PostContact([FromBody] Customer contact)
 {
    repository.Add(contact);
  }

public void Add(Customer contact)
{
   try
   {            

      var addedContact = ctx.Customers.Add(contact);
      ctx.SaveChanges();
    }
   catch (Exception ex)
    {
      string err = ex.ToString();
    }         

 }

After making change on Class Customer in EDMX, still cannot insert.

Thanks




Entit Framework Core

2017-04-28T00:19:58.363-07:00

Hi,     how do I create an Edit for below. All the examples I have found don't seem to work? using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ExploreCalifornia.Models; using Microsoft.AspNetCore.Authorization; namespace ExploreCalifornia.Controllers {     [Route("blog")]     public class BlogController : Controller     {         private readonly BlogDataContext _db;         public BlogController(BlogDataContext db)         {             _db = db;         }         [Route("")]         public IActionResult Index(int page = 0)         {             var pageSize = 2;             var totalPosts = _db.Posts.Count();             var totalPages = totalPosts / pageSize;             var previousPage = page - 1;             var nextPage = page + 1;             ViewBag.PreviousPage = previousPage;             ViewBag.HasPreviousPage = previousPage >= 0;             ViewBag.NextPage = nextPage;             ViewBag.HasNextPage = nextPage < totalPages;             var posts =                 _db.Posts                     .OrderByDescending(x => x.Posted)                     .Skip(pageSize * page)                     .Take(pageSize)                     .ToArray();             if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")                 return PartialView(posts);             return View(posts);         }         [Route("{year:min(2000)}/{month:range(1,12)}/{key}")]         public IActionResult Post(int year, int month, string key)         {             var post = _db.Posts.FirstOrDefault(x => x.Key == key);             return View(post);         }         [Authorize]         [HttpGet, Route("create")]   [...]



Want to add edit and and delete button functionality to my asp.net calendar control , C#

2017-04-27T02:12:01.35-07:00

Hi, I am trying to add a edit and delete feature to my  calendar I built using Asp.net calendar control and utilizing C#. The calendar is binded to an existing SQL database where all events are stored and the calendar is able to display the event titles for their corresponding days within the day cell and also color the background of that cell. I would like to add an edit feature and a delete feature to the calendar. The calendar has text boxes which you fill in with the event information and click the submit button to get the event to show on the calendar and to exist in the database. I would  like to fill those text boxes if an event already exists for the day selected (meaning they chose a day that already contains an event) with the already existing event data and then select "edit" and be able to edit the existing data and re-submit it into the database. And also be able to delete the event from the calendar and the database. Could someone help me with this. It is a functionality that I just realized I needed. Below is my C# code, I have not added any edit or delete buttons yet. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Configuration; namespace Calender { public partial class WebForm1 : System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); protected DataSet dsMonth; protected void Page_Load(object sender, EventArgs e) { con.Open(); Calendar1.VisibleDate = DateTime.Today; FillEventDataset(); } protected void FillEventDataset() { DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year, Calendar1.VisibleDate.Month, 1); DateTime lastDate = GetFirstDayOfNextMonth(); dsMonth = GetCurrentMonthData(firstDate, lastDate); } protected DateTime GetFirstDayOfNextMonth() { int monthNumber, yearNumber; if (Calendar1.VisibleDate.Month == 12) { monthNumber = 1; yearNumber = Calendar1.VisibleDate.Year + 1; } else { monthNumber = Calendar1.VisibleDate.Month + 1; yearNumber = Calendar1.VisibleDate.Year; } DateTime lastDate = new DateTime(yearNumber, monthNumber, 1); return lastDate; } protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate) { DataSet dsMonth = new DataSet(); ConnectionStringSettings cs; cs = ConfigurationManager.ConnectionStrings["ConnectionString"]; String connString = cs.ConnectionString; SqlConnection dbConnection = new SqlConnection(connString); String query; query = "SELECT Date, Evnt FROM Events " + " WHERE Date >= @firstDate AND Date < @lastDate"; SqlCommand dbCommand = new SqlCommand(query, dbConnection); dbCommand.Parameters.Add(new SqlParameter("@firstDate", firstDate)); dbCommand.Parameters.Add(new SqlParameter("@lastDate", lastDate)); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand); try { sqlDataAdapter.Fill(dsMonth); } catch { } return dsMonth; } protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) { DateTime nextDate; if (dsMonth != null) { foreach (DataRow dr in dsMonth.Tables[0].Rows) { nextDate = (DateTime)dr["Date"]; if (nextDate == e.Day.Date) { e.Cell.BackColor = System.Drawing.Color.Pink; Label lb = new Label(); lb.Visible = true; lb.Text = "
"; lb.Text += dr[1].ToString(); string a = lb.Text; e.Cell.Controls.Add(lb); } } } } protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e) { FillEventDataset(); } protected void Calendar1_Se[...]



ASP.NET Core EntityFramework

2017-04-27T04:36:09.683-07:00

Hi,

    I have a tutorial example that uses EF to create two databases.

I have been deploying to a remote server for testing in the real world.

My hosting provider only allows me one Database. So I would like to put all the tables in the one database.

One of the database was for the built in Identity - security setup and the other for a blog.

If I can get it working locally first.

From the config.developement.json below

"BlogDataContext": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DB_******_*******;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;",
    "IdentityDataContext": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DB_DB_******_*******;;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"

The above does not seem to work as only the Identity tables are added to the Database.

Not sure what is the way to go about this?

Thanks,




How do I add a .NET Core 1.1 Class Library dll to ASP.Net core 1.1 project

2017-04-27T17:49:06.937-07:00

Both project are on .NET core 1.1.

The dll is added to the project in Dependencies -> Assemblies. When I publish the asp.net core web site, I can see the dll in the root folder. The web application runs fine until my code calls the dll, which gives me:

FileNotFoundException: Could not load file or assembly 'Test.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Is there a config/json file that I need to update the reference?

How can I make this work?

Thanks,
Patrick




Going in Cricles on Distinct Record Returns

2017-04-28T21:52:56.367-07:00

I am sure this is simple and I am just missing something...

I have a view component:

 public IViewComponentResult Invoke(int id)
        {
            var supplierContacts = _context.SupplierContact                                                             
                                   .Where(s => s.SupplierID== id )
                                   .Distinct();         
           
            return View(supplierContacts);
        }

The invoke statement is returning correctly the records for the supplier contacts.  For example Peter and Raj work for Techsource returns fine.

Where I am having issues is where the supplier contact has two forms of contact, say mobile phone and email, this is returning the contact persons name twice.

So instead of:

Peter

Email

Phone

Raj

Email

The result is

Peter

Email

Phone

Peter

Email

Phone

Raj

Email

I can kind of see why this is.  After all the only restriction I am passing to the expression is the SupplierID and I can also see that the records are not distinct in SupplierContact as there is a listing with an email and then separately a listing with the phone etc.

I just cant see how to write something like:

  var supplierContacts = _context.SupplierContact                                                             
                                   .Where(s => s.SupplierID== id )
                                   .Distinct(SupplierConact.Name);  

How do I force the statement to return just the distinct names in supplierContact without breaking the IEnumerable in the view?




Using tempdata

2017-04-27T22:04:03.193-07:00

hi,

I have used tempdata a lot in a controller class and the controller class is now 3k lines of code .Am looking to move some functions to a sepearate class but doing that causes the tempdata values to get cleared. Any thoughts on how to achieve the same by not losing my tempdata and develop classes which access the tempdata values from the controller.

thanks

Vj