Saturday, December 26, 2015

MVC 5 Code First ApplicationDbContext throws error

In my MVC 5 Code First project I decided to put my domain tables under the out of box ApplicationDbContext


When I run the command "update-database ..." I got this error:
"Introducing FOREIGN KEY constraint 'FK_dbo.aaa_dbo.bbb_abcId' on table 'aaa' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors."

This is because I had not null 2 foreign keys in same table that both reference the primary key in same parent table. This creates 2 conflicting cascade delete paths. The solution is to make one of them nullable. See the source link:

Friday, December 25, 2015

mvc code first add foreign key referencing Asp.Net Identity ApplicationUser

in my case I have my own dbcontext called MyContext.

1. in the child class MyModel add:

public ApplicationUser User { get; set; }

2. in IdentityModels add below into class ApplicationDbContext

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

3. for some reason this is not enough, the same code in 2. needs to be add into my own dbcontext too. So in MyContext add below

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

in database it correctly generates the foreign key relationship as:

CONSTRAINT [FK_dbo.UserProfiles_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[AspNetUsers] ([Id])

Wednesday, December 23, 2015

Visual Studio 2015 Community MVC project could not open .cshtml views after installed github update

Visual Studio 2015 Community MVC project could not open .cshtml views after installed github update. Lucky found the solution here 

Step 1: remove everything under this folder C:\Users\abc\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache

 Step 2: reopen VS

TSQL: find out which table a constraint belongs to

TSQL: find out which table a constraint belongs to


SELECT
   OBJECT_NAME(o.parent_object_id)
FROM
   sys.objects o
WHERE
   o.name = 'ConstraintABC' AND o.parent_object_id <> 0

Friday, August 28, 2015

Google Chrome cannot connect to internet after upgrade from Windows 8.1 to Windows 10

this solution worked for me (https://productforums.google.com/d/msg/chrome/ZE4c98nklAw/47xvIIz8zN8J) 1. run cmd as administrator 2. type in "netsh winsock reset" 3. restart pc

Tuesday, August 19, 2014

mvc checkboxlist


//Set up a viewmodel MyViewModel to contain the following

        [DisplayName("Available Products")]
        public IList AvailableProducts { get; set; }
        public IList SelectedProducts { get; set; }

        public PostedProducts PostedProducts { get; set; }



//The definition of ProductDropdownItemViewModel and PostedProducts are:

    public class PostedProducts
    {
        public int[] ProductIds { get; set; }
    }

    public class ProductDropdownItemViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }        
    }


//In your controller method populate the above viewmodel

  e.g. 
                MyViewModel.AvailableProducts = db.Products
                .Select(p => new ProductDropdownItemViewModel 
            {
                Id = p.Id,
                Name = p.Name
            }).ToList();


