mercredi 30 septembre 2015

Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?

I have the following code/markup

@for (int m = 0; m < Model.Parts.Count; m++ ) {
    var item2 = Model.Parts[m];
    <tr id='@item2.WorkOrderPartId'>
        <td></td>
        <td style='text-align:center'> @item2.LineNo </td>
        <td> @item2.SalesOrderLineNo</td> 
        <td style='text-align:center'>
            @item2.Length
        </td> 
        <td style='width:100px;text-align:right'>
          </td> 
        <td style='width:100px;text-align:left'>
         </td>
         </td>
        <td style='padding-right:10px'>0</td>
        <td style='padding-right:10px'>0</td> 
    <td class='RemainingWeight'></td>
    <td>  </td> 
        </tr>
}

When this view get executed following error is getting OnException.

Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?

Please helpme? :(

Better way to handle connection string with Persist Security Info = True?

I ran into a bug in one part of my code when I'm trying to retrieve my connection string from web.config for opening connection.

This is my code:

var dbcontext = new System.Data.Entity.DbContext(_conStr.Database.Connection.ConnectionString);            
var conn = dbcontext.Database.Connection; ;            
var connState = conn.State;   
conn.Open();

After some investigation, I found the full error message as below in my SQL server log:

Login failed for user 'sa'. Reason: Password did not match that for the login provided. [CLIENT: ]

When I debug, I found the source of error. Below is my complete data source as stated in web.config.

data source=(localhost);initial catalog=Database1;integrated security=False;User id=sa;password=12345;

The issue is when I call _conStr.Database.Connection.ConnectionString for my dbcontext in my code above. When I check the value of my connection string, I found out that the password is missing, so it return the following connection string value: data source=(localhost);initial catalog=Database1;integrated security=False;User id=sa;

My password is missing in the return connection string value, but it's clearly listed in the web config.

After lots of investigation, I found the solution to make sure the password is there when I use ADO net connection property is to include Persist Security Info=True in my web.config. Then, my complete connection string can be called without any missing element.

This solve my earlier issue BUT I also found articles stated that Persist Security Info must not set the True for security purpose.

I had consulted my senior and he suggested to put remove the user Id and password from web.config, encrypt both user id and password value, and put them as an App Key, then modify the data source as below:

data source=(localhost);initial catalog=Database1;integrated security=False;Persist Security Info=True;User id={0};password{1};

When I call the data source from my code behind, I should get the encrypted user id and password App Key, decrypt them, then use string.format as below to reformat the string value:

string strConStr = string.Format(strConStr, strAppKeyUserId, strAppKeyPassword);

Now my question is, is my senior suggestion a suitable method to cater for Persist Security Info=True? I feels like it's the same but can't really tell the exact impact by applying the suggested method or not. Either way, as long as I'm setting Persist Security Info_True, the password will return back to the connection.

Also, a side note, I can't use System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString because the code above locate inside a repository solution that doesn't have web.config, only app.config. I can only format the connection string value in my application and pass the complete connection string value into the method.

Please enlighten me on this. Thank you.

web.config xtd is not transforming how it should

I'm trying to publish my site and I'm having problems.

My normal web.config file looks like this:

<system.web>
  <compilation targetFramework="4.5" debug="true">
       ...
  </compilation>
</system.web>

my web.config.release looks something like this:

<system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>

What it should look like when published:

<system.web>
  <compilation targetFramework="4.5">
       ...
  </compilation>
</system.web>

Unfortunately it is not removing the debug attribute when I publish the site. Does any body know as to why this is happening? Pretty sure I have it set-up how it should be. Also, other transformations are working, except for this one.

Issue while doing Login using AJax call in mvc

I am trying to do login with ajax call in mvc , its working fine but once the session expires,then I click on any page it navigates to Login page and then m not able to do Login. My JS code is as

function verifiedLogin() {

    loading();

    $.ajax({
        url: "Login/Proceed",
        cache: false,
        type: "POST",
        data: { UserName: document.getElementById('username').value, password: document.getElementById('password').value },
        dataType: "json",

        success: function (result) {

            //if (status.Success) {
            //alert('In SUccess');
            window.location.href = "/Home/SearchResult";
            //var a=window.location.href;
            //alert(a);
            //}
            //else {
            //    alert("Invalid Crediential");
            //    $('#overlay').remove();
            //}
        },
        error: function (result) {

            alert("Please enter valid credential ");
            $('#overlay').remove();
        }
    });

}

First time its working fine issue is when it logs me out after session expire, then my URL become

http://localhost:53791/Login/Login?ReturnUrl=%2fJob%2fSearchJobQueue

If I remove returnurl from the url then its working, but I don't know from where it is adding. Code in web.config

  <authentication mode="Forms">
  <forms loginUrl="~/Login/Login" defaultUrl="~/Home/SearchResult" timeout="1" slidingExpiration="true" />
</authentication>

How can I remove this?

Please suggest.

Pagination using Entity Framework through Web API

I have a class like this:

public class BE_CategoryBase
{
    public Int32 CategoryID { get; set; }
    public String CategoryName
    {
        get;
        set;
    }
    public String CategorySanitized { get; set; }
    public Boolean IsActive { get; set; }
    public DateTime? ModificationDate { get; protected set; }
    public Int64? ModifiedBy { get; set; }
}

In the Web API I have Action Method like this.

So far I am fetching all records from the server in single request. The above API call is Post because there are many filters being used. As the Get has limited length in query string...so I used Post.

[Route("api/v1/CategoryList"), HttpPost]
public async Task<IHttpActionResult> CategoryList([FromBody]BE_Category obj)
{
    var result = await _category.CategoryList(obj);

    if (!string.IsNullOrEmpty(result.Key))
        await _log.CreateLog(new BE_Logs { Message = result.Key });

    return Ok(new { ErrorMessage = result.Key, result = result.Value });
}

Now, In order to use Paging, I was thinking of adding startPage and PageSize columns in the BE_CategoryBase class. As I am using Entity Framework Code First, adding the column in the class will add these columns in Database Table also.

Is there any elegant way to implement paging with Post Action Method ?

NoLock in Entity Framework

I am trying to read the records from table even when the table is locked due to particular transaction.

I am using below code

public async Task<KeyValuePair<String, List<Om_Category>>> CategoryList(Om_Category obj)
{
    try
    {
        using (var transaction = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions 
                { 
                    IsolationLevel = IsolationLevel.ReadUncommitted 
                },
                TransactionScopeAsyncFlowOption.Enabled))
        {
            using (var categoryContext = new ModelGeneration())
            {

                categoryContext.Configuration.ProxyCreationEnabled = false;
                var data = await categoryContext
                    .tblCategory
                    .ToListAsync();

                transaction.Complete();

                return new KeyValuePair<String, List<Om_Category>>("", data);
            }
        }
    }
    catch (Exception ex)
    {
        return new KeyValuePair<String, List<Om_Category>>(ex.Message, null);
    }
}

But seems like I am missing something to implement NoLocks. Still it show timeout. Am I missing something ?

mardi 29 septembre 2015

i want to make data as image type in rdlc reports(pdf)

