The object ‘DF__Jobs__IsPrivate__52E34C9D’ is dependent on column ‘IsPrivate’.

I have a column IsPrivate which was originally tiny int but I decided to change it to bool

PM> add-migration MigrationName results to

AlterColumn("dbo.Jobs", "IsPrivate", c => c.Boolean(nullable: false));

When I run update-database, I got an error
The object 'DF__Jobs__IsPrivate__52E34C9D' is dependent on column 'IsPrivate'.
ALTER TABLE ALTER COLUMN IsPrivate failed because one or more objects access this column.

It’s because IsPrivate column has default constraint DF__Jobs__IsPrivate__52E34C9D so I need to manually add code to drop it
Sql("ALTER TABLE dbo.Jobs DROP CONSTRAINT DF__Jobs__IsPrivate__52E34C9D");
AlterColumn("dbo.Jobs", "IsPrivate", c => c.Boolean(nullable: false));

When I run update-database again, this time it’s successful

Getting Current Controller and Action Name in Controller or View

Getting in View current controller, action and id in View
string controller = ViewContext.RouteData.Values["controller"].ToString();
string action = ViewContext.RouteData.Values["action"].ToString();

Getting current controller, action and id in Controller
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();

Add Auto Increment Key To Table

public class Company
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Key, Column(TypeName = "varchar"), MaxLength(50)]
    public string UserId { get; set; }
}

public class CompanyConfiguration : EntityTypeConfiguration<Company>
{
  public CompanyConfiguration()
  {
      //for query purpose only
      Property(c => c.Id)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

      //this is the Key to One-to-One/Zero relationship
      HasKey(c => c.UserId);
  }
}

Asp.net MVC Custom Error Pages

In web.config > system.web
modes: On, Off, RemoteOnly
<!--On - display Views/Shared/Error.cshtml only rendered when there is an exception, 404 is not included in this custom error -->
<customErrors mode="RemoteOnly"></customErrors>

This applies whenever the server hits 500 or 404 errors. Not good in debugging but good in production. In system.webServer

<!--errorMode="DetailedLocalOnly" display only to remote clients-->
    <!--errorMode="Custom" display to all both local and remote -->
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" subStatusCode="-1" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="404" path="404.html" responseMode="File" />
      <error statusCode="500" path="500.html" responseMode="File" />
    </httpErrors>

Note: adding the second block will override the first block

Adding Build Configuratior in Asp.Net

Beside “Debug” there is a dropdown, click and select “Configuration Manager”. In “Active Solution Configuration” select “New” then add a name like “Testing” and “Select copy settings from” preferrably copy settings from Release.

Right click “web.config” and select “Add Config Transform”. This will create Web.Testing.config.

Securing Configuration Settings


<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

Create another config file like AppSettings.config and in web.config > appSettings, add configSource attribute and specify the file

<appSettings configSource="AppSettings.config"></appSettings>

This is useful in public repositories and other scenarious where you don’t want to share your other credentials but to specific people only.
Exclude the AppSettings.config from repository

Showdown

@Html.TextAreaFor(j => j.JobDescription, new { @class = "form-control", @rows = "6", @placeholder = "Enter Job Description" })
        <small class="color-white-mute">Formatting Options: ##heading *italic* **bold** * bulleted list</small>
        <span id="showdown-container">
            <span id="showdown-preview">Preview</span>
        </span>

Scripts

$("#JobDescription").keyup(function () {
    var txtBox = $(this);
    showdownConvert(txtBox);
});
function showdownConvert(txtBox) {
    var converter = new showdown.Converter({ headerLevelStart: 2 });
    $('#showdown-preview').html(converter.makeHtml(txtBox.val()));

    if (txtBox.val()=="") {
        $('#showdown-preview').html("Preview");

    }
}

https://github.com/showdownjs/showdown
http://showdownjs.github.io/demo/
https://mathiasbynens.be/notes/showdown-javascript-jquery

Increasing IIS Upload Limit

When uploading file to IIS greater than default will lead to
Exception Details: System.Web.HttpException: Maximum request length exceeded.

To solve this problem, we need specify our upload limit the server is allowed to accept say 5MB (1024×5000)
In Web.config > system.web add
<httpRuntime maxRequestLength="5120000" executionTimeout="3600" />

In Web.config > system.webServer
<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="5120000" />
    </requestFiltering>
</security>

Note: maxRequestLength and maxAllowedContentLength must match

Customizing PagedList.Mvc

@Html.PagedListPager(
Model.Jobs,
page => Url.Action("Jobs",
new { controller = "Company", area = "Admin", page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }),
new PagedListRenderOptions
{
LinkToFirstPageFormat = "<<",
LinkToLastPageFormat = ">>",
LinkToNextPageFormat = "",
LinkToPreviousPageFormat = "",
UlElementClasses = new[] { "pagination","pagination-theme" }
}
)

More info about PagedList.Mvc https://github.com/TroyGoode/PagedList/blob/master/src/PagedList.Mvc/PagedListRenderOptions.cs