tag:blogger.com,1999:blog-13586871219009237852024-03-04T22:15:44.401-08:00dotNet From ManilaHi, my name is Harold Javier. I am an ASP.NET (dotNet) trainer, coach, mentor, and consultant for more than 8 years. It is my mission to teach, educate, and train people about some simple solutions to common problems we experience either as a software developer or as a researcher on topics about ASP.NET Core, ASP.NET MVC, ASP.NET Web API, ASP.NET Web Form, and .NET (dotNet) technology in general.Unknownnoreply@blogger.comBlogger143125tag:blogger.com,1999:blog-1358687121900923785.post-21227782756719476102020-01-08T21:44:00.000-08:002020-01-08T21:45:30.551-08:00ASP.NET MVC 5 Hands-on TrainingAnother successful ASP.NET MVC 5 training at Manly Plastics, Inc. conducted by veteran ASP.NET trainer, <a href="http://www.haroldjavier.com/">Harold Javier</a>, and senior developer, Carl Stephen Laredo.<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMFdHVAHJyt-QCbKqoV2x5pSPorb0BIC_22d_5sf0taNwm1oRyMntt3Pt931dyDCHo8f_mohZrwVLB821BIIgx2s2o2g7YSiGkeMVKoh5SGid-qHw1JuAMHfXZrVxSPkln55jqw2Zf4h0/s1600/Day+1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="720" data-original-width="960" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMFdHVAHJyt-QCbKqoV2x5pSPorb0BIC_22d_5sf0taNwm1oRyMntt3Pt931dyDCHo8f_mohZrwVLB821BIIgx2s2o2g7YSiGkeMVKoh5SGid-qHw1JuAMHfXZrVxSPkln55jqw2Zf4h0/s320/Day+1.jpg" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifDk7lYIFvMQVR93kS8xBfnNil2RxexTrisip1tguNg7bAoQxk3GKW-Lnk_3qVMOL2S7TWQd_69bqUDymTxUhZv123Z0SxvOgJ7zii-8EbsXCiFYR4_hHluhIaV3ZMd-KeoF6NKRYJiiA/s1600/Day+2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="720" data-original-width="960" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifDk7lYIFvMQVR93kS8xBfnNil2RxexTrisip1tguNg7bAoQxk3GKW-Lnk_3qVMOL2S7TWQd_69bqUDymTxUhZv123Z0SxvOgJ7zii-8EbsXCiFYR4_hHluhIaV3ZMd-KeoF6NKRYJiiA/s320/Day+2.jpg" width="320" /></a></div>
<br />Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-28296961547565768672019-05-19T22:56:00.004-07:002019-05-19T22:56:55.635-07:00ASP.NET Best Practices TrainingWe had another successful training in Quezon City on topics about ASP.NET MVC Best Practices conducted by <a href="http://www.haroldjavier.com/">Harold Javier</a>, a veteran .NET trainer and developer, together with Carl Stephen Laredo.<br />
<br />
It was attended by Direc Business Technology, Inc. technical and functional consultants, team leaders, system analysts, and software developers.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0OEy1Hvpq43cnb40jlAT_mnr1HEurAtjsexzorSEyfKF0B5R_wjJVkoRd_BHAUyJezBJNCNZvvnZmG0vlWvhyiktYNln4th-JjXdptMqSHf2B4rCqeV6AdTQXdcb39ZteW7S_3ZAtRkA/s1600/harold_net_lecturer.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="1600" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0OEy1Hvpq43cnb40jlAT_mnr1HEurAtjsexzorSEyfKF0B5R_wjJVkoRd_BHAUyJezBJNCNZvvnZmG0vlWvhyiktYNln4th-JjXdptMqSHf2B4rCqeV6AdTQXdcb39ZteW7S_3ZAtRkA/s320/harold_net_lecturer.jpg" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvA6hhmW5s4GOoYMnvyHfyTNoNj5bs8E7kGJJxbmBmuK8f5QYARcVg-yOHu6Fv8X8guOz-3qhkIYb1rcMmWsy1kn0EXTWxYPehtjx3Fg1CdvkSGYmppvL7TlAoDd8Jv7a9vxwNYazlBKg/s1600/harold_net_trainer.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="1600" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvA6hhmW5s4GOoYMnvyHfyTNoNj5bs8E7kGJJxbmBmuK8f5QYARcVg-yOHu6Fv8X8guOz-3qhkIYb1rcMmWsy1kn0EXTWxYPehtjx3Fg1CdvkSGYmppvL7TlAoDd8Jv7a9vxwNYazlBKg/s320/harold_net_trainer.jpg" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVEsJfA_YhF6HGticPz_sT78oJNtU4IygOx3kp5wIMTBY2A_oypNQ-C_nfgMZtXs7JgK6j_8DY_CPTa5WjfoDp775jPC_qMd1NzrVoYHLMHCEO7hyphenhyphenZJhz0_d7oyd6H1mc1bGanzfzHqU0/s1600/cs_trainer.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="720" data-original-width="960" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVEsJfA_YhF6HGticPz_sT78oJNtU4IygOx3kp5wIMTBY2A_oypNQ-C_nfgMZtXs7JgK6j_8DY_CPTa5WjfoDp775jPC_qMd1NzrVoYHLMHCEO7hyphenhyphenZJhz0_d7oyd6H1mc1bGanzfzHqU0/s320/cs_trainer.jpg" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-1358687121900923785.post-75536743751117966882019-03-28T00:28:00.001-07:002019-07-31T22:58:27.240-07:00ASP.NET MVC 5 (Best Practices) WorkshopDue to high demand, I'm still conducting workshops and seminars on ASP.NET MVC 5 using Visual Studio 2013 with .NET Framework 4.5.1.<br />
<br />
For the benefit of the attendees, below are the NuGet packages that I use during the ASP.NET MVC 5 live workshop:<br />
<br />
ORM: <b>Entity Framework version 6.2.0 </b><br />
<i><span style="color: blue;">install-package EntityFramework -Version 6.2.0</span></i><br />
<br />
DI/IoC: <b>Structuremap</b><br />
<i><span style="color: blue;">install-package StructureMap.MVC5</span></i><br />
<br />
Mapping: <b>AutoMapper version 5.1.1</b><br />
<i><span style="color: blue;">install-package AutoMapper -Version 5.1.1</span></i><br />
<br />
<br />
And for the lazy trainees who always forget the correct format of the connectionString, you may copy then paste the below sample connectionString to your web.config just above the </configuration> end tag:<br />
<br />
<br />
<connectionStrings><br />
<add name="YourDbConnectionString" connectionString="Data Source=YourDatabaseServerName;Initial Catalog=SampleDB;Integrated Security=True"<br />
providerName="System.Data.SqlClient" /><br />
</connectionStrings><br />
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-7144693238810723342018-09-26T22:58:00.002-07:002018-09-26T22:58:41.085-07:00ASP.NET Core MVC's Action Result naming changesWorking from version 1.1 to 2.1. I found this very handy:<br />
<br />
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; margin-bottom: 16px;">
Following methods on the <code style="background-color: rgba(27, 31, 35, 0.05); border-radius: 3px; box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 11.9px; margin: 0px; padding: 0.2em 0.4em;">Controller</code> base class have been renamed for the sake of consistency and making them less verbose.</div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; margin-bottom: 16px;">
HttpUnauthorized => Unauthorized<br style="box-sizing: border-box;" />HttpNotFound(and its overloads) => NotFound<br style="box-sizing: border-box;" />HttpBadRequest(and its overloads) => BadRequest</div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; margin-bottom: 16px;">
Following action result types have also been renamed. The <code style="background-color: rgba(27, 31, 35, 0.05); border-radius: 3px; box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 11.9px; margin: 0px; padding: 0.2em 0.4em;">Http</code> prefix has been removed.</div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px;">
Microsoft.AspNetCore.Mvc.HttpUnauthorizedResult => Microsoft.AspNetCore.Mvc.UnauthorizedResult<br style="box-sizing: border-box;" />Microsoft.AspNetCore.Mvc.HttpOkResult => Microsoft.AspNetCore.Mvc.OkResult<br style="box-sizing: border-box;" />Microsoft.AspNetCore.Mvc.HttpOkObjectResult => Microsoft.AspNetCore.Mvc.OkObjectResult<br style="box-sizing: border-box;" />Microsoft.AspNetCore.Mvc.HttpNotFoundResult => Microsoft.AspNetCore.Mvc.NotFoundResult<br style="box-sizing: border-box;" />Microsoft.AspNetCore.Mvc.HttpNotFoundObjectResult => Microsoft.AspNetCore.Mvc.NotFoundObjectResult<br style="box-sizing: border-box;" />Microsoft.AspNetCore.Mvc.HttpStatusCodeResult = > Microsoft.AspNetCore.Mvc.StatusCodeResult</div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px;">
<br /></div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px;">
<br /></div>
<div style="background-color: white; box-sizing: border-box; color: #24292e; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";">
<span style="font-size: xx-small;">Source: a user named 'kichalla' from Github</span></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-4963326557591714932018-09-26T01:48:00.003-07:002018-09-26T01:48:45.457-07:00Solving Error 500 (internal server error) when running a newly deployed ASP.NET Core WebAPI<span style="font-family: inherit;">I encountered an <b>Error 500</b> when I first run the ASP.NET Core 2.1 Web API deployed on a Windows 2008 Server machine with IIS version 7.5.</span><br />
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">When I checked the log (since I set <b>stdoutLogEnabled="true"</b>), I found an error that says:</span><br />
<span style="font-family: inherit;"><br /></span>
<b><span style="font-family: inherit;">fail: Microsoft.EntityFrameworkCore.Database.Command[20102]</span></b><br />
<b><span style="font-family: inherit;"> Failed executing DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='60']</span></b><br />
<b><span style="font-family: inherit;"> CREATE DATABASE [SampleDb];</span></b><br />
<b><span style="font-family: inherit;">System.Data.SqlClient.SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.</span></b><br />
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">I know it has something to do with the permission in the database.</span><br />
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;"><u>The solutions below just worked for me:</u></span><br />
<span style="font-family: inherit;"><br /></span>
<ol style="background-color: white; border: 0px; box-sizing: inherit; color: #242729; font-size: 15px; font-stretch: inherit; font-variant-east-asian: inherit; font-variant-numeric: inherit; line-height: inherit; list-style-image: initial; list-style-position: initial; margin: 0px 0px 1em 30px; padding: 0px; vertical-align: baseline;">
<li style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px 0px 0.5em; overflow-wrap: break-word; padding: 0px; vertical-align: baseline;"><span style="font-family: inherit;">Connect to the database using <strong style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">SQL Server Management Studio</strong>.</span></li>
<li style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px 0px 0.5em; overflow-wrap: break-word; padding: 0px; vertical-align: baseline;"><span style="font-family: inherit;"><span style="font-weight: inherit;">Click </span><strong style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">Security</strong><strong style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">, </strong><span style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">then</span><span style="font-weight: inherit;"> </span><strong style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">Logins</strong></span></li>
<li style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px 0px 0.5em; overflow-wrap: break-word; padding: 0px; vertical-align: baseline;"><span style="font-family: inherit;">Double click the user that will access your database. In my case it is NT AUTHORITY\NETWORK SERVICE</span></li>
<li style="border: 0px; box-sizing: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; line-height: inherit; margin: 0px 0px 0.5em; overflow-wrap: break-word; padding: 0px; vertical-align: baseline;"><span style="font-family: inherit;"><span style="font-weight: inherit;">Select the </span><b>Server Roles</b><span style="font-weight: inherit;"> and check the <u>dbcreator</u>, <u>public</u>, and <u>sysadmin</u> credentials.</span></span></li>
</ol>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-41178642691061531022018-09-24T20:40:00.002-07:002018-09-24T20:40:45.625-07:00Error MSB3027 Could not copy "obj\Debug\netcoreapp2.1\ to "bin\Debug\netcoreapp2.1\<b>Could not copy "obj\Debug\netcoreapp2.1\ to "bin\Debug\netcoreapp2.1\</b><br />
<br />
Have you experienced this error when you're trying to rebuild your application?<br />
<br />
It looks like the IIS Express is "locking" the output when debugging the same project.<br />
<br />
My initial solution was to wait for some time and close some running applications, then tried to rebuild again.<br />
<br />
I worked for sometime, then same thing happened again when I tried to rebuild the application.<br />
<br />
But when I finally close the Visual Studio and opened the same project and build it, it worked fine with no issue.<br />
<br />
So far, that's my quick and easy way to resolve the issue. I'll try to update this post when I found a better approach in solving this problem.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-77950447445659215392018-09-20T00:52:00.004-07:002018-09-20T00:54:37.525-07:00Dapper ORM (A simple implementation) Part 1I recommed the use of <b>Dapper</b>. Aside from it's developed by a good team from Stack Overflow, it was built with performance in mind. And on top of that, Dapper is <u>lightweight</u> and <u>very fast</u> compared to other ORMs.<br />
<br />
<i>You may install Dapper from the NuGet</i>.<br />
<br />
The implementation is so easy to do.<br />
<br />
Here in my example, I'll show you how to get a list of users with the <b>Query()</b> extension method of Dapper to retrieve all the records from the <i><b>User</b> table</i> in our <i><b>UserDb </b>database</i>:<br />
<br />
<br />
<br />
private readonly string connectionString = "Server=BDF_SERVER;Database=UserDb;Trusted_Connection=True;";<br />
<br />
<br />
//To display all the users from the table<br />
public List<User> Display_All_Users()<br />
{<br />
using (var con = new SqlConnection(connectionString))<br />
{<br />
string strRead = "SELECT * FROM User";<br />
return con.Query<User>(strRead).ToList();<br />
}<br />
}<br />
<br />
<br />
//To search a particular user from the table<br />
<br />
public User Display_User_By_Id(int id) <br />
{<br />
using (var con = new SqlConnection(connectionString))<br />
{<br />
string strRead = "Select * From User WHERE Id = @Id"<br />
return con.Query<User>(strRead, new { id }).SingleOrDefault();<br />
}<br />
}<br />
<div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-1338835500311416912018-09-16T19:34:00.002-07:002018-09-16T19:36:47.519-07:00Database First (Reverse engineering to the existing database) in ASP.NET CoreIf you have an existing database (for example in MS SQL server) and you want to "reverse engineer" to that existing database and create its database context in your ASP.NET Core project, one of the simple and faster ways to do it is by installing the following NuGet packages using the Package Manager:<br />
<div>
<br /></div>
<div>
<div>
<b>Install-Package Microsoft.EntityFrameworkCore.SqlServer</b></div>
<div>
<b>Install-Package Microsoft.EntityFrameworkCore.Tools </b></div>
<div>
<b>Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design</b></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Then, to create the models or database context of the existing database to a folder named Models, you can use the following command:</div>
<div>
<br /></div>
<div>
<div class="MsoNormal">
<b>Scaffold-DbContext
“Server=Your_Server_Name;Database=SampleDb;Trusted_Connection=True;”
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models</b><o:p></o:p></div>
</div>
<div>
<br /></div>
<div>
This command will generate a DbContext and POCO of SampleDb from Your_Server_Name database to Models folder.</div>
<div>
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-88228463673213399772017-09-28T19:29:00.004-07:002017-09-28T19:29:58.056-07:00How to get the MAC address of Any device on the network using C#I once deployed a web application on a client that required to identify all the MAC addresses of different devices connected on the network. I can do <b>arp -a</b> command from command prompt, but I also created a short script to identify the MAC address of every device connected on the network using C#. Here's my code:<br />
<br />
[System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]<br />
private static extern int SendARP(int targetIp, int sourceIp, byte[] pcMacAddr, ref int macAddLength);<br />
public static PhysicalAddress GetMacAddress(IPAddress ipAddress)<br />
{<br />
const int macAddressLength = 6;<br />
int length = macAddressLength;<br />
var macBytes = new byte[macAddressLength];<br />
SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length);<br />
return new PhysicalAddress(macBytes);<br />
}Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-90254425976145023982017-08-14T19:13:00.001-07:002017-08-14T19:13:37.516-07:00How to print content of the page using ASP.NET AjaxToolkitI once had a requirement to print a portion of the page using AjaxToolkit. Below is my sample code to generate a printable simple report on button click:<br />
<br />
<br />
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"><br />
</ajaxToolkit:ToolkitScriptManager><br />
<script type="text/javascript"><br />
function PrintPanel() {<br />
var panel = document.getElementById("<%=Panel1.ClientID %>");<br />
var printWindow = window.open('', '', 'height=500,width=1000');<br />
printWindow.document.write('<html><head><title>My Sample Report</title></head>');<br />
printWindow.document.write('<body style="font-size: 12px; font-family: Calibri">');<br />
printWindow.document.write(panel.innerHTML);<br />
printWindow.document.write('</body></html>');<br />
printWindow.document.close();<br />
setTimeout(function () {<br />
printWindow.print();<br />
}, 500);<br />
return false;<br />
}<br />
</script><br />
<br />
<br />
<i><asp:Button ID="btnPrint" runat="server" Text="Print Report" OnClientClick="return PrintPanel();" Visible="False" /></i><br />
<br />
<i> <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" BackColor="#ffffff"></i><br />
<br />
<i> //All your HTML layout and elements, reports, GridView, etc. go here</i><br />
<i> </i><br />
<i> </asp:Panel></i><br />
<br />Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-43207925146178523922017-08-14T18:56:00.000-07:002017-08-14T18:57:01.983-07:00How to migrate CSV to MS SQL Server database using SqlBulkCopyBelow is a sample code in migrating or importing as CSV file to SQL database:<br />
<br />
<i>void Migrate_CSV_File_To_Database()</i><br />
<i> {</i><i> </i><br />
<i> if (FileUpload1.HasFile)</i><br />
<i> {</i><br />
<i> const string saveFolder = @"C:\temp\imported";</i><br />
<i> string filePath = Path.Combine(saveFolder, </i><i>FileUpload1</i><i>.FileName);</i><br />
<i> FileUpload1.SaveAs(filePath);</i><br />
<i> string connString = WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;</i><br />
<i> var excelConnString =</i><br />
<i> String.Format(</i><br />
<i> "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1\"",</i><br />
<i> filePath);</i><br />
<i><br /></i>
<i> //Create Connection to Excel work book </i><br />
<i> using (var excelConnection = new OleDbConnection(excelConnString))</i><br />
<i> {</i><br />
<i> //Create OleDbCommand to fetch data from Excel </i><br />
<i> const string strSelect = "SELECT [Column1], [Column2], [Column3], [Column4] FROM [Sheet1$]";</i><br />
<i> using (var cmd = new OleDbCommand(strSelect, excelConnection))</i><br />
<i> {</i><i> </i><br />
<i> excelConnection.Open();</i><br />
<i> using (var dReader = cmd.ExecuteReader())</i><br />
<i> {</i><br />
<i> using (var sqlBulk = new SqlBulkCopy(connString))</i><br />
<i> {</i><br />
<i> //Give your Destination table name </i><br />
<i> sqlBulk.DestinationTableName = "Destination_Table_Name";</i><br />
<i> sqlBulk.WriteToServer(dReader);</i><br />
<i> }</i><br />
<i> }</i><br />
<i> excelConnection.Close(); </i><i> </i><br />
<i> }</i><br />
<i> }</i><br />
<i> } </i><br />
<i> }</i>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-72352800223576280212017-08-14T18:42:00.001-07:002017-08-14T18:42:56.271-07:00How to import GridView to Excel in ASP.NET WebForm with C#I have a requirement to import a GridView data to MS Excel without using any third party library. The solutions are kinda old stuff actually and they're all over the net, but I still want to share it here on my blog for the benefit of my visitors.<br />
<br />
A. First, you need to add VerifyRenderingInServerForm method to confirm that an HtmlForm control is rendered for the specified ASP.NET server control at run time.<br />
<br />
<i> public override void VerifyRenderingInServerForm(Control control)</i><br />
<i> {</i><br />
<i> </i><br />
<i> }</i><br />
<i> </i><br />
B. Then, add the following sample codes to the button click event.<br />
<br />
<i>protected void btnConvertToExcel_Click(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> Response.ContentType = "application/vnd.ms-excel";</i><br />
<i> Response.AddHeader("content-disposition", "attachment;filename=SalesReport.xls");</i><br />
<i> Response.Charset = "";</i><br />
<i> var sw = new StringWriter();</i><br />
<i> var hw = new HtmlTextWriter(sw);</i><br />
<i> gvSalesReport.AllowPaging = false;</i><br />
<i> </i><br />
<i> //Call the method in viewing Sales Report in GridView </i><br />
<i> Get_Sales_Report(); </i><br />
<i> </i><br />
<i> </i><br />
<i> for (int i = 0; i <= gvSalesReport.Rows.Count - 1; i++)</i><br />
<i> {</i><br />
<i> GridViewRow row = gvSalesReport.Rows[i];</i><br />
<i> </i><br />
<i> //Change Color back to white</i><br />
<i> row.BackColor = System.Drawing.Color.White;</i><br />
<i> </i><br />
<i> //Apply text style to each Row</i><br />
<i> row.Attributes.Add("class", "textmode");</i><br />
<i> </i><br />
<i> //Apply style to Individual Cells of Alternating Row (optional)</i><br />
<i> if (i % 2 != 0)</i><br />
<i> {</i><br />
<i> row.Cells[0].Style.Add("background-color", "#C2D69B");</i><br />
<i> row.Cells[1].Style.Add("background-color", "#C2D69B");</i><br />
<i> row.Cells[2].Style.Add("background-color", "#C2D69B");</i><br />
<i> row.Cells[3].Style.Add("background-color", "#C2D69B"); </i><br />
<i> }</i><br />
<i> }</i><br />
<i> gvSalesReport.RenderControl(hw);</i><br />
<i> </i><br />
<i> //style to format numbers to string</i><br />
<i> const string style = "<style>.textmode{mso-number-format:\\@;}</style>";</i><br />
<i> Response.Write(style);</i><br />
<i> Response.Output.Write(sw.ToString());</i><br />
<i> Response.Flush();</i><br />
<i> Response.End();</i><br />
<i> }</i>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-66720972065458239232017-08-02T18:54:00.000-07:002017-08-02T19:58:09.843-07:00Peachpie Error: ProjectName.msbuildproj(22,3): error MSB4020: The value "" of the "Project" attribute in element is invalid.Just this morning while drinking 2 cups of my favorite<i> Nescafe Decaf </i>and<i> Alaska Krem-Top</i>, I created my first <b>Peachpie</b> project.<br />
<br />
I'm using <u>dotnet version 2.0.0-preview2-006497</u> and I started installing templates for peachpie by typing <i>dotnet new -i Peachpie.Templates::*</i> .<br />
<br />
Then I began to create a new <b>Peachpie console application</b> by simply typing <i>dotnet new peachpie-console</i>. And I got a message that says <u>The template "Peachpie console application" was created successfully</u>.<br />
<br />
But when I ran the <i>dotnet restore </i>command, I got the following error message:<br />
<br />
<b>ProjectName.msbuildproj(22,3): error MSB4020: The value "" of the "Project" attribute in element <Import> is invalid.</b><br />
<br />
And obviously I cannot run the command <i>dotnet run</i> until I fix the build error.<br />
<br />
I will try to find the reason what happened and I'll update this post as soon as I can.<br />
<br />
----------------------------------------------------------------------------------------------------------------<br />
<br />
<br />
<b>Finally, I found a solution to this error! </b><br />
<br />
<br />
I simply edited/replaced the default msbuildproj file with the following:<br />
<br />
<Project Sdk="Microsoft.NET.Sdk"><br />
<PropertyGroup><br />
<OutputType>exe</OutputType><br />
<TargetFramework>netcoreapp1.1</TargetFramework><br />
</PropertyGroup><br />
<br />
<ItemGroup><br />
<Compile Include="**/*.php" /><br />
</ItemGroup><br />
<br />
<ItemGroup><br />
<DotNetCliToolReference Include="Peachpie.Compiler.Tools" Version="0.7.0-*" /><br />
<PackageReference Include="Peachpie.NET.Sdk" Version="0.7.0-*" PrivateAssets="Build" /><br />
</ItemGroup><br />
<br />
<!-- A temporary solution, import C# Visual Studio design time targets in order to be able to load the project in Visual Studio --> <br />
<PropertyGroup><br />
<CSharpDesignTimeTargetsPath Condition="'$(CSharpDesignTimeTargetsPath)'==''">$(MSBuildExtensionsPath)\Microsoft\VisualStudio\Managed\Microsoft.CSharp.DesignTime.targets</CSharpDesignTimeTargetsPath><br />
</PropertyGroup><br />
<Import Project="$(CSharpDesignTimeTargetsPath)" Condition="Exists('$(CSharpDesignTimeTargetsPath)')" /><br />
</Project><br />
<br />
<br />
Then, I typed the <i>dotnet restore ProjectName.msbuildproj </i>command.<br />
<br />
Once restore is completed, you can now run your application by typing <i>dotnet run</i> command.<br />
<br />
<br />Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1358687121900923785.post-15072797599841606892017-07-20T00:17:00.000-07:002017-07-20T00:17:26.680-07:00How do you render different layout in ASP.NET MVCThere are several ways to render different layout in ASP.NET MVC. I just give preference to the 2 ways below.<br />
<br />
<br />
A. <b>By defining the layout on the view</b>. <u>For example:</u><br />
<br />
Placing the below code on top of Index.cshtml of AdminController<br />
<br />
<i>@{</i><br />
<i> Layout = "~/Views/Shared/_AdminLayout.cshtml";</i><br />
<i>}</i><br />
<i><br /></i>
then placing the below code on top of Index.cshtml of EmployeeController<br />
<br />
<i>@{</i><br />
<i> Layout = "~/Views/Shared/_EmployeeLayout.cshtml";</i><br />
<i>}</i><br />
<br />
<br />
B.<b> By identifying the controller and render the Layout per controller in a single _ViewStart file in the root directory of the Views folder</b>. <u>For example:</u><br />
<br />
<i>@{</i><br />
<i> var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();</i><br />
<i> string layoutSelection = "";</i><br />
<i> if (controller == "Admin") </i><br />
<i> {</i><br />
<i> layoutSelection = "~/Views/Shared/_AdminLayout.cshtml";</i><br />
<i> }</i><br />
<i> else</i><br />
<i> {</i><br />
<i> layoutSelection = "~/Views/Shared/_EmployeeLayout.cshtml";</i><br />
<i> }</i><br />
<i> Layout = layoutSelection ;</i><br />
<i>}</i>Unknownnoreply@blogger.com4tag:blogger.com,1999:blog-1358687121900923785.post-15233857623263265502017-07-14T01:18:00.001-07:002017-07-14T01:19:24.885-07:00How to register and login a user using ASP.NET Identity and Owin with ASP.NET WebFormI'll explain to you how to register a new user account and redirect the user to login page using ASP.NET Identity and OWIN.<br />
<br />
Here are the simple steps that you may use.<br />
<br />
First you need to create an empty WebForm application. In my example, I named it "IdentitySample".<br />
<br />
Then, follow the below steps:<br />
<br />
<br />
<b>Step 1. Install the following NuGet packages:</b><br />
<i><br /></i>
<i>Microsoft.AspNet.Identity.EntityFramework</i><br />
<i>Microsoft.Owin.Host.SystemWeb</i><br />
<i>Microsoft.Owin.Security.Cookies</i><br />
<br />
<br />
<b>Step 2. Add a Startup.cs class</b><br />
<br />
<i>using Microsoft.AspNet.Identity;</i><br />
<i>using Microsoft.Owin;</i><br />
<i>using Microsoft.Owin.Security.Cookies;</i><br />
<i>using Owin;</i><br />
<i><br /></i>
<i>[assembly: OwinStartup(typeof(</i><i>IndentitySample</i><i>.Startup))]</i><br />
<i><br /></i>
<i>namespace IndentitySample</i><br />
<i>{</i><br />
<i> public class Startup</i><br />
<i> {</i><br />
<i> public void Configuration(IAppBuilder app)</i><br />
<i> { </i><br />
<i> app.UseCookieAuthentication(new CookieAuthenticationOptions</i><br />
<i> {</i><br />
<i> AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,</i><br />
<i> LoginPath = new PathString("/Login")</i><br />
<i> });</i><br />
<i> }</i><br />
<i> }</i><br />
<i>}</i><br />
<br />
<br />
<b>Step 3. Add connectionString in web.config file</b><br />
<br />
<i><connectionStrings></i><br />
<i> <add name="DefaultConnection" connectionString="Data Source=dotnetguru;Initial Catalog=LoginDb;Integrated Security=True"</i><br />
<i> providerName="System.Data.SqlClient" /></i><br />
<i> </connectionStrings></i><br />
<i> </i><br />
<br />
<b>Step 4. Add a Registration page</b><br />
<br />
<i><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="IndentitySample.Register" %></i><br />
<i><br /></i>
<i><!DOCTYPE html></i><br />
<i><br /></i>
<i><html xmlns="http://www.w3.org/1999/xhtml"></i><br />
<i><head runat="server"></i><br />
<i> <title></title></i><br />
<i></head></i><br />
<i><body style="font-family: Arial, Helvetica, sans-serif; font-size: small"></i><br />
<i> <form id="form1" runat="server"></i><br />
<i> <div></i><br />
<i> <h4 style="font-size: medium">Register a new user</h4></i><br />
<i> <hr /> </i><br />
<i> <div style="margin-bottom:10px"></i><br />
<i> <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label></i><br />
<i> <div></i><br />
<i> <asp:TextBox runat="server" ID="UserName" /> </i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <div style="margin-bottom:10px"></i><br />
<i> <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label></i><br />
<i> <div></i><br />
<i> <asp:TextBox runat="server" ID="Password" TextMode="Password" /> </i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <div style="margin-bottom:10px"></i><br />
<i> <asp:Label runat="server" AssociatedControlID="ConfirmPassword">Confirm password</asp:Label></i><br />
<i> <div></i><br />
<i> <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" /> </i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <div></i><br />
<i> <div></i><br />
<i> <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" /></i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <p></i><br />
<i> <asp:Literal runat="server" ID="StatusMessage" /></i><br />
<i> </p> </i><br />
<i> </div></i><br />
<i> </form></i><br />
<i></body></i><br />
<i></html></i><br />
<br />
<br />
<b>Step 5. Modify Register.aspx.cs</b><br />
<br />
<i>using Microsoft.AspNet.Identity;</i><br />
<i>using Microsoft.AspNet.Identity.EntityFramework;</i><br />
<i>using Microsoft.Owin.Security;</i><br />
<i>using System;</i><br />
<i>using System.Linq;</i><br />
<i>using System.Web;</i><br />
<i><br /></i>
<i>namespace IndentitySample</i><br />
<i>{</i><br />
<i> public partial class Register : System.Web.UI.Page</i><br />
<i> {</i><br />
<i> protected void Page_Load(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i><br /></i>
<i> }</i><br />
<i> protected void CreateUser_Click(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> // Default UserStore constructor uses the default connection string named: DefaultConnection</i><br />
<i> var userStore = new UserStore<IdentityUser>();</i><br />
<i> var manager = new UserManager<IdentityUser>(userStore);</i><br />
<i><br /></i>
<i> var user = new IdentityUser() { UserName = UserName.Text };</i><br />
<i> IdentityResult result = manager.Create(user, Password.Text);</i><br />
<i><br /></i>
<i> if (result.Succeeded)</i><br />
<i> {</i><br />
<i> var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;</i><br />
<i> var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);</i><br />
<i> authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);</i><br />
<i> Response.Redirect("~/Login.aspx");</i><br />
<i> }</i><br />
<i> else</i><br />
<i> {</i><br />
<i> StatusMessage.Text = result.Errors.FirstOrDefault();</i><br />
<i> }</i><br />
<i> }</i><br />
<i> }</i><br />
<i>}</i><br />
<br />
<br />
<b>Step 6. Add a Login page</b><br />
<br />
<i><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="IndentitySample.Login" %></i><br />
<i><br /></i>
<i><!DOCTYPE html></i><br />
<i><br /></i>
<i><html xmlns="http://www.w3.org/1999/xhtml"></i><br />
<i><head runat="server"></i><br />
<i> <title></title></i><br />
<i></head></i><br />
<i><body style="font-family: Arial, Helvetica, sans-serif; font-size: small"></i><br />
<i> <form id="form1" runat="server"></i><br />
<i> <div></i><br />
<i> <h4 style="font-size: medium">Log In</h4></i><br />
<i> <hr /></i><br />
<i> <asp:PlaceHolder runat="server" ID="LoginStatus" Visible="false"></i><br />
<i> <p></i><br />
<i> <asp:Literal runat="server" ID="StatusText" /></i><br />
<i> </p></i><br />
<i> </asp:PlaceHolder></i><br />
<i> <asp:PlaceHolder runat="server" ID="LoginForm" Visible="false"></i><br />
<i> <div style="margin-bottom: 10px"></i><br />
<i> <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label></i><br />
<i> <div></i><br />
<i> <asp:TextBox runat="server" ID="UserName" /></i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <div style="margin-bottom: 10px"></i><br />
<i> <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label></i><br />
<i> <div></i><br />
<i> <asp:TextBox runat="server" ID="Password" TextMode="Password" /></i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> <div style="margin-bottom: 10px"></i><br />
<i> <div></i><br />
<i> <asp:Button runat="server" OnClick="SignIn" Text="Log in" /></i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> </asp:PlaceHolder></i><br />
<i> <asp:PlaceHolder runat="server" ID="LogoutButton" Visible="false"></i><br />
<i> <div></i><br />
<i> <div></i><br />
<i> <asp:Button runat="server" OnClick="SignOut" Text="Log out" /></i><br />
<i> </div></i><br />
<i> </div></i><br />
<i> </asp:PlaceHolder></i><br />
<i> </div></i><br />
<i> </form></i><br />
<i></body></i><br />
<i></html></i><br />
<br />
<br />
<b>Step 7. Modify the Login.aspx.cs</b><br />
<br />
<br />
<i>using Microsoft.AspNet.Identity;</i><br />
<i>using Microsoft.AspNet.Identity.EntityFramework;</i><br />
<i>using Microsoft.Owin.Security;</i><br />
<i>using System;</i><br />
<i>using System.Web;</i><br />
<i><br /></i>
<i>namespace IndentitySample</i><br />
<i>{</i><br />
<i> public partial class Login : System.Web.UI.Page</i><br />
<i> {</i><br />
<i> protected void Page_Load(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> if (!IsPostBack)</i><br />
<i> {</i><br />
<i> if (User.Identity.IsAuthenticated)</i><br />
<i> {</i><br />
<i> StatusText.Text = string.Format("Hello {0}!!", User.Identity.GetUserName());</i><br />
<i> LoginStatus.Visible = true;</i><br />
<i> LogoutButton.Visible = true;</i><br />
<i> }</i><br />
<i> else</i><br />
<i> {</i><br />
<i> LoginForm.Visible = true;</i><br />
<i> }</i><br />
<i> }</i><br />
<i> }</i><br />
<i> protected void SignIn(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> var userStore = new UserStore<IdentityUser>();</i><br />
<i> var userManager = new UserManager<IdentityUser>(userStore);</i><br />
<i> var user = userManager.Find(UserName.Text, Password.Text);</i><br />
<i><br /></i>
<i> if (user != null)</i><br />
<i> {</i><br />
<i> var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;</i><br />
<i> var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);</i><br />
<i><br /></i>
<i> authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);</i><br />
<i> Response.Redirect("~/Login.aspx");</i><br />
<i> }</i><br />
<i> else</i><br />
<i> {</i><br />
<i> StatusText.Text = "Invalid username or password.";</i><br />
<i> LoginStatus.Visible = true;</i><br />
<i> }</i><br />
<i> }</i><br />
<i><br /></i>
<i> protected void SignOut(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;</i><br />
<i> authenticationManager.SignOut();</i><br />
<i> Response.Redirect("~/Login.aspx");</i><br />
<i> }</i><br />
<i> }</i><br />
<i>}</i><br />
<br />
<br />
<b>That's it!</b><br />
<div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-48761514697067639922017-07-13T23:43:00.002-07:002017-07-13T23:43:24.942-07:00How to add friendly URL to your ASP.NET web applicationFirst you need to install a <i>NuGet</i> package called <b>Microsoft.AspNet.FriendlyUrl</b>.<br />
<br />
Then, add a class called <b>RouteConfig.cs</b> and make it similar to the codes below:<br />
<br />
<i>using System.Web.Routing;</i><br />
<i>using Microsoft.AspNet.FriendlyUrls;</i><br />
<br />
<i>namespace WebFormsIndentity</i><br />
<i>{</i><br />
<i> public static class RouteConfig</i><br />
<i> {</i><br />
<i> public static void RegisterRoutes(RouteCollection routes)</i><br />
<i> {</i><br />
<i> var settings = new FriendlyUrlSettings();</i><br />
<i> settings.AutoRedirectMode = RedirectMode.Permanent;</i><br />
<i> routes.EnableFriendlyUrls(settings);</i><br />
<i><br /></i>
<i> routes.MapPageRoute("", "MyPage", "~/Page.aspx");</i><br />
<i> }</i><br />
<i> }</i><br />
<i>}</i><br />
<br />
**Actually, you can add as many MapPageRoutes as you want in RegisterRoutes. JUst keep the first and second parameters unique.<br />
<br />
Finally, in your Global Application class (<b>Global.asax</b>), add the following in the Application_Start() event:<br />
<br />
<i> protected void Application_Start(object sender, EventArgs e)</i><br />
<i> {</i><br />
<i> RouteConfig.RegisterRoutes(RouteTable.Routes);</i><br />
<i> }</i><br />
<br />
<br />
And TA-DA.... you now have an SEO-friendly URL!Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-62743980001855984772017-07-11T23:59:00.000-07:002017-07-12T00:01:40.159-07:00DB Context (ASP.NET MVC vs. ASP.NET Core MVC)<b>ASP.NET MVC</b><br />
<br />
<span style="color: red;">using System.Data.Entity; </span><br />
<br />
public class ProfileContext : DbContext<br />
{<br />
public ProfileContext() : base(<span style="color: red;">"ProfileConnectionString"</span>)<br />
{<br />
}<br />
<br />
public DbSet<Profile> Profiles { get; set; }<br />
<br />
protected override void OnModelCreating(<span style="color: red;">DbModelBuilder</span> modelBuilder)<br />
{<br />
modelBuilder.Entity<Profile>().ToTable("Profile"); <br />
}<br />
}<br />
<br />
<br />
<b>ASP.NET Core MVC</b><br />
<br />
<span style="color: red;">using Microsoft.EntityFrameworkCore;</span><br />
<br />
public class ProfileContext : DbContext<br />
{<br />
public ProfileContext(<span style="color: red;">DbContextOptions<ProfileContext> options</span>) : base(<span style="color: red;">options</span>)<br />
{<br />
}<br />
<br />
public DbSet<Profile> Profiles { get; set; }<br />
<br />
protected override void OnModelCreating(<span style="color: red;">ModelBuilder</span> modelBuilder)<br />
{<br />
modelBuilder.Entity<Profile>().ToTable("Profile");<br />
}<br />
}<br />
<br />
<br />Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1358687121900923785.post-50851020343944723832017-07-11T21:56:00.003-07:002017-07-11T21:56:19.666-07:00Filtering a List of Results in ASP.NET MVC 5Here's a simple example on how to filter results based on the given name:<br />
<br />
<br />
<b>Controller</b><br />
<br />
public ActionResult Index(string searchValue)<br />
{ <br />
var emp = db.Profiles.Select(y => y);<br />
if (!String.IsNullOrEmpty(searchValue))<br />
{<br />
emp = emp.Where(y => y.Name.Contains(searchValue));<br />
} <br />
return View(emp);<br />
<br />
}<br />
<br />
<br />
<b>View</b><br />
<br />
@using (Html.BeginForm())<br />
{<br />
<p><br />
Search by name: @Html.TextBox("SearchValue")<br />
<input type="submit" value="Search" /><br />
</p><br />
}<br />
<br />
<table class="table"><br />
<tr><br />
<th><br />
@Html.DisplayNameFor(model => model.Name)<br />
</th><br />
<th><br />
@Html.DisplayNameFor(model => model.Age)<br />
</th><br />
</tr><br />
<br />
@foreach (var item in Model) {<br />
<tr><br />
<td><br />
@Html.DisplayFor(modelItem => item.Name)<br />
</td><br />
<td><br />
@Html.DisplayFor(modelItem => item.Age)<br />
</td> <br />
</tr><br />
}<br />
</table><br />
<div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-67880770455140526772017-07-11T21:05:00.002-07:002017-07-11T21:05:43.663-07:00Sorting a List of Results in ASP.NET MVC 5Here's a simple example:<br />
<br />
<br />
<u><b>Controller </b></u><br />
<br />
private ProfileContext db = new ProfileContext();<br />
<br />
public ActionResult Index(string sortOrder)<br />
{<br />
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name" : "";<br />
ViewBag.AgeSortParm = sortOrder == "Age" ? "age" : "Age";<br />
<br />
var emp = db.Profiles.Select(y => y);<br />
<br />
switch (sortOrder)<br />
{<br />
case "name":<br />
emp = emp.OrderByDescending(y => y.Name);<br />
break;<br />
<br />
case "age":<br />
emp = emp.OrderByDescending(y => y.Age);<br />
break;<br />
<br />
default:<br />
emp = emp.OrderBy(y => y.Name);<br />
break;<br />
}<br />
<br />
return View(emp);<br />
}<br />
<br />
<br />
<u><b>View</b></u><br />
<u><br /></u>
<table class="table"><br />
<tr><br />
<th><br />
@Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })<br />
</th><br />
<th><br />
@Html.ActionLink("Age", "Index", new { sortOrder = ViewBag.AgeSortParm })<br />
</th> <br />
</tr><br />
<br />
@foreach (var item in Model) {<br />
<tr><br />
<td><br />
@Html.DisplayFor(modelItem => item.Name)<br />
</td><br />
<td><br />
@Html.DisplayFor(modelItem => item.Age)<br />
</td> <br />
</tr><br />
}<br />
</table><br />
<div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-91921698253822603612017-07-06T00:07:00.005-07:002017-07-06T00:08:22.752-07:00When you connect to the database and it throws: "ArgumentNullException: Value cannot be null. Parameter name: connectionString"<i>Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<SqlServerDbContextOptionsBuilder> sqlServerOptionsAction)</i><br />
<i>SampleProject.Startup.<ConfigureServices>b__3_0(DbContextOptionsBuilder options) in Startup.cs</i><br />
<br />
It only means you're trying to connect to the database without first "building" the configuration of the appsettings.json with the hosting environment.<br />
<br />
The solution to this is to add the following to your Startup class:<br />
<br />
<b> public Startup(IHostingEnvironment env)</b><br />
<b> {</b><br />
<b> var builder = new ConfigurationBuilder()</b><br />
<b> .SetBasePath(env.ContentRootPath)</b><br />
<b> .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)</b><br />
<b> .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)</b><br />
<b> .AddEnvironmentVariables();</b><br />
<b> Configuration = builder.Build();</b><br />
<b> } </b>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-31802742894421653102017-07-05T20:03:00.000-07:002017-07-05T20:03:20.408-07:00'No executable found matching command "dotnet-aspnet-codegenerator"'When I created a new controller with the built in scaffolding, I got the following error:<br />
<br />
<i>'No executable found matching command "dotnet-aspnet-codegenerator"'</i><br />
<br />
To resolve the issue, I just edited the .csproj file and added the following:<br />
<br />
<b><ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" /> </ItemGroup></b><br />
<br />
Then, everything worked fine.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-8897626605117506162017-07-04T00:54:00.002-07:002017-07-04T00:54:53.560-07:00ArgumentNullException: Value cannot be null. Parameter name: connectionStringSo I posted it.<br />
<br />
It happened to me twice this morning.<br />
<br />
In my first thought, I said, "What?"<br />
<br />
On my second attempt, I still got the same error.<br />
<br />
And I said to myself, "What the f*?"<br />
<br />
Then, finally I found that in my appSettings.json, I misspelled the ConnectionStrings to ConnectionString.<br />
<br />
Now, I realize that too much coffee is not a replacement to lack of sleep and not an excuse for stupidity, lol!<br />
<br />
Anyway, I'm just having fun working on my dotNet Core project 😁<br />
<br />
<br />
<br />
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1358687121900923785.post-12040863608516721452017-07-03T01:58:00.001-07:002017-07-03T01:58:21.275-07:00'EntityTypeBuilder' does not contain a definition for 'ToTable'While utilizing the EF 7 with dotNet core apps, I got an error that says:<br />
<br />
<i>'EntityTypeBuilder<T>' does not contain a definition for 'ToTable' and no extension method 'ToTable' accepting a first argument of type 'EntityTypeBuilder<T>' could be found ....</i><br />
<br />
Installing the Nuget package <b style="background-color: white; color: #222222; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13.2px;">Microsoft.EntityframeworkCore.SqlServer </b><span style="background-color: white; color: #222222; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13.2px;">solved the issue.</span>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-1358687121900923785.post-63546087984692303122017-06-30T01:34:00.003-07:002017-06-30T01:36:14.875-07:00'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'When you try to connect to SQL Server database using Entity Framework and you got the following error message:<br />
<i><br /></i>
<i>'</i><i>DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer' and no extension method 'UseSqlServer' accepting a first argument of type 'DbContextOptionsBuilder' could be found .....</i><br />
<div>
<br /></div>
<div>
A simple way to get around with this error is to simply add or install a NuGet package <b>Microsoft.Entityframeworkcore.Sqlserver</b></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1358687121900923785.post-1389069071067522712017-06-19T18:24:00.003-07:002017-06-19T19:52:54.572-07:00HTTP Error 403.14 - ForbiddenWhen I published my web application this morning, I got this Error:<br />
<br />
<h3 style="color: #cc0000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 1.4em; margin: 10px 0px 0px;">
HTTP Error 403.14 - Forbidden</h3>
<h4 style="font-family: Verdana, Arial, Helvetica, sans-serif; margin: 10px 0px 5px;">
<span style="background-color: #999999; font-weight: normal;">The Web server is configured to not list the contents of this directory.</span></h4>
<br />
Luckily, I remembered the one-liner script that I added to web.config 2 years ago when I experienced the same error when I published and deployed my ASP.NET MVC application for one of my clients.<br />
<br />
Okay, to fix this error, simply add the script below to your web.config file:<br />
<br />
<pre class="default prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; color: #393318; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-stretch: inherit; font-variant-numeric: inherit; line-height: inherit; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; vertical-align: baseline; width: auto; word-wrap: normal;"><code style="border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline; white-space: inherit;"><span class="tag" style="border: 0px; color: #7d2727; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;"><system.webServer></span><span class="pln" style="border: 0px; color: #303336; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">
</span><span class="tag" style="border: 0px; color: #7d2727; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;"><directoryBrowse</span><span class="pln" style="border: 0px; color: #303336; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;"> </span><span class="atn" style="border: 0px; color: #e64320; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">enabled</span><span class="pun" style="border: 0px; color: #303336; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">=</span><span class="atv" style="border: 0px; color: #0f74bd; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">"true"</span><span class="pln" style="border: 0px; color: #303336; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;"> </span><span class="tag" style="border: 0px; color: #7d2727; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">/></span><span class="pln" style="border: 0px; color: #303336; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;">
</span><span class="tag" style="border: 0px; color: #7d2727; font-family: inherit; font-stretch: inherit; font-style: inherit; font-variant: inherit; font-weight: inherit; line-height: inherit; margin: 0px; padding: 0px; vertical-align: baseline;"></system.webServer></span></code></pre>
Unknownnoreply@blogger.com0