I want to make data as image rather than text so the user can't copy the text from pdf in rdlc reports.

 public FileResult DownloadArticle(int id)
    {
        SignalRDataContext srcontext = new SignalRDataContext();
        LocalReport localReport = new LocalReport();
        localReport.ReportPath = Server.MapPath("~/Report/Report1.rdlc");
        ReportDataSource reportDataSource = new ReportDataSource();
        localReport.EnableExternalImages = true;
        reportDataSource.Name = "DataSet1";
        reportDataSource.Value = srcontext.Articles.Where(x => x.ArticleID == id).Select(x => new { x.code, x.Article_Name }).ToList();
        localReport.DataSources.Add(reportDataSource);
        string reportType = "pdf";
        string mimeType;
        string encoding;
        string fileNameExtension = "pdf";
        Warning[] warnings;
        string[] streams;
        byte[] renderedBytes;
        renderedBytes = localReport.Render(reportType, "", out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
        Response.AddHeader("content-disposition", "attachment;filename=Membership." + fileNameExtension);
        return File(renderedBytes, fileNameExtension);
    }

lundi 28 septembre 2015

jqtree click event not working on partial view

I am using jqtree for filtering products through categories. It works during the first time I click a category. After selecting a category, I'll click the search button to display the Items data which is in partial view. Then when I will select another category to search for another set of data, The click event does not work anymore.

jquery code I used:

function SearchProducts() {
    var dataToSave = ko.toJSON({
        productname: $('#txtProductName').val(),
        categoryId: $('#lblCategoryID').text()
    });

    var url = '@Url.Action("AddEditProduct", "Inventory")';
        $.ajax(url, {
            data: dataToSave,
            type: "post",
            contentType: "application/json",
            success: function (result) {
                $("#addeditproduct").html(result);
            }
        });
    };

    $(function () {
    var url = '@Url.Action("GetCategoryTreeView","Inventory")'
    $('#SelectedCategoryID').text();

    $('#tree1').tree({
        dataUrl: url,
        autoOpen: 1,
        selectable: true
    });
});

$('#tree1').bind(
    'tree.click',
    function (event) {
        var node = event.node;
        SelectedCategory = '';
        lblParentID = '';
        lblParentName = '';
        $('#SelectedCategoryID').text('');
        lblParentID = node.ID;
        lblParentName = node.name;
        SelectedCategory = 'Category Selected: ' + node.name + ' (Category ID: ' + lblParentID + ')';
        $('#SelectedCategoryID').text(SelectedCategory);
        $('#lblCategory').text(node.name + ' (' + lblParentID + ')');
        lblCatID = lblParentID;
        $('#lblCategoryID').text(lblParentID)
    }
);

Code at controller for searching products

    [HttpPost]
    public ActionResult AddEditProduct(VMAddEditProduct viewModel)
    {
        var user = db.Users.Where(u => u.Username == this.User.Identity.Name).Single();
        dynamic items = null;
        if (viewModel.CategoryId != 0)
        {
            if (viewModel.ProductName != null && viewModel.ProductName != "")
            {
                items = (from product in db.tblFMSItems
                         join category in db.FMSCategory on product.CategoryID equals category.ID
                         where product.CenterID == user.CenterId
                         && product.CategoryID == viewModel.CategoryId
                         && product.ProductName == viewModel.ProductName
                         select new
                         {
                             CategoryId = product.CategoryID,
                             ProductId = product.ProductId,
                             ProductName = product.ProductName,
                             CategoryName = category.ProductType,
                             SKU = product.SKU,
                             Desc = product.Desc
                         })
                        .OrderBy(product => product.ProductName)
                        .ToList();
            }
            else
            {
                items = (from product in db.tblFMSItems
                         join category in db.FMSCategory on product.CategoryID equals category.ID
                         where product.CenterID == user.CenterId
                         && product.CategoryID == viewModel.CategoryId
                         select new
                         {
                             CategoryId = product.CategoryID,
                             ProductId = product.ProductId,
                             ProductName = product.ProductName,
                             CategoryName = category.ProductType,
                             SKU = product.SKU,
                             Desc = product.Desc
                         })
                            .OrderBy(product => product.ProductName)
                            .ToList();
            }
        }
        else if (viewModel.ProductName != null && viewModel.ProductName != "")
        {
            items = (from product in db.tblFMSItems
                     join category in db.FMSCategory on product.CategoryID equals category.ID
                     where product.CenterID == user.CenterId
                     && product.ProductName == viewModel.ProductName
                     select new
                     {
                         CategoryId = product.CategoryID,
                         ProductId = product.ProductId,
                         ProductName = product.ProductName,
                         CategoryName = category.ProductType,
                         SKU = product.SKU,
                         Desc = product.Desc
                     })
                    .OrderBy(product => product.ProductName)
                    .ToList();
        }
        else if ((viewModel.ProductName == null) && viewModel.CategoryId == 0)
        {
            items = (from product in db.tblFMSItems
                     join category in db.FMSCategory on product.CategoryID equals category.ID
                     where product.CenterID == user.CenterId
                     select new
                     {
                         CategoryId = product.CategoryID,
                         ProductId = product.ProductId,
                         ProductName = product.ProductName,
                         CategoryName = category.ProductType,
                         SKU = product.SKU,
                         Desc = product.Desc
                     })
                    .OrderBy(product => product.ProductName)
                    .ToList();
        }
        var results = new List<VMAddEditProduct>();



        foreach (var fmsitem in items)
        {
            var itemDesc = "";
            if (fmsitem.Desc != null && fmsitem.Desc.Contains("<br/>"))
            {
                itemDesc = fmsitem.Desc.Replace("<br/>", "\n");
            }
            else
            {
                itemDesc = fmsitem.Desc;
            }
            var result = new VMAddEditProduct();
            result.CategoryId = fmsitem.CategoryId;
            result.CategoryName = fmsitem.CategoryName;
            result.ProductId = fmsitem.ProductId;
            result.SKU = fmsitem.SKU;
            result.ProductName = fmsitem.ProductName;
            result.Desc = itemDesc;

            results.Add(result);
        }
        return View("~/Views/Report/AddEditProducts.cshtml", results);
    }

event change for enumdropdownlist

In view

@Html.EnumDropDownListFor(model => model.Field)

Model

public Fields Field { get; set; }

public enum Fields
{
    First = 1,
    Second
}

These my markup

<select id="Field" name="Field">
    <option selected="selected" value="1"> First</option>
    <option value="2">Second</option>
</select>

These script dont call

$('select#Field').change(function () {
    var orderIdd = $('#Field').val();
    alert(orderIdd);
});

Show column text as link based on some condition

I am using Kendo Grid to show the value. Now one of my field based on some condition wanted to show text as link and that link should refer to javascript function. Below is my code

 columns =>
                                          {
                                              columns.Bound(r => r.RequestCode).Width(110);
                                              columns.Bound(r => r.StaffId).Width(90);

                                              columns.Bound(r => r.StaffName).Width(130);
                                              columns.Bound(r => r.Company);

                                              columns.Bound(r => r.RequestType).Width(90);
                                              columns.Bound(r => r.NoofDays);

                                              columns.Bound(r => r.TravelStartDate).Format("{0:dd-MMM-yyyy}").Width(130);
                                              columns.Bound(r => r.TravelEndDate).Format("{0:dd-MMM-yyyy}").Width(130);

                                              columns.Bound(r => r.SLADays).Width(90);
                                              columns.Bound(r => r.AdvanceAmount).Width(130);

                                              //columns.Bound(r => r.Installments);
                                              columns.Bound(r => r.Installments).Width(90);

                                              //columns.Bound(r => r.RecoveryAmount);

                                              columns.Bound(r => r.RecoveryAmount).ClientTemplate("<span  id='vatId'> #= VATAmount=kendo.toString((Installments == 0 ? 0 : AdvanceAmount/Installments), 'n0') # </span>" +
                                              "<input type='hidden' class='VATAmount'  value='#=kendo.toString( (Installments == 0 ? 0 : AdvanceAmount/Installments), 'n0')#' />").Width(130);
                                              columns.Bound(r => r.WfStatusDesc).ClientTemplate("<a href=javascript:jsFoo(\'" + "#: RequestCode #" + "\')>#: WfStatusDesc #</a>").Title("Expense Status").Width(110);

                                              columns.Bound(r => r.PaidAmount).Visible(false);
                                              columns.Bound(r => r.DutyTravelID).Visible(false);
                                              columns.Bound(r => r.StaffSeqNumber).Visible(false);


                                            

                                          }
so in wfstatusDesc column i want that if text is equal to Approve then show as link else simple text. and if show link then after click on that link should call a javascript function with passed parameter of request id.

How to add the if condition to my Telerik Grid

I want to add the if condition to my Telerik Grid.

This is my code

 columns.Bound(p => p.PKCustID).ClientTemplate("#if(PKCustID!= 5){#" +
                   "<a href='" + Url.Action("Details", "Server") + "/#=ID#'>#=Name#</a>" +
                   "#} else {#" +
                   "another template" +
                   "# } #");

what is wrong with my code?

MVC Bind Checkboxes and then values on Checkbox Checked Changed [HttpPost]

Its very simple for professionals. Heres my modal

public class Photo

{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PhotoId { get; set; }
    [Display(Name = "Category Name")]
    [Required]
    public string CategoryName { get; set; }
    [Display(Name = "Decription")]
    [Required]
    public String Decription { get; set; }

    [Display(Name = "Image Path")]
    public String ImagePath { get; set; }

    [Display(Name = "Thumb Path")]
    public String ThumbPath { get; set; }


    [Display(Name = "Created On")]
    public DateTime CreatedOn { get; set; }


}

Step1) Bind Checkboxes using CategoryName

enter image description here

Step 2) Bind Values which is shown below in Grid structure and also implements view type

enter image description here

Step 3) Implementation of Paging

enter image description here

dimanche 27 septembre 2015

Similar application to "Architect Lite : Front-End HTML Builder" that compatible with ASP.NET MVC

My requirement is,

Create a Module to Design Flyers or Brochures dynamically , using front-end dashboard.

Once I design a specific template or design then click Generate Brochure Button I want to export that design as Image or PDF file .

Since this is complex task I've decided to integrate JQuery widget for my project

I want to know similar application that compatible with asp.net mvc like Architect Lite : Front-End HTML Builder

ASP.NET MVC Multi-language feature does not work as expected

I have the app working using Radio buttons e.g.

@using (Html.BeginForm("SetCulture", "Home"))
{
<input type="radio" name="culture" id="en-us" value="en-us" class="culture" /> English
<input type="radio" name="culture" id="tr" value="tr" class="culture" /> Türk
}

but when i use input of image type it does not send the wanted VALUE

@using (Html.BeginForm("SetCulture", "Home"))
{
<input type="image" src="~/Content/Images/en.png" name="culture" id="en-us" value="en-us" class="culture" /> 
<input type="image" src="~/Content/Images/tr.png" name="culture" id="tr" value="tr" class="culture" />
}

jQuery code:

$(".culture").click(function () {
     $(this).parents("form").submit(); // post form
});

HomeController Code:

public ActionResult SetCulture(string culture){
    // action code here
}

I see no reason why the images wouldn't work but for some reason it happens. Any ideas?

Thank you so much

samedi 26 septembre 2015

Remove debug attribute in Web.Config.Release

My web.config.release looks something like this:

<system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>

This is what it should render, but it's not:

<system.web>
  <compilation debug="true" targetFramework="4.5">
       ...
  </compilation>
</system.web>

When I publish I am using the publish option as release. Not sure if the ftp method has anything to do with it, but other transformations are rendering just fine. Not sure what's wrong with this because it's still showing this attribute in my released config when publishing.

BuildCoreAdmin solrnetfacility is returning nullpointer exception

need to do swapping of my cores and hence need to set the SolrCoreAdmin in my solrFacility, so i can use it throughout my application using my windsor container.

When I do the following :

var solrFacility = new SolrNetFacility(ConfigurationSettings.ContentSearch_Solr_ServiceBaseAddress);

            solrFacility.AddCore(AgentsIndex.IndexName, typeof(AgentsIndexMapper), ConfigurationSettings.ContentSearch_Solr_ServiceBaseAddress +"/"+ AgentsIndex.IndexName);
            solrFacility.AddCore(AgentsIndex.SwapIndexName, typeof(AgentsIndexMapper), ConfigurationSettings.ContentSearch_Solr_ServiceBaseAddress + "/" + AgentsIndex.SwapIndexName);
            solrFacility.BuildCoreAdmin(ConfigurationSettings.ContentSearch_Solr_ServiceBaseAddress);
                _WindsorContainer.AddFacility("solr", solrFacility);

I get following error:

[NullReferenceException: Object reference not set to an instance of an object.] Castle.Facilities.SolrNetIntegration.SolrNetFacility.BuildCoreAdmin(ISolrConnection conn) +40

I looked up the code inside BuildCoreAdmin using reflector and I think its trying to access a base.Kernel...is that null? How do I set that kernel? The base file is AbstractFacility and that has a function setKernel. What should this kernel be?

How do i solve this? im new to solrnet and need your help. Thanking you. Regards, Kasturi Chavan

Style css for MVC Checkboxlist using Bootstrap

How to apply css to

@Html.CheckBoxList((ViewBag.checklist as List < SelectListItem >))

MVC HtmlHelper Code

public static class CheckBoxListExtension

{
    public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, IEnumerable<SelectListItem> listOfValues)
    {
        var sb = new StringBuilder();

        if (listOfValues != null)
        {
            sb.Append("<table>");

            foreach (var item in listOfValues)
            {
                sb.Append("<tr>");

                var label = htmlHelper.Label(item.Value, HttpUtility.HtmlEncode(item.Text));
                var checkbox = htmlHelper.CheckBox(item.Text, new { id = item.Value }).ToHtmlString();

                sb.AppendFormat("{0}{1}", "<td>" + checkbox + "</td>", "<td>" + label + "</td>");

                sb.Append("</tr>");
            }
        }
        sb.Append("</table>");
        return MvcHtmlString.Create(sb.ToString());
    }


}

vendredi 25 septembre 2015

MVC3 Telerik grid save into database

In MVC3 VS 2010, I have telerik grid view, add, edit and update in session repository, the logic i implemented from Telerik samples. But its working only in session. I need to update this into the relevent table. Kindly advice how to proceed where to add context.SaveChanges(); ?

MVC Project Page inspector: No mapping data was returned from the server

I am try to run this old MVC project created sometime between 2010-2011. It initially used Reference of System.Web.MVC 3.0.0.0, which is out-dated. Therefore, I made changes and updated to MVC 3 version: 3.0.50813.1, that cleared up the error. Then for some reason, When I try to run it, It keeps looping and says

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll A first chance exception of type 'System.Data.EntityCommandExecutionException' occurred in System.Data.Entity.dll*

Then I did Page Inspection,It displayed :No mapping data was returned from the server. Initially, I though the problem was with the Network access security, but this account has a full access. Currently wondering, How I should approach this problem!!.

Use built in element highlighting with custom editor control

When using the standard TextBoxFor helper methods if the field as validation, and that validation fails the input element gets the css class to highlight it in red.
I want to do the same thing for my custom editor.

The editor consists of a hidden input element and a textbox that acts as a dropdown using jquery.

I want the MVC validation to highlight the textbox, which as a custom id. How can I achieve this?

jeudi 24 septembre 2015

Management of Views Folder in MVC Razor

I am using ASP.NET MVC Razor C#. There are 2 Controllers in the Project

  1. User Controller
  2. Account Controller

There exists one action method in each controller. Then I created the Views for each of them and finally that created folders in their respective directories in View Folder.

Question: Is it possible If I create the Folder called Users in Views Folder and drag and drop the Controller Folders in User Folders ?

In MVC3 how do I get validation messages to use my custom ModelMetadataProvider?

I have a custom ModelMetadataProvider, which sets the displayname based on adding spaces after capital letters in the property name:

public class ModelMetadataProviderPlus : ModelMetadataProvider
{
    private readonly ModelMetadataProvider _BaseProvider;

    public ModelMetadataProviderPlus(ModelMetadataProvider baseProvider)
    {
        _BaseProvider = baseProvider;
    }

    private void SetMissingDisplayName(ModelMetadata modelMetaData)
    {
        if (modelMetaData.DisplayName == null && modelMetaData.PropertyName != null)
        {
            modelMetaData.DisplayName = modelMetaData.PropertyName.AddSpacesAfterCaps();
        }
    }

    public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)
    {
        var Result = _BaseProvider.GetMetadataForProperties(container, containerType);

        return Result.Select(r =>
        {
            SetMissingDisplayName(r);
            return r;
        });
    }

    public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
    {
        var Result = _BaseProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);

        SetMissingDisplayName(Result);

        return Result;
    }

    public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)
    {
        var Result = _BaseProvider.GetMetadataForType(modelAccessor, modelType);

        SetMissingDisplayName(Result);

        return Result;
    }
}

I configure the MVC framework to use it using

ModelMetadataProviders.Current = new ModelMetadataProviderPlus(ModelMetadataProviders.Current);

This all works fine, however the validation error messages don't seem to use this provider, as the error message for the [Required] attribute says (for example): The DefectCount field is required..

I use nInject, so i tried doing:

kernel.Bind<ModelMetadataProvider>().ToConstant(new ModelMetadataProviderPlus(ModelMetadataProviders.Current));

but although the labels etc. appeared correctly the validation messages still didn't.

I've searched for a while now and although I've found a couple of places where the same issue is noted, I can't find anything with a solution.

mercredi 23 septembre 2015

Server Error in '/' Application. A generic error occurred in GDI+

Working on localhost but not on server. All permissions are set on godaddy for GalleryImages folder. When runs

public ActionResult Create(Photo photo, IEnumerable<HttpPostedFileBase> files)
{
    if (!ModelState.IsValid)
        return View(photo);
    if (files.Count() == 0 || files.FirstOrDefault() == null)
    {
        ViewBag.error = "Please choose a file";
        return View(photo);
    }

    var model = new Photo();
    foreach (var file in files)
    {
        if (file.ContentLength == 0) continue;

        model.CategoryName =photo.CategoryName;
        model.Decription = photo.Decription;
        var fileName = Guid.NewGuid().ToString();
        var extension = System.IO.Path.GetExtension(file.FileName).ToLower();

        using (var img = System.Drawing.Image.FromStream(file.InputStream))
        {
            model.ThumbPath = String.Format("/GalleryImages/thumbs/{0}{1}", fileName, extension);
            model.ImagePath = String.Format("/GalleryImages/{0}{1}", fileName, extension);


            SaveToFolder(img, fileName, extension, new Size(200, 200), model.ThumbPath);

            SaveToFolder(img, fileName, extension, new Size(600, 600), model.ImagePath);

        }

        model.CreatedOn = DateTime.Now;
        db.Photos.Add(model);
        db.SaveChanges();
    }

    return View("Index");
}

Redirect Page based on dropdown information in ASp.NET mvc

I have a dropdown control have two type of values 'Contractor' and 'Full time', based on the dropdown selection relevant controls will be displayed.

Now when i click on the submit button i have to redirect to different action method (i.e) when 'Contractor' is selected it should redirect to AddContractor() else it should redirect to Full time along with the filled information.

How to implement it using single Html.Beginform()

Perform multiple Task async

I am using ASP.NET MVC Razor c#. I am saving the data in Database using async like below.

public async Task<ActionResult> CreateTask(VM_CreateTask project)
{
    var result = await _project.CreateTask(obj);
    return new EmptyResult();
}

This is working fine. So far ok.

There are some very large file that need to be uploaded after creating the record.

I found this link to upload the files Async

Question:

Is it possible to save the large file inside same Action Method using async ? Here one more challenge is that the CreateTask returns TaskID. I am creating the folders based on TaskID. So I have to wait for the Task completion to start Task files upload under the TaskID Folder

Unobtrusive Validation for dropdown list with multiple selection option

View Model

public class VM_CreateProject
{
    [Range(1, Int32.MaxValue, ErrorMessage = "Please select the Category")]
    public Int32 CategoryID { get; set; }

    [Required(ErrorMessage = "Please select at least one item")]
    public string[] SkillID { get; set; }
}

Razor View