//In your view display the checkbox list this way

  e.g. the postback method name is Edit

     @model MyViewModel
     @using (Html.BeginForm("Edit", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
        @Html.CheckBoxListFor(x => x.PostedProducts.ProductIds,
                      x => x.AvailableProducts,
                      x => x.Id,
                      x => x.Name,
                      x => x.SelectedProducts,
                      MvcCheckBoxList.Model.Position.Vertical)
     }


//In your postback method Edit use the following code to retrieve your selected items


       public ActionResult Edit(PostedProducts postedProducts)
       {

                foreach (var id in postedProducts.ProductIds)
                {
                     //do whatever you like with the selected product id
                }

       }

Tuesday, August 05, 2014

tsql create table if not already exists


IF  NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[table1]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[table1](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Name] [nvarchar](150) NOT NULL,
 CONSTRAINT [PK_abc] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



END
go

c# read data from .xsl


public void ReadExcel(HttpPostedFileBase file, string currentUserName)
        {

            DataTable tbContainer = new DataTable();
            string strConn = XlsConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.FileName +";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
            string sheetName = "sheet1";
            FileInfo fileInfo = new FileInfo(file.FileName);
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
            DataSet ds = new DataSet();
            oda.Fill(tbContainer);
            var newParcelTubeExport = new ParcelTubeExport();

            //your code to utilize the data

         }

Thursday, July 31, 2014

javascript round decimal to preferred number of decimal places

function round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

javascript validation for decimal(10,2)

$(function () {
    $('.decimal10n2').keyup(function () {
        if (!$(this).val().match(/./gi) || !$(this).val().match(/[0-9]+/g)) {
            $(this).val("");
        }
        else if ($(this).val().split('.').length - 1 > 1)
        {
            this.value = $(this).val().slice(0, -1);
        }
        else if ($(this).val().indexOf('.') != -1) {
            if($(this).val().split(".")[0].length > 10)
            {
                if (isNaN(parseFloat(this.value))) return;
                this.value = $(this).val().split(".")[0].slice(0,-1);
            }
            else if ($(this).val().split(".")[1].length > 2) {
                if (isNaN(parseFloat(this.value))) return;
                this.value = parseFloat(this.value).toFixed(2);
            }
        }

        return this;
    });
});


Tuesday, April 29, 2014

jquery close navigation submenu when click away

$(document).ready(function () {
    $(".navbar-sub-opener").click(function (evt) {
        //close submenu when click away - part 2
        evt.stopPropagation();
        //hide all submenus
        $(".navbar-sub").hide();
        //only open the one that's immediate inside the clicked parent menu item
        $(this).next($(".navbar-sub")).show();
    });

    //close submenu when click away - part 1
    $('html').click(function () {
        $(".navbar-sub").hide();
    });
});

Thursday, April 10, 2014

jquery center div


jQuery.fn.center = function () {
    this.css("position", "fixed");
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

Wednesday, April 02, 2014

mvc partial view popup dialog form

required javascript:

$(document).ready(function () {
    $(".popupformContainer").dialog({
        height: 600,
        width: 300,
        autoOpen: false,
        modal: true,
        open: function (event, ui) {
            $(this).load("/controllername/actionname", { "parameter": $(this).data("parametervalue") }, function (html) {
            });
        },
        close: function (event, ui) {
            event.preventDefault();
            alert("closing");
        },
        buttons: {
            text: "提交", click: function (event) {
                event.preventDefault();
                $.validator.unobtrusive.parse("#PopupForm");
                $("#PopupForm").validate();
                if ($("#PopupForm").valid()) {
                    $("#PopupForm").submit();
                }
                else {
                    event.preventDefault();
                    alert("invalid");
                }
            }
        }
    });

    $(".btnOpenPopupForm").click(function () {
        $(".popupformContainer").data("parameter", $(this).attr("value")).dialog("open");
    });


});
in the parent view you need the button to open popup with class "btnOpenPopupForm" and an empty div with class "popupformContainer" for hosting the popup
in the partial view for the popup all you need is the form and all the form elements, the buttons are automatically generated unless you want some custom buttons

Thursday, March 27, 2014

tsql where clause checking even or odd number

update student
set isOdd = 1, isEven = 0
where exammark % 2 =1

Wednesday, March 26, 2014

Monday, March 10, 2014

mvc refresh current view without losing stuff like sorting, filtering etc

return Redirect(Request.UrlReferrer.ToString());

Saturday, March 01, 2014

mvc HttpPostedFileBase always null

make sure the form declaration in the view has all necessary attributes, e.g.


@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
      ...
}

found a useful way to show div as a modal

http://jsfiddle.net/r77K8/1/

Friday, February 28, 2014

asp.net mvc c# upload image, generate and upload thumbnail

public void UploadProductImage(HttpPostedFileBase file)
        {
            string subPath = "~/Images/";

            bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
            }

            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(Server.MapPath(subPath), pic);

                file.SaveAs(path);

                UploadProductImageThumbnail(file, productId);
            }
        }


public void UploadProductImageThumbnail(HttpPostedFileBase file)
        {
            using (var image = Image.FromStream(file.InputStream, true, true))
            {
                var thumbWidth = 50;
                var thumbHeight = 50;

                using (var thumb = image.GetThumbnailImage(
                    thumbWidth,
                    thumbHeight,
                    () => false,
                    IntPtr.Zero))
                {
                    var jpgInfo = ImageCodecInfo.GetImageEncoders()
                        .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

                    using (var encParams = new EncoderParameters(1))
                    {
                        string thumbPath = "~/Images/Thumbnails";
                        bool isExists = System.IO.Directory.Exists(Server.MapPath(thumbPath));

                        if (!isExists)
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath(thumbPath));
                        }

                        var thumbPathFull = Path.Combine(Server.MapPath(thumbPath), file.FileName);
                        long quality = 100;
                        encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                        thumb.Save(thumbPathFull, jpgInfo, encParams);
                    }
                }
            }
        }

Friday, February 21, 2014

linq compare int with string

products = products.Where(p =>
                    SqlFunctions.StringConvert((double)p.ProductId).Trim() == searchString);