@using (Html.BeginForm("CreateProject", "user", FormMethod.Post, new
                {
                    @class = "form-horizontal form-label-left"
                }))
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        <div class="col-md-12 col-sm-12 col-xs-12">
            @Html.DropDownListFor(i => i.CategoryID, categoryItems, new
                       {
                           @class = "form-control",

                       })
            <span> @Html.ValidationMessageFor(i => i.CategoryID)</span>

        </div>
    </div>
    <div class="form-group">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <select id="SkillID" multiple="multiple" class="form-control" name="SkillID">
                <option value="-1">Select Skills</option>
            </select>
            <span> @Html.ValidationMessageFor(i => i.SkillID)</span>
        </div>
    </div>
}

JQuery code that goes to server to fetch the skills

<script>
    $(function () {
        $('#CategoryID').change(function () {
            var mySelect = $('#SkillID');
            mySelect[0].options.length = 0;
            $.ajax({
                url: "/SkillListByCategoryID",
                type: "POST",
                data: JSON.stringify({ 'categoryID': this.value }),
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data.Success) {
                        if (data.val != null) {
                            $.each(data.val, function (val, text) {
                                mySelect.append(
                                    $('<option></option>').val(text.SkillID)
                                              .html(text.Skill)
                                );
                            });
                        }
                    }
                    else {
                        alert(data.key);
                    }
                },
                error: function (data) {
                    alert("An error has occured!!!");
                    $('#imgSkillListByCategoryID').css('display', 'none');
                }
            });
        });
    });

</script>

Validation for Category is successfully applied through Unobtrusive. But for the Skills (Multiple selection) is not working.

Is there anything missing in the code ?

RediretToAction doesn't work - MVC 3

I'm trying to redirect to another action but it's not working. The action is called but the return View() doesn't change the screen.

[HttpPost]
public ActionResult Login(LoginViewModel vm)
{
     return RedirectToAction("AlterarSenhaPadrao", new { Id = usuario.Id });
}

public ViewResult AlterarSenhaPadrao(int Id)
{
    return View(new AlterarSenhaViewModel { UsuarioId = Id });
}

Looking at the Developer Tools on Chrome, I get this:

enter image description here

So, the action is called but it doesn't return the view properly. By the way, my controller is not assigned with [Authorize]. Any ideia about why is this happening?

Thanks

UPDATE

//Shows the login page
public ActionResult Login()
{
    return View(new LoginViewModel());
}

//The submit action, the same I posted below.
[HttpPost]
public ActionResult Login(LoginViewModel vm)
{

}

And my login page: enter image description here

create registration form template and save as ms word file in asp.net mvc

I want to create registration form template which can include few fields

Here the scenario

  1. Once I come to this view page,I can check following check boxes

enter image description here

  1. Then Click Create Template I can Download it as Microsoft Word File

These fields can be in varies types.

Example

  • Product Name - TextBox
  • Description - TextArea
  • Product Features - TextBox (5 list down text boxes)
  • etc ....

likewise those fields can be vary. If I select first 2 checkboxes . and Click **Create Template* , I should be getting a registration form look like below.


                         Registration Form

Product Name : .............................................................................

Product Description : 
............................................................................................
............................................................................................
............................................................................................

Prodcut Features :

.........................................................

.........................................................

.........................................................

.........................................................

.........................................................


I want to know is there any 3rd party tool or any good resource to perform task like this.

Javascript list passing to c#

I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32. The problem is the list is either empty or does not pass. I tried to use stringify but it doesn't fill the requirments.

Here is the code from the javascript part:

$('#AddColumn').click(function () {

    var nodeURL = document.getElementById("IDHolder").innerHTML;
    var nodeConfig= nodeURL+".CONFIG";
    var nodeAdd=nodeURL+".CONFIG.AddColumn";
    var nodeName = $("#ColumnName").val();
    var nodeType = $("#ColumnType").data("kendoComboBox").value();
    var ListNodedet = [nodeName, nodeType];
    var Listmet = [nodeConfig, nodeAdd];
    var ListNodeDetails = JSON.stringify(ListNodedet);

    var ListMethod = JSON.stringify(Listmet);

    var select = 1;
    var url = "/Configuration/CallMethod";

    $.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
        $("#Data2").html(data);
    });
})

The C# code for the controller were it calls another method in models:

 public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
    {
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
        return AddMethod;
    }

The Model:

public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
    {
        var serverInstance = GetServerInstance(iPAddress);
        if (serverInstance == null)
            return false;
        return serverInstance.CallMethod(ListNodeDetails, ListMethod);

    }

The service model

     public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
    {
        try
        {
            if (_mSession == null)
            {
                return false;
            }
            NodeId objectID = NodeId.Parse(ListMethod[0]);
            NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
            List<Variant> inputArguments = ListNodeDetails;

            List<StatusCode> inputArgumentErrors = null;
            List<Variant> outputArguments = null;
            StatusCode error = _mSession.Call(
                objectID,
                Methodtype,
                inputArguments,
                new RequestSettings() { OperationTimeout = 10000 },
                out inputArgumentErrors,
                out outputArguments);
            if (StatusCode.IsBad(error))
            {
                Console.Write("Server returned an error while calling method: " + error.ToString());
                return false;
            }
            return true;
        }
        catch (Exception exception)
        {

            Console.WriteLine(exception.ToString());
            return false;
        }

    }

At the end it calls some functions using OPC UA to add data.

Unobtrusive Validation for dropdown list with multiple selection option

View Model

public class VM_CreateProject
{
    [Range(1, Int32.MaxValue, ErrorMessage = "Please select the Category")]
    public Int32 CategoryID { get; set; }

    [Required(ErrorMessage = "Please select at least one item")]
    public string[] SkillID { get; set; }
}

Razor View

@using (Html.BeginForm("CreateProject", "user", FormMethod.Post, new
                {
                    action = "/CreateProject",
                    id = "CreateProject",
                    @class = "form-horizontal form-label-left"
                }))
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        <div class="col-md-12 col-sm-12 col-xs-12">
            @Html.DropDownListFor(i => i.CategoryID, categoryItems, new
                       {
                           @class = "form-control",
                           @id = "CategoryID",
                           @Name = "CategoryID"
                       })
            <span> @Html.ValidationMessageFor(i => i.CategoryID)</span>

        </div>
    </div>
    <div class="form-group">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <select id="SkillID" multiple="multiple" class="form-control" name="SkillID">
                <option value="-1">Select Skills</option>
            </select>
            <span> @Html.ValidationMessageFor(i => i.SkillID)</span>
        </div>
    </div>
}

Validation for Category is successfully applied through Unobtrusive. But for the Skills (Multiple selection) is not working.

Is there anything missing in the code ?

Trying to get the Selected checkbox values with the ID value

Below is the Model

public class M_ProjectType
{
    public Int16 ProjectTypeID { get; set; }
    public String ProjectType { get; set; }
    public Boolean IsActive { get; set; }
    public Decimal Cost { get; set; }
    public String Description { get; set; }
    public Boolean IsChecked { get; set; }
}

Below is View Model

public class VM_Project
{
    public string[] SkillID { get; set; }

    public List<M_ProjectType> ProjectType { get; set; }
}

Below is Get Action method. here I am getting the data for projects that will be sent to View Model

[HttpGet, Route("Project")]
public async Task<ActionResult> Project()
{
    var projectTypes = (await _projectTypes.ProjectTypesList()).Value;

    var list = new List<M_ProjectType>();
    foreach (var item in projectTypes)
    {
        list.Add(new M_ProjectType
            {
                Cost = item.Cost,
                Description = item.Description,
                IsActive = item.IsActive,
                IsChecked = false,
                ProjectType = item.ProjectType,
                ProjectTypeID = item.ProjectTypeID
            }
        );
    }
    var project = new VM_Project
    {
        ProjectType = list
    };

    return View(project);
}

Below is Razor View

@foreach (var item in Model.ProjectType)
{
    <table class="table table-striped">
        <tbody>

            <input type="hidden" value="@item.ProjectTypeID" name="ProjectTypeID" />
            <tr>
                <td style="width:5%">
                    @Html.CheckBoxFor(i => item.IsChecked, new { @class = "tableflat" })
                    @Html.HiddenFor(i => item.ProjectTypeID)
                </td>
                <td style="width:10%">@item.ProjectType</td>
                <td style="width:80%">@item.Description</td>
                <td style="width:5%"><b>$@item.Cost</b></td>
            </tr>

        </tbody>
    </table>
}

Below is Post Action Method

[HttpPost, Route("Project")]
public ActionResult Project(VM_Project project)
{
    return View();
}

Question: I am getting project.ProjectType = null. Any suggestion why this is happening ?

mardi 22 septembre 2015

Entity Framework Include no longer functioning

I have a MVC 3 EF 4.1 project and just installed .Net 4.5 on the server.

The query:

db.Notes
     .Include(x => x.PostedUser)
     .Include(x => x.LastEditedUser)
     .Where(x => x.ProjectId == projectId)
     .ToList();

Before I upgraded .Net to 4.5, this query would return records with or without a related LastEditedUser.

Now, the query only returns records where there is a LastEditedUser.

Removing the .Include(x => x.LastEditedUser) fixes the issue, but I don't know why it stopped working.

Any ideas?

How to reach asp configuration tools in visual studio 2015

I worked with this top solution provided on the stack over flow till now Visual Studio 2013 and ASP.NET Web Configuration Tool. I used it perfectly but now i have stuck in another problem having an internal error like "CS0122: 'System.Configuration.StringUtil' is inaccessible due to its protection level" Any help please....

jqtree click event not working on partial view

I am using jqtree for filtering products through categories. It works during the first time I click a category. After selecting a category, I'll click the search button to display the Items data which is in partial view. Then when I will select another category to search for another set of data, The click event does not work anymore.

jquery code I used:

function SearchProducts() {
    var dataToSave = ko.toJSON({
        productname: $('#txtProductName').val(),
        categoryId: $('#lblCategoryID').text()
    });

    var url = '@Url.Action("AddEditProduct", "Inventory")';
        $.ajax(url, {
            data: dataToSave,
            type: "post",
            contentType: "application/json",
            success: function (result) {
                $("#addeditproduct").html(result);
            }
        });
    };

    $(function () {
    var url = '@Url.Action("GetCategoryTreeView","Inventory")'
    $('#SelectedCategoryID').text();

    $('#tree1').tree({
        dataUrl: url,
        autoOpen: 1,
        selectable: true
    });
});

$('#tree1').bind(
    'tree.click',
    function (event) {
        var node = event.node;
        SelectedCategory = '';
        lblParentID = '';
        lblParentName = '';
        $('#SelectedCategoryID').text('');
        lblParentID = node.ID;
        lblParentName = node.name;
        SelectedCategory = 'Category Selected: ' + node.name + ' (Category ID: ' + lblParentID + ')';
        $('#SelectedCategoryID').text(SelectedCategory);
        $('#lblCategory').text(node.name + ' (' + lblParentID + ')');
        lblCatID = lblParentID;
        $('#lblCategoryID').text(lblParentID)
    }
);

Code at controller for searching products

    [HttpPost]
    public ActionResult AddEditProduct(VMAddEditProduct viewModel)
    {
        var user = db.Users.Where(u => u.Username == this.User.Identity.Name).Single();
        dynamic items = null;
        if (viewModel.CategoryId != 0)
        {
            if (viewModel.ProductName != null && viewModel.ProductName != "")
            {
                items = (from product in db.tblFMSItems
                         join category in db.FMSCategory on product.CategoryID equals category.ID
                         where product.CenterID == user.CenterId
                         && product.CategoryID == viewModel.CategoryId
                         && product.ProductName == viewModel.ProductName
                         select new
                         {
                             CategoryId = product.CategoryID,
                             ProductId = product.ProductId,
                             ProductName = product.ProductName,
                             CategoryName = category.ProductType,
                             SKU = product.SKU,
                             Desc = product.Desc
                         })
                        .OrderBy(product => product.ProductName)
                        .ToList();
            }
            else
            {
                items = (from product in db.tblFMSItems
                         join category in db.FMSCategory on product.CategoryID equals category.ID
                         where product.CenterID == user.CenterId
                         && product.CategoryID == viewModel.CategoryId
                         select new
                         {
                             CategoryId = product.CategoryID,
                             ProductId = product.ProductId,
                             ProductName = product.ProductName,
                             CategoryName = category.ProductType,
                             SKU = product.SKU,
                             Desc = product.Desc
                         })
                            .OrderBy(product => product.ProductName)
                            .ToList();
            }
        }
        else if (viewModel.ProductName != null && viewModel.ProductName != "")
        {
            items = (from product in db.tblFMSItems
                     join category in db.FMSCategory on product.CategoryID equals category.ID
                     where product.CenterID == user.CenterId
                     && product.ProductName == viewModel.ProductName
                     select new
                     {
                         CategoryId = product.CategoryID,
                         ProductId = product.ProductId,
                         ProductName = product.ProductName,
                         CategoryName = category.ProductType,
                         SKU = product.SKU,
                         Desc = product.Desc
                     })
                    .OrderBy(product => product.ProductName)
                    .ToList();
        }
        else if ((viewModel.ProductName == null) && viewModel.CategoryId == 0)
        {
            items = (from product in db.tblFMSItems
                     join category in db.FMSCategory on product.CategoryID equals category.ID
                     where product.CenterID == user.CenterId
                     select new
                     {
                         CategoryId = product.CategoryID,
                         ProductId = product.ProductId,
                         ProductName = product.ProductName,
                         CategoryName = category.ProductType,
                         SKU = product.SKU,
                         Desc = product.Desc
                     })
                    .OrderBy(product => product.ProductName)
                    .ToList();
        }
        var results = new List<VMAddEditProduct>();



        foreach (var fmsitem in items)
        {
            var itemDesc = "";
            if (fmsitem.Desc != null && fmsitem.Desc.Contains("<br/>"))
            {
                itemDesc = fmsitem.Desc.Replace("<br/>", "\n");
            }
            else
            {
                itemDesc = fmsitem.Desc;
            }
            var result = new VMAddEditProduct();
            result.CategoryId = fmsitem.CategoryId;
            result.CategoryName = fmsitem.CategoryName;
            result.ProductId = fmsitem.ProductId;
            result.SKU = fmsitem.SKU;
            result.ProductName = fmsitem.ProductName;
            result.Desc = itemDesc;

            results.Add(result);
        }
        return View("~/Views/Report/AddEditProducts.cshtml", results);
    }

VoteTrust Algorithm

I am doing an IEEE Project called VoteTrust: Leveraging Friend Invitation Graph to Defend against Social Network Sybils. I want to detect Sybil accounts. For That purpose i am I am assigning a vote capacity that each user can send request.and i am propagating the vote capacity through real users. So for selecting real users i want to calculate trust of each user.For calculating trust i need to get the In degree and Out degree ( number of send request and receive request ) of each user. So please tell me how to calculate it . I heard about Page algorithm and trust Rank algorithm. I am very beginner in coding . so please some one help me to do that? I am doing this project in .net

lundi 21 septembre 2015

How to bind kendo telrick grid dynamicale using mvc

This is the model part:- I have taken one list and string list for column value and string for column hearder

 public class MRAprofileGridNew
    {
        public string DBColumnName { get; set; }
        public List<string> DBColumnvalue { get; set; }


    }

This is CONTROLLER parts:-model is return over here

public ActionResult RiskScorePatientData([DataSourceRequest]DataSourceRequest request, string ACOName)
        {
            return Content(reportRepository.MedicalRiskScorePatientData(User.EmailId, ACOName).KendoJsonResult(request), "application/json");
        }

View Part:- Her i want to bind the data dynamicale here i have struck how to bind data dynamicale

@model string

    @{

        Guid guid = Guid.NewGuid();
        string gridId = "MRAReportRiskScorePatientData_" + Model.Replace(" ", string.Empty);
    }
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="reportGrid">

        @*@if (!string.IsNullOrEmpty(Model))
            {*@
        @(Html.Kendo().Grid<Guardian.Core.Model.ViewModels.MRAprofileGridNew>()
                            .TableHtmlAttributes(new { @class = "table table-condensed Patient-Grid" })
                                  .Name("N Florida Physicians Trust")
                    .ToolBar(tb =>
                    {
                        tb.Excel().HtmlAttributes(new { @class = "btn btn-danger btn-xs pull-right " });

                    })
                    .Columns(columns =>
                    {

                           columns.Bound(p => p.FirstName).Title("First Name").Width(90);
                            columns.Bound(p => p.LastName).Title("Last Name").Width(90);
                            columns.Bound(p => p.HICN).Title("HICN").Width(70).HtmlAttributes(new { @class = "text text-left" });
                            columns.Bound(p => p.year).Title("Year").Width(50).HtmlAttributes(new { @class = "text text-right" });
                            columns.Bound(p => p.ProviderName).Title("Provider Name").Width(200);
                           columns.Bound(p => p.ACOID).Title("ACOID").Width(50).HtmlAttributes(new { @class = "text text-left" });
                            columns.Bound(p => p.V22MedicalRiskScore).Width(10).HtmlAttributes(new { @class = "text text-right" }).HeaderTemplate("<span class='kh-Grid-tooltip' data-toggle='tooltip' data-placement='top' title='CMS-HCC V22 Risk Score'>CMS-HCC V22 RS</span>");
                           columns.Bound(p => p.RxRiskScore).Width(20).HtmlAttributes(new { @class = "text text-right" }).HeaderTemplate("<span class='kh-Grid-tooltip' data-toggle='tooltip' data-placement='top' title='RxRiskScore'>RxRscore</span>");
                          columns.LoadSettings(Model.DBColumnvalue);


                    })
                    .Excel(excel => excel
                    .FileName("")
                    .Filterable(true)
                    .AllPages(true))

                    .Filterable()
                    .Pageable()
                    .Sortable()
                            .Events(events => events.DataBound("onDataBoundPreservePatientGrid"))
                    .Filterable()
                    .DataSource(dataSource => dataSource
                        .Ajax()
                        .Model(model =>
                        {
                            //Define the model
                            foreach (var column in Model)
                            {
                                Model.Field(column.DBColumnvalue);
                            }
                        })
                        .PageSize(10)
                                        .Read(read => read.Action("RiskScorePatientData", "Reports", new { ACOName = "Florida Physician Trust" }))
                                .ServerOperation(false)
                    )

                     .Resizable(resize => resize.Columns(true))
                     .Reorderable(reorder => reorder.Columns(true))
        )
        @*// }*@
    </div>

How to create Database from code first approach - Entity Framework

Looking at example it looks very simple but I am not able to create database using code first approach.

My code: Model

public class Books
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

Context:

public class BookDBContext : DbContext
    {
        public DbSet<Books> Books { get; set; }
        public BookDBContext()
            : base("name=BookDBContext")
        {
        }
    }

Controller code:

public ViewResult CodeFirst()
        {
            BookDBContext context = new BookDBContext();
            List<Books> result = new List<Books>();
            result =context.Books.ToList();
            return View();
        }

Config:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EF-20150919111248;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EF-20150919111248.mdf" providerName="System.Data.SqlClient" />
    <add name="NorthwindEntities" connectionString="metadata=http://res*/Controllers.EF.csdl|res*/Controllers.EF.ssdl|res*/Controllers.EF.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Northwind;user id=imad;password=imad123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="DBEntities" connectionString="metadata=http://res*/Controllers.DB.csdl|res*/Controllers.DB.ssdl|res*/Controllers.DB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Northwind;user id=imad;password=imad123;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="DBEEntities" connectionString="metadata=http://res*/Models.DB.csdl|res*/Models.DB.ssdl|res*/Models.DB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Northwind;user id=imad;password=imad123;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="BookDBContext" connectionString="Data Source=.;Initial Catalog=Sample;User Id=imad;Password=imad123;" providerName="System.Data.EntityClient"/>
  </connectionStrings>

Last one is mine.

Debugger comes and goes out of controller. No DB created in ssms no edmx generated. What else I need to do?

Update

I had not installed EF using Nuget. Just referenced EntityFramework.dll from other app. But it's working in Schema First approach.

Thanks.

Register event listener for the particular NHibernate Session

In my asp.net mvc application session factory is cached on application level. Than new session is created and closed on each request. Unfortunately logging service which is subscribed on PostUpdate, PostInsert events of the session factory requires current user id. Thus it is created in request scope. So it's possible that more than one instance of the logging service exists at the same time and listen events from the session factory/session (in case if more than one request is handled at the same time). As a result changes of one user will raise event on session factory which will be stored by all existing instances of the logger service.

The solution could be subscribing on session rather than on session factory. This will shrink scope of the logger service's dependencies to a single request's scope.

My questions is: Is there any way to register event listener for particular nhibernate session rather than for whole session factory?

Passing Parameters in URL containing special characters using javascript [duplicate]

This question already has an answer here:

Hi I am trying to call an action result in my controller containing parameters, but whenever one of these parameter contains # sign(special character) the string parameters does not include # sing in parameter and Next all parameters are set to null.

Following is my java script through which i am calling my action result.

    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnExport').unbind().click(function () {
                var url = @Url.Content("~/BankStatement/ExportBankStatementSummary") +
                    "?legalName=" + '@ViewBag.LegalName' +
                    "&dba=" + '@ViewBag.DBA' + 
                    "&contactPerson=" + '@ViewBag.ContactPerson' +
                    "&address=" + '@ViewBag.Address' + 
                    "&period=" + '@ViewBag.Period' +
                    "&totalHeading=" + '@ViewBag.TotalHeading';
                window.location = url;
            });
        });
    </script>

This is the action result that is called in this java script

public ActionResult ExportBankStatementSummary(string legalName, string dba, 
                                               string contactPerson, string address, 
                                               string period, string totalHeading)
    {
        ViewBag.LegalName = legalName;
        ViewBag.DBA = dba;
        ViewBag.ContactPerson = contactPerson;
        ViewBag.Address = address;
        ViewBag.Period = period;
        ViewBag.TotalHeading = totalHeading;

        ...

The problem is that in the action result parameters, when ever any of the parameter contains any special character (# in this case) then that parameter and next parameters becomes null.

For example if address is "Street # 2" then parameter address becomes "Street " and next parameters period and totalHeading becomes null.

Any help will be highly appreciated.

Thanks in advance.

Pass parameters to actionresult from jsonresult

I wrote code to filter results like following image ,

enter image description here

once after it filter I want to send model values of following field as parameters to another controller method, I can call that method once I click Generate Report button

this is view file

    @model project_name.Models.SearchVM

    @{
        ViewBag.Title = "Product_Incomplete_Search";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h4>Report of incomplete product profile</h4>

    @using (Html.BeginForm())
    {

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group"></div>


        <div class="row">

            <div class="col-xs-6">
                <div class="form-group">
                    @Html.LabelFor(m => m.Type, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            ...............



        <div class="row">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="button" value="Generate Report" class="btn btn-success submit" onclick="location.href='@Url.Action("ReportExport", "Home", new { type = Model.Type , ............. })'" /> &nbsp; <button id="search" type="button" class="btn btn-success submit">Search</button>
                </div>                      
            </div>
        </div>



    }
<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Product name</th>
            <th>Type</th>
            .........
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="table"></tbody>
</table>

<table id="template" class="table" style="display: none;">
    <tr>
        <td></td>
        <td></td>
        <td></td>
        ........
        <td><a>Edit</a></td>
    </tr>
</table>   


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")



    <script type="text/javascript">
        $(function () {
            $('.datepicker').datepicker({
                dateFormat: 'yy/mm/dd', changeMonth: true,
                changeYear: true, yearRange: '1910:2015'
            });
        });
    </script>

    <script type="text/javascript">

        var url = '@Url.Action("FetchProducts")';
        var editUrl = '@Url.Action("Edit")';
        var type = $('#Type');
        ..............

        var template = $('#template');
        var table = $('#table');
        $('#search').click(function () {
            table.empty();
            $.getJSON(url, { type: type.val(), ......, function (data) {
                $.each(data, function (index, item) {
                    var clone = template.clone();
                    var cells = clone.find('td');
                    cells.eq(0).text(item.ID);
                    cells.eq(1).text(item.Name);
                    cells.eq(2).text(item.Type);
                    ........................
                    cells.eq(7).text(item.Status);
                    var href = '@Url.Action("Edit")' + '/' + item.ID;
                    cells.eq(8).children('a').attr('href', href);
                    table.append(clone.find('tr'));
                });
            });
        });
    </script>


}

I want to call and send parameters to ReportExport method once I click Generate Report button

But I'm getting null values , I think this is because of I'm doing searching using Json , So How can I get Type value and send that as parameter ,

[HttpGet]
public ActionResult ReportExport(string id, string type, ...........)
{

dimanche 20 septembre 2015

Removing or Replacing # (hash) in URL using Regex

I'm new to regex and I'm using it in jquery to remove/replace the url but when i triggered an anchortag with href="#" the url will add a # and I'm not able to replace it with my current regex fix to replace the url.

http://localhost:3131/Main/MainPage?a=1221#&ab=&ac=

the original link onload is

http://localhost:3131/Main/MainPage?a=1221

but after triggering an anchortag with href="#" return, it becomes this:

http://localhost:3131/Main/MainPage?a=1221#

and my expected result upon removing the hash(#) in my url is this:

http://localhost:3131/Main/MainPage?a=1221&ab=&ac=

heres my function for replacing the url when closing modal windows in jquery

function updateQueryStringParameter(uri, key, value, key1,value1) {
            var re = new RegExp("([?&])" + key + "=.*?(&|$)" + key1 + "=.*?(&|$)", "i");
            var separator = uri.indexOf('?') !== -1 ? "&" : "?";
            if (uri.match(re)) {
                return uri.replace(re, '$1' + key + "=" + value + '$2' + key1 + "=" + value1 + '$3' );
                }
            else {
                return uri + separator + key + "=" + value + separator + key1 + "=" + value1;
              }
          };

Hope someone can help me as i am a beginner on using Regular expression specially in jquery.

Thanks!

samedi 19 septembre 2015

How to securely show an auto-generated password in MVC 4?

I have most of my MVC 4 web application ready. I have even developed the password auto-generation algorithm. Now I am stuck as to how to show this password to the user.

The controller handling the Sign Up process is the one that will generate the password by calling a method from the PasswordGenerator class. I want to show this to the user in a message box using some jQuery.

I've tried passing it through TempData and ViewBag but the password can be seen in the HTML code sent over the internet. Is there anyway to do this securely without showing the password over the internet?

FYI, sending an email with the password is not an option. This is a class project, not intended for something of that magnitude.

Any help would be appreciated.

Passing a Dictionary

I have a controller that Populates a dictionary with key as Month dates as 0,5,10,15,20,25,30 and the Values as some Distance covered for each period. Say for eg: Dictionary element of key 5 has distance covered between days 0 and 5 of that Month.

Dictionary<int, double> ChartDetails = getDetails.getFMS1DataSet(FMS1Resultset);

I need to know how can I pass this dictionary from Controller to View. In View I access them to display a chart of Number of Days VS distance covered. The Chart is SyncFusion User controls

@(Html.EJ().Chart("container")
          .PrimaryXAxis(pr => pr.Range(ra => ra.Min(2005).Max(2011).Interval(1)).Title(tl => tl.Text("Days")))
          .PrimaryYAxis(pr => pr.Title(tl => tl.Text("Fuel Usage")).RangePadding(ChartRangePadding.None)
          .LabelFormat("{value}%").Range(ra => ra.Min(25).Max(50).Interval(5)))
          .CommonSeriesOptions(cr => cr.Type(SeriesType.Line).EnableAnimation(true)
          .Marker(mr => mr.Shape(ChartShape.Circle).Size(sz => sz.Height(10).Width(10)).Visible(true)).Border(st => st.Width(2)))
          .Series(sr =>
              {
                  sr.Points(pt =>
                      {
                          pt.X("0").Y(0).Add();
                          pt.X("5").Y().Add();
                          pt.X("10").Y().Add();
                          pt.X("15").Y().Add();
                          pt.X("20").Y().Add();
                          pt.X("25").Y().Add();
                          pt.X("30").Y().Add();
                      }).Name("Fuel").Tooltip(sr1 => sr1.Visible(true).Template("Tooltip")).Add();

              })
          .CanResize(true)

Here for pt.X("5").Y().Add(); I want the Y parameter to be added as Dictionary elements

vendredi 18 septembre 2015

jQuery validate remote not sending correct json data

There are a number of similar posts but this is not working for me. I've tried it about 20 different ways now so if someone can put me on the right track its much appreciated.

First I tried this. Seems to be correct according to the docs but the JSON that is being sent is just the element id ('element' is a jQuery element ref)

if (valData.ValidationItems[i].Date) {
    element.rules("add", {
        remote: {
            url: websiteBase + "Home/DateValidation",
            type: "post",
            data: {
                Date: function () { return $("#" + element[0].id).val() },
                Min: valData.ValidationItems[i].RangeMin,
                Max: valData.ValidationItems[i].RangeMax
            },
            dataType: "json"
        },
        messages: { remote: valData.ValidationItems[i].ValidationMessage }
    });
}

This next bit that I tried works one time but then locks up the browser

remote: function () {
    var remoteData = {
        Date: $("#" + element[0].id).val(),
        Min: data.ValidationItems[i].RangeMin,
        Max: data.ValidationItems[i].RangeMax
    }
    var remoteJSON = JSON.stringify(remoteData);
    var r = {
        url: websiteBase + "Home/DateValidation",
        type: "post",
        dataType: "json",
        data: remoteJSON
    }
    return r;
}

This is using jQuery validate 1.8 which is the version installed for MVC 3 projects.

MVC + Insert master and all child values in one view

This is how my form looks now:- enter image description here

I am trying to do the following:-

  1. Enter the group details.
  2. Enter a member.
  3. If more members are there, then click "add more members". This should show one more line with same controls('member name, place, age).
  4. Then after adding all members, click save. This should save both group details(master) and members in group(child).

Although I was able to show the details(already added) using viewmodel, But I could not find how to insert(save) this. I can use jquery to add one more row when "add more member" is clicked. But how to save after that is the major problem.

Thanks in advance

how can i jump one cshtml page to another cshtml?

i have two .cshmtl page for registration. when user complete first registration page i want to jump the controller to another page that is also a part of registration without controller so,how can i complete this task?

 <div class="control-group form-actions pull-right"> <a href="~/Views/Registration/RegStep2" class="btn btn-primary">Continue <i class="fa fa-arrow-circle-right"></i></a> </div>
        </div>

When user click above continue button user will jump on another controller without controller...

jeudi 17 septembre 2015

call to method inside code behind file(aspx.cs file) from controller method

I have following controller method

public class ReportController : Controller
{
    // GET: Report
    public ActionResult Incomplete_Product_Report()
    {
        return View();
    }

}

I want to call following method which is ShowReport() inside the code behind file in aspx web-form .

  private void ShowReport()
  {

  //DataSource
  DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, dateHERE.Text);
   ....................
  }

  private DataTable GetData(string type, string category, string country, string subsidary, string dateHERE)
  {
    ................
  }

then ShowReport() method call and pass parameters call GetData()

NancyFX Doesn't Recognize Custom Data Annotations

I am using NancyFX for my API Gateway and I have a model such as the following:

public class CreatePerson
{
    [Required]
    public string FirstName {get;set;}

    [Required]
    public string LastName {get;set;}

    [Required]
    [Phone]
    public string Phone {get;set;}

    [Required]
    [MyCustomValidationRule]
    public string ImagePath {get;set;}
}

It uses both a custom MyCustomValidationRule attribute as well as the provided Phone and Required attributes.

In my module I have the following:

public class PersonModule
{
  public PersonModule()
  {
      Post["/",true] = async (context,cancel)=> 
      {
          var request = this.BindAndValidate<CreatePerson>();

          if(!ModelValidationResult.IsValid)
          {
              //THIS NEVER HITS
          }
      }
  }
}

The [Required] attributes are working and if I omit any of the properties, it works fine. However, if I pass in an invalid phone (such as sdfsdgsdg or I do something that clearly breaks MyCustomValidationRule attribute, it is not caught. Furthermore, I have placed a breakpoint in the constructor of the MyCustomValidationRule attribute, and it never hits.

Why is this not hitting?

Set Default date for Column inside OnModelCreating

I have below DateTime Property

[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreationDate { get; set; }

From the article on Google I got to know that this can be achieved by

Update-Database in Package Manager Console

Is there any way to do this in Model Creating ?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Code for setting the default date for a column
}

Trying to Prevent sending the Password Property

I have 7 projects in my solution that work together to save a role to the database. Here are the details: In the similar way User Management code is divided in 7 parts.

Question: from the web API I am sending the class or list of class objects of user. Is there any way to prevent from sending the Password Property ?

Project - 1 - Object Model(Class Library Project) - Only declaring the Class Properties

public class OM_Role
{
    [DisplayName("Role ID"), Key]
    public Int16 RoleID { get; set; }

    [DisplayName("Role Name"), Required(ErrorMessage = "Please enter role")]
    public String Role { get; set; }

    [DisplayName("Is Activated")]
    public Boolean IsActivated { get; set; }
}

Project - 2 - IDAL(Class Library Project) - Declaring the Interface methods

public interface IRole
{
    Task<String> Save(OM_Role role);
}

Project - 3 - Definition of Save Role Method

public class DAL_Role : IRole
{
    public async Task<String> Save(OM_Role role)
    {
        using (var transaction = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted },
            TransactionScopeAsyncFlowOption.Enabled))
        {

            using (var roleContext = new DatabaseTables())
            {
                var data = await roleContext.tblRoles.FirstOrDefaultAsync(
                i => i.RoleID == role.RoleID);
                if (data != null)
                {
                    data.Role = role.Role;
                    data.IsActivated = role.IsActivated;
                }
                else
                {
                    role.IsActivated = false;
                    roleContext.tblRoles.Add(role);
                }
                await roleContext.SaveChangesAsync();
                transaction.Complete();
                return "";
            }
        }
    }
}

Project - 4 - WebAPI for calling the DAL Layer through IRole using Ninject

public class roleAPIController : ApiController
{
    IRole _role;
    public roleAPIController(IRole role)
    {
        _role = role;
    }

    public roleAPIController()
    {
    }

    [Route("api/v1/SaveRole"), HttpPost]
    [System.Web.Mvc.ValidateAntiForgeryToken]
    public async Task<HttpResponseMessage> Save([FromBody] OM_Role role)
    {
        var result = await _role.Save(role);
        return Request.CreateResponse(HttpStatusCode.OK, new { ErrorMessage = result });
    }
}

Project - 5 - BLL(Class Library Project) - This calls the Web API

internal class RoleResponse
{
    public String ErrorMessage { get; set; }
    public OM_Role result { get; set; }
    public int RoleID { get; set; }
}


public class BLL_Roles : IRole
{
    public async Task<KeyValuePair<string, List<Om_Role>>> RolesList()
    {
        try
        {
            var url = "api/v1/AllRoles";
            String URI = String.Format("{0}{1}", "Mydomainurl", url);

            var result = await clsCommon.GetDeserializedData<RoleListResponse>(null, URI);
            return new KeyValuePair<String, List<Om_Role>>(result.ErrorMessage, 
                                                       result.result);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

Project - 6 - Presentation Layer that calls BLL using Ninject

[LoginAuthentication, AdminAuthorization]
public class roleController : Controller
{
    IRole _role;
    public roleController(IRole role)
    {
        _role = role;
    }

    [HttpPost, Route("SaveRole")]
    public async Task<JsonResult> Save(OM_Role objrole)
    {
        var data = await _role.Save(objrole);
        return Json(new { Success = String.IsNullOrEmpty(data) });
    }
}

Project - 7 - Code First Database Creation Entity FrameWork

public class DatabaseTables : DbContext
{
    public DatabaseTables()
        : base("Connection")
    {
    }

    public virtual IDbSet<OM_Role> tblRoles { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        RoleTable(modelBuilder);
    }

    private void RoleTable(DbModelBuilder modelBuilder)
    {
        var roleModel = modelBuilder.Entity<OM_Role>();
        roleModel.Property(x => x.RoleID)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        roleModel.Property(x => x.Role).IsRequired().IsVariableLength().HasMaxLength(50);
        roleModel.Property(x => x.IsActivated).IsRequired();
        roleModel.ToTable("tblRole");
    }
}

MVC Override OnException Error: No suitable method found to override

I'm trying to override OnException in Global.asax to handle error and writing log. I'm not sure which part is wrong, I keep on getting the error "MyApp.MvcApplication.OnException(System.Web.Mvc.ExceptionContext)': no suitable method found to override" whenever I rebuild my solution.

this is the code I have in Application_Start()

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();         
    }

And this is the code I have in OnException()

protected override void OnException(ExceptionContext context)
    {
        Exception ex = context.Exception;

        if (!string.IsNullOrEmpty(ex.Message) ||
            !string.IsNullOrEmpty(ex.Source.ToString()) ||
            !string.IsNullOrEmpty(ex.StackTrace))
        {                

            WriteLog(ex.Message.ToString(), ex.StackTrace.ToString(), ex.Source.ToString(), "0");

            context.Result = new ViewResult
            {
                ViewName = String.Format("~/ErrorPage/ErrorPage?message={0}&stack={1}&source={2}", HttpUtility.UrlEncode(ex.Message), HttpUtility.UrlEncode(ex.StackTrace), HttpUtility.UrlEncode(ex.Source))
            };
        }

        context.ExceptionHandled = true;
    }

The WriteLog() function is tested working in other application, I don't think there's any problem in it and I even tried:

protected override void OnException(ExceptionContext context) {
    Exception ex = context.Exception;

    context.Result = new ViewResult
            {
                ViewName = "~/Shared/Error.cshtml";
            };
    context.ExceptionHandled = true;
}

But nothing work. The error just remain there.

How could such problem occur and how do I fix it? I read many tutorial about this, I don't think I'm spelling OnException() wrongly.

Please help. Thanks

image not getting displayed after changing src attribute of img using jquery

I have an image on my page. On clicking a button I want to change the src of the image and display the new image. Below is my code.

<img id="img_change" src = "~/content/images/img1.jpg" />

Below i have

<script>
$("document").ready(function() {
  $("button").click(function() {
    $("img_change").attr("src","~/content/images/img2.jpg");
  });
});

On clicking the image is not getting displayed. I've tried all that I know. Plz help!

mercredi 16 septembre 2015

Issue when download html files from mvc project

When i tried to download arabic files from mvc project , I found the arabic data is changed to special characters like this "تاريخ الشكوى"

that's my code that i use in download

System.Web.Mvc.FileStreamResult FSR = new FileStreamResult(stream, "application/msword");
                        FSR.FileDownloadName = CorrespondenceselectedFile.FileName;
                        return FSR;

DefaultNetworkCredentials resulting in 403 on server

I have a website in ASP.NET MVC3 C# that makes requests to a web service using HttpWebRequest. I use the following code to make the request:

HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url);
loginRequest.ContentType = "application/xml";
loginRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
loginRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; 
loginRequest.Method = "GET";
loginRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
loginRequest.Headers["Cache-Control"] = "no-cache";
loginRequest.Headers["Pragma"] = "no-cache";

HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
using (StreamReader sr = new StreamReader(loginResponse.GetResponseStream()))
{
    string results = sr.ReadToEnd();
}
logonToken = loginResponse.Headers["X-SAP-LogonToken"].ToString();
loginResponse.Close();

On my laptop, this works great. But when I deploy to my server running IIS 7.5, I got an HTTP 401. After enabling ASP.NET impersonation that changed to an HTTP 403.

My web.config contains:

<authentication mode="Windows" />
<identity impersonate="true"/>

If I replace the code to use my hardcoded credentials, it will work on the server:

loginRequest.Credentials = new NetworkCredential("username", "password", "domain");

So, what could be different about my server environment that is causing DefaultNetworkCredentials to fail?

Thanks!

join two tables using entity framework mvc [duplicate]

This question already has an answer here:

I am trying to join to tables using EF, here is my code :

For the modele :

namespace help2.Models
{
    public class intDB1
    {
        public int ID { get; set; }
        public DateTime debint { get; set; }
        public DateTime finint { get; set; }
        public DateTime id_int { get; set; }
        public decimal id_tpint { get; set; }
        public virtual tpintDB tp_intDB { get; set; }
    }
}

namespace help2.Models
{
    public class tpintDB1
    {
        public decimal id_tpint { get; set; }
        public string libelle { get; set; }
        public string desc_tpint { get; set; }
        public virtual ICollection<intDB> intDBs { get; set; }
    }
}

     public class intDBContext : DbContext
        {
            public DbSet<intDB1> intDB1s { get; set; }
            public DbSet<tpintDB1> tpintDB1s { get; set; }
        }

-For the controller:

public class intsController : Controller
    {
        intDBContext db = new intDBContext();
        //
        // GET: /ints/

        public ActionResult Index()
        {
            return View(db.intDB1s.ToList());
        }

        //
        // GET: /ints/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /ints/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /ints/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /ints/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /ints/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /ints/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /ints/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

And this is my view:

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            debint
        </th>
        <th>
            finint
        </th>
        <th>
            id_int
        </th>
        <th>
            id_tpint
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.debint)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.finint)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.id_int)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.id_tpint)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

and then I get this error:

": No key is set for EntityType 'tpintDB'. Set the key to this EntityType"

Align labels in DataVisualization.Charting effectively

I need to develop a chart using datavisualization. Now the chart looks like below

enter image description here

In the above chart i am using rangebar to show min and max values, in rangebar the label (65---210) now comes in the middle part. But i need to show the min and max like one in red. ie min value in the start position of the rangebar and max value in the end position of the rangebar.

Please let me know if there is any way to do it

mardi 15 septembre 2015

styling a web grid column based on its context using razor engine asp.net mvc

I am using asp.net mvc with linq to sql in my application, I am unable to style my web grid column based on its data, below is my code

grid.Column("PeriodString", header: "Period"),
grid.Column("LegalName", header: "Legal Name"),
grid.Column("PreviousClosing", header: "Previous Closing"),
grid.Column("OpeningBalance", header: "Opening Balance"),
grid.Column("NoofReceipt", header: "# of Receipts"),
grid.Column("NoofPayment", header: "# of Payments"),
grid.Column("TotalReceipt", header: "Total Receipts"),
grid.Column("TotalPayment", header: "Total Payment"),
grid.Column("ClosingBalance", header: "Closing Balance"),
grid.Column(header: "Matching", format: (a) => 
    a.OpeningBalance == a.PreviousClosing ? "Yes" : "No")

I want to style Matching column to red color if its value is "No"

I know that styling is possible by using:

style: "MyStyle"

and in CSS:

.MyStyle {color:"red"}

But it sets the whole column text in red, I want to color only that value that contain "No" in it. Any help will be highly appreciated.

Thanks

Url to replace space with Hyphen in MVC Razor

I am using ASP.NET MVC Razor C# with Attribute Routes

In my Category form when I click on Edit. it opens the Url like below:

http://localhost:38812/Category/Database%20Design

I am trying to change the Url like below

http://localhost:38812/Category/Database-Design

Here the problem is, when I go to database to search for the category based details..it does not search because there is no category with the name of Database-Design. It exist as Database Design with space.

Is there any way to not include the Id in Url and so we can also achieve the below Url? :

http://localhost:38812/Category/Database-Design

ASP Repeater - Not able to add Class in DIV

I am using Repeater control in my asp.net file. Everything is working fine except that DIV is distorted as it is throwing errors while adding class in DIV

  • Below code it is working fine:(With distorted DIV)

<%# (Container.ItemIndex != 0 && Container.ItemIndex % 5 == 0) ? @"" : string.Empty %> ' />

This is what I want:(To add class in DIV but it's throwing error)

<%# (Container.ItemIndex != 0 && Container.ItemIndex % 5 == 0) ? @"" : string.Empty %> ' />

How can I allow users to access js files from sub-sub folders ASP .NET MVC3

I'm wondering if its possible to allow users to access my js files from sub-sub folders. The folder structure is:

Views
|-employee
|--js
|---employee.js
|--index.html

If you access: http://localhost/employee/ there's no error. But if you try to access: http://localhost/employee/js/employee.js it gives me 404.

Thanks in advance.

How can i update two tables from two model classes using a single edit view in Asp.Net MVC?

For updating the information of employee in my scenario, i have two tables and two models classes, how can i update two tables using a single view. Many of my Information is stored/fetched from one table and only one information is stored in one table.

lundi 14 septembre 2015

Power Point viewer asp.net mvc

I want powerpoint viwer in asp.net mvc application. It should work on all platform .I should be open source . I just need powerpoint viewer. Please tell me possible solutions Thanks

Unit testing for 100,000 concurrent users on a single machine

My code is in ASP.NET MVC Razor C# and Database is SQL Server 2012. Right now the code is on localhost.

ok. Before moving to the server, I want to test the website design should able to scale/support 100,000 concurrent users.

Question : I am a .NET Developer only. Is there any way to do the unit testing for 100,000 concurrent users on a single machine ?

Storing data / value on Session or TempData in Jquery

Guys is there any way to save or store data/value in Session or TempData using Jquery? because I need to Call the value stored in TempData and use it in a dropdown after refreshing the page

I tried adding this line but cant store or call

In my Cshtml:

$("#dropdownStatus").change(function(){
var status = $("#dropdownStatus option:selected").val();
status = TempData["Status"];
}

and In my Controller I simply added variable that will be use in a Condition

var Status = TempData["Status"];

I hope someone can help me in this, Thanks