mardi 27 décembre 2016

Validation of Date in MVC Gridview

I have the following gridview code and I am trying to do some basic validation on my dates. As you can see I have a start date and end date and I need to validate them so that StartDate <= EndDate. Is there a simple way to add this validation to the code below?

Html.DevExpress().GridView(settings =>
{
    settings.Name = "gvActiveScheduledAnnouncements";
    settings.Width = Unit.Percentage(100);
    settings.KeyFieldName = "AnnouncementId";

    settings.CallbackRouteValues = new { Controller = "Home", Action = "ActiveScheduledAnnouncementsPartial" };

    settings.SettingsEditing.Mode = GridViewEditingMode.EditForm;

    settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddNewAnnouncement" };
    settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateActiveScheduledAnnouncement" };
    settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteActiveScheduledAnnouncement" };

    settings.Columns.Add(c =>
    {
        c.Caption = "Announcement Text";
        c.FieldName = "Text";

        c.ColumnType = MVCxGridViewColumnType.Memo;
        c.EditFormSettings.ColumnSpan = 2;

        c.ColumnType = MVCxGridViewColumnType.Memo;
        var memo = c.PropertiesEdit as MemoProperties;
        memo.Rows = 3;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "Start Date";
        c.FieldName = "StartDate";


        c.ColumnType = MVCxGridViewColumnType.DateEdit;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "End Date";
        c.FieldName = "EndDate";

        c.ColumnType = MVCxGridViewColumnType.DateEdit;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "Display Status";
        c.FieldName = "DisplayStatus";

        c.EditFormSettings.Visible = DefaultBoolean.False;
    });
})
.Bind(Model)
.Render();

How to retrieve list of data in model

I have data in model and I used to store that data in session as below in controller

 if (providerListingModel.ServiceDetails != null && providerListingModel.ServiceDetails.Count > 0)
            Session["ServiceDetails"] = providerListingModel.ServiceDetails;
 else
            Session["ServiceDetails"] = null;

and for retrieving I had used the logic as

       if (Session["ServiceDetails"] != null)
        {
            if (providerListingModel.ServiceDetails == null)
            {
                List<ServiceDetail> sam = (List<ServiceDetail>)Session["ServiceDetails"];

                foreach (var items in sam)
                {
                    var sd = new ServiceDetail();
                    sd.Id = items.Id;
                    sd.CategoryServiceId = items.CategoryServiceId;
                    sd.ServiceType = items.ServiceType;
                    sd.ServicePrice = items.ServicePrice;
                    sd.IsSelected = items.IsSelected;
                    sd.ProviderListingId = providerListingModel.ProviderListingId;
                    providerListingModel.ServiceDetails.Add(sd);
                }
            }
            Session["ServiceDetails"] = null;
        }

The session contains data but on providerListingModel.ServiceDetails.Add(sd); it throw null exception. ServiceDetails is a class and it contains list of items

namespace xyz.DAL
{
 using System;
 using System.Collections.Generic;

public partial class ServiceDetail
{
    public int Id { get; set; }
    public int ProviderListingId { get; set; }
    public Nullable<int> CategoryServiceId { get; set; }
    public string ServiceType { get; set; }
    public Nullable<int> ServicePrice { get; set; }
    public string CustomeService { get; set; }
    public Nullable<bool> IsSelected { get; set; }

    public virtual CategoryService CategoryService { get; set; }
    public virtual ProviderListing ProviderListing { get; set; }
}
}

am I missing some code? As I am new I don't know what I am doing wrong

enter image description here enter image description here

dimanche 25 décembre 2016

Retain TempData Value after creating new session

For some reason, I am creating new Session within my controller's action method. But I have TempData in my ActionMethod1 and I would like to pass the value to ActionMethod2 after creating new seesion. But after creating new session id my TempData value cleared. Below code has been used to create new sessionid.

System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager(); string NewSession = manager.CreateSessionID(System.Web.HttpContext.Current);

Please let me know if any other possible solutions to retain tempdata value even after creating new session.

Difference between property with no data annotation and property with "?" asp.net MVC

I have a very basic question of ASP.Net MVC 5. What is the difference between a property defined as

1. public int a {get; set;}

and 

2. public int? a{get; set;}

and 

3. [Required]
public int a {get; set;}

I know the 3rd one; it means the value is required and cannot be NULL. Can someone please tell me the difference between 1 and 2.

i want to disable my custom validation in edit action in asp.net mvc

Model

public partial class MemberModel 
    {

        [Key]
        public int MemberID { get; set; }

        [Required]
        [Unique_Member]
        [StringLength(255)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }


        [Required]
        [Unique_Member]
        [StringLength(255)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name="Name")]
        public string FullName { get { return string.Format(FirstName + " " + LastName); } }

        [Required]
        [StringLength(355)]
        public string Address { get; set; }
        [Required(ErrorMessage="The City field is Required")]
        public int CityID { get; set; }

        [Required(ErrorMessage = "The Country field is Required")]
        public int CountryID { get; set; }


        [Required]
        [RegularExpression(@"^((0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{4}$|^\d{4}-\d{7}$", ErrorMessage = "Invalid Phone number")]
        [Unique_Member]
        public string Pin { get; set; }


        [Display(Name="Mobile No.")]
        [Required(ErrorMessage="Mobile No. Required")]
        [RegularExpression(@"^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$",ErrorMessage="Invalid Phone number")]
        public string Phone { get; set; }


        [Required]
        [EmailAddress]
        public string Email { get; set; }


        public virtual List<Order_SummeryModel> Order_Summeries { get; set; }
        public virtual CountryModel Country { get; set; }
        public virtual CityModel City { get; set; }
    }

Custom Validation [Unique_Member]

its a custom validation for three properties "Pin","FirstName" and "LastName" which i made for create new member. It checks whether fullname and pin of new member is unique or not.

its works perfectly for create action but in edit action this restrict me to update the member model, i want to disable it for edit action, or there is another way to update the model with disable it.

  public class Unique_MemberAttribute : ValidationAttribute
    {
        private static int count;

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Context_getway db = new Context_getway();
            string membervalue = value.ToString();
            //var count = db.Members.Where((x => x.Name == membervalue || x.Pin == membervalue || x.Email == membervalue)).Count();
            var count_fname = db.Members.Where(x => x.FirstName == membervalue).Count();
            var count_lname = db.Members.Where(x => x.LastName == membervalue).Count();
            var count_pin = db.Members.Where(x => x.Pin == membervalue).Count();

            if ((count_fname != 0)||(count_lname != 0))
            {
                count++;
                if (count == 2)
                {
                    return new ValidationResult("Member Already Exist with the same Full Name (Change First Name OR Last Name)!");

                }
            }
            if (count_pin != 0)
            {
                return new ValidationResult("Member Already Exist with the same Pin!");
            }


                return ValidationResult.Success;

        }
    }
    [MetadataType(typeof(MemberModel))]
    public partial class MemberModel
    {

    }

Member Controller (edit action)

 [HttpGet]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            else
            {
                var member = db.Members.Find(id);
                ViewBag.CountryID = new SelectList(db.CountryModels.ToList(), "CountryID", "Country",member.CountryID);
                ViewBag.CityID = new SelectList(db.CityModels.ToList(), "CityID", "City",member.CityID); 
                if (member != null)
                {
                    return View(member);
                }
                else
                    return HttpNotFound();
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(MemberModel member)
        {

            try
            {  
                if (ModelState.IsValid)
                {
                    db.Entry(member).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    TempData["Msg"] = "Update Successfully";
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewBag.CountryID = new SelectList(db.CountryModels.ToList(), "CountryID", "Country",member.CountryID);
                    ViewBag.CityID = new SelectList(db.CityModels.ToList(), "CityID", "City",,member.CityID); 
                    return View(member);
                }
            }
            catch(Exception e)
            {
                TempData["Msg"] = "Update Unsuccessfully: "+ e.Message;
                return View();
            }
        }

samedi 24 décembre 2016

i want to run onclick event in

     <a onclick="log_out_event" href="LogIn.aspx"><i class="icon_key_alt"></i> Log Out</a>

//i want to run onclick event in

vendredi 23 décembre 2016

LINQ creates query leaving "From" clause empty

I've got an mvc3 application with the following code:

public static List<ApprovalDTO> ConvertToDTO(IQueryable<REGISTER> r2, GMIEntities db, User user)
{
    List<ApprovalDTO> rta = new List<ApprovalDTO>();

    r2= r2.Where(r => r.APPROVAL.STATE1.DESC_STATE == Constants.ON_HOLD);
    String sql = ((System.Data.Objects.ObjectQuery)r2.OrderBy(o => o.ANALYSIS.ANALYSIS_DATE)).ToTraceString();


   System.Diagnostics.Debug.WriteLine(sql);  }

Which returns the following Query to be run against an oracle database:

SELECT
"Extent1".-SOME INFO-
FROM  ( SELECT  
 -SOME INFO- FROM     ORDER BY "ANALYSIS_DATE" ASC ) "MYSCHEMA"."REGISTER"  ORDER BY "ANALYSIS_DATE" ASC ) "Extent1"

This obviously gives an "Invalid table name" error when executing the query, since LINQ isn't filling the FROM clause for extent1 What could be causing this?

mercredi 21 décembre 2016

oledb string manipulation for repeatitive strings

I have an excel sheet with column names as :

{ "test 1", "test 1","test 1","test 11","test 12"}

and is getting interpreted from oledb to C# method as

{ "test 1", "test 11","test 12","test 111","test 121"}.

How do I display the original column names in the grid of my asp .net web application?

If I use linq like :

original.Select(x => original.Where(y => x.StartsWith(y)).Min()).ToList(); 

I will get the string as :

{ "test 1", "test 1","test 1","test 1","test 1"}

So how can I get the original string array as it is?

mardi 20 décembre 2016

Rotate text using mvcrazortopdf

I needed text inside 'th' tag of table to be shown vertically i.e.,

transform: rotate(270deg); using css

while rendering into pdf using mvcrazortopdf.

vendredi 16 décembre 2016

Devexpress Gridview column styling issue

I have a devexpress gridview for managing user feedback that appears in a popup when an admin clicks a button. Currently the grid columns dynamically size based on content as you can see here:

enter image description here

The problem is this view currently doesn't scroll so if the user has too many entries the popup blows out the bottom of the page. The user specifically wants scrolling and not pagination. If I try to enable scrolling on the gridview I have 2 problems. First for some reason my command column gets truncated strangely, and second all of the columns seem to go to a fixed width which is unpleasing to read if there are longer feedback messages. Does anyone know why this happens? Full control code posted at bottom.

enter image description here

Html.DevExpress().GridView(settings =>
    {
        settings.Name = "gvManageFeedback";
        settings.Width = Unit.Percentage(100);
        settings.KeyFieldName = "FeedbackId";
        settings.Styles.Header.HorizontalAlign = HorizontalAlign.Center;
        settings.Styles.Header.Wrap = DefaultBoolean.True;
        settings.Styles.Header.VerticalAlign = VerticalAlign.Bottom;

        //Scrolling causing weird style issues for some reason
        settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
        settings.Settings.VerticalScrollableHeight = 400;
        settings.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;

        settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
        settings.SettingsBehavior.AllowSort = true;
        settings.SettingsBehavior.AllowDragDrop = false;
        settings.SettingsBehavior.AllowGroup = false;

        settings.Settings.ShowFilterRow = false;
        settings.Settings.ShowTitlePanel = false;        
        settings.Settings.ShowFooter = false;

        settings.CallbackRouteValues = new { Controller = "Home", Action = "ManageFeedbackGrid" };

        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;

        settings.CommandColumn.Visible = true;
        settings.CommandColumn.VisibleIndex = 0;
        settings.CommandColumn.ButtonRenderMode = GridCommandButtonRenderMode.Image;
        settings.CommandColumn.Width = Unit.Pixel(20);
        settings.CommandColumn.CellStyle.HorizontalAlign = HorizontalAlign.Left;
        settings.CommandColumn.ShowEditButton = true;
        settings.SettingsCommandButton.EditButton.Image.ToolTip = "Acknowledge";
        settings.SettingsCommandButton.EditButton.Image.Url = Url.Content("~/images/20Acknowledge.png");
        settings.SettingsCommandButton.UpdateButton.Image.Url = Url.Content("~/images/20Save.png");
        settings.SettingsCommandButton.UpdateButton.Image.ToolTip = "Submit comment and acknowledge";
        settings.SettingsCommandButton.CancelButton.Image.Url = Url.Content("~/images/20Cancel.png");

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "AcknowledgeFeedback" };

        settings.CommandColumn.ShowClearFilterButton = true;
        settings.SettingsCommandButton.ClearFilterButton.Image.Url = Url.Content("~/images/20ClearFilter.png");

        settings.Settings.ShowFilterRow = true;
        settings.Settings.ShowFilterRowMenu = true;

        settings.Columns.Add(c =>
        {
            c.Caption = "User";
            c.FieldName = "UserName";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Date";
            c.FieldName = "CreatedOn";

            c.ColumnType = MVCxGridViewColumnType.DateEdit;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Category";
            c.FieldName = "Category";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Feedback";
            c.FieldName = "Text";

            c.ColumnType = MVCxGridViewColumnType.Memo;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Acknowledged By";
            c.FieldName = "AcknowledgedUserName";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Comments";
            c.FieldName = "AdministratorComments";

            c.ColumnType = MVCxGridViewColumnType.Memo;
            var memo = c.PropertiesEdit as MemoProperties;
            memo.Rows = 3;
            c.EditFormSettings.ColumnSpan = 2;
        });
    })
    .Bind(Model)
    .Render();

jeudi 15 décembre 2016

How to auto execute code / click button in JS after 1 month or by schedule?

I have a simple project in asp.net mvc3. I am trying to do in my project is to add a scheduling date or month to execute a specific button or code. I found this LINK but I can't understand enough because I just started to learn asp.net mvc. Hope someone can help me. Thanks

ASP.NET MVC post to controller action from same controller

I'm working on this project that currently has the follow method:

 [HttpPost]
 public ActionResult Service(string identifier)

This function is currently being used by a webpage form

 <form method="POST" action="/Connector/Service">
 <input type="hidden" id="identifier" name="identifier"/>

So Service is used when the user clicks on a button that submits the form on the webpage. The user is taken to this page from another action. I have to implement a feature where sometimes instead of taking the user to the webpage, the user goes directly to the Service method from the action.

I found this thread when searching: ASP.NET MVC: RedirectToAction with parameters to POST Action

But it seems like that is bad design and returning RedirectToAction with Service actually did not work for me.

return RedirectToAction("Service", new {identifier})

Upon more search it seems like I actually cannot make a post request from my controller. Asp.NET MVC : redirect to another controller with POST Action

Any ideas on what I could do here? I am fairly new to ASP.NET and have no idea what to do at this point. All help is appreciated, thanks.

mercredi 14 décembre 2016

Prevent Unauthenticated Access to Uploaded Document URLs - MVC

My application(MVC3) allows users to upload their documents on a form. Once uploaded, access to these documents is available to anonymous users by visiting the link containing the document ID and request ID in the URL.

Ex: http://ift.tt/2hI4E72

Need to secure uploaded document URLs from unauthorized access by requiring authenticated user's session cookie.

In MVC3, what are all the possible ways to implement session cookie. I really appreciate, if any other possible ways.

mardi 13 décembre 2016

Scripts are not getting rendered

Cshtml code.

@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "datefield", type = "date" } })

@section Scripts {
    @Scripts.Render("~/Content/css")
    @Scripts.Render("~/Scripts/jquery")
}

Bundle.config code

bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
   "~/Scripts/jqueryui1.12.s",
   "~/Scripts/jqueryui-12.js",   
    "~/Scripts/DateTimePicket.js"
));     

bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/jqueryui1.12.css"
));

code of DateTimePicker

$(function () {
    alert("hi");
    $(".datefield").datepicker();
});

where is the issue. The code of these file "~/Scripts/jqueryui1.12.s", "~/Scripts/jqueryui-12.js", are from

<script src="http://ift.tt/20g0BuL"></script>
<script src="http://ift.tt/2dsPzTA"></script>

I am just trying to add the datepicker and the code got messed up.

mercredi 7 décembre 2016

Reset ASP.NET_SessionId cookie to prevent Login Cookie Session Fixation attack - MVC3

In my application SSO(Single Sign On) has been implemented. When a user first visits the login page, they are redirected to the SSO login page.

The ASP.NET_SessionId cookie that serves as the first login cookie for application is set in the user’s browser prior to submitting a username/password.

After successful authentication, the value of the ‘ASP.NET_SessionId’ cookie is not refreshed.

Help me to Re-set the value of the ASP.NET_SessionId cookie after successful authentication in MVC3.

mardi 6 décembre 2016

Custom authentication with MVC

I want to create custom authentication with MVC3.

Scenerio:: User will have a login form, where he will input userId and password. These credentials are then verified against my business logic. I can not use default process, like validating it from User table then assign role etc..

My business logic will provide me a boolen value IsValidUser and UserRole.

PROBLEM:: I need to do two things:
1. Use these values returned by Business logic in AuthoriseAttribute filter. So that I can restrict a user from accessing any particular action of a controller.(I have tried putting these values in Session variable, but not able to use them in Authorisation filter.)
2. How to use Formsauthentication.Setauthcookie for accomplishing this task.

lundi 5 décembre 2016

Moving file from one folder to other in FTP

I have an requirement to move files from one folder to other in ftp i used the below code block but getting following error

The remote server returned an error: (501) Syntax error in parameters or arguments.

 public void MoveFile(string souce,string destination, string UserName, string Password)
    {
        FtpWebRequest ftpRequest = null;
        FtpWebResponse ftpResponse = null;
        try
        {
            ftpRequest = (FtpWebRequest)WebRequest.Create(souce);
            ftpRequest.Credentials = new NetworkCredential(UserName, Password);
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            ftpRequest.Method = WebRequestMethods.Ftp.Rename;
            ftpRequest.RenameTo = destination;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpResponse.Close();
            ftpRequest = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

can you please help me how to solve this issue.

Encountered end tag "li" with no matching start tag error when putting li inside if statement

i am using asp.net MVC 5 and Visual studio 2013

and working on Razor view

the view is working fine without if statement around the < li > start

if i enclosed any < li > start, with an if condition statement i get this error

Parser Error Message: Encountered end tag "li" with no matching start tag. Are your start/end tags properly balanced?

@using TheodorHR_App.Models
<div id="tree_CadreGroupLevel" class="tree-demo">
    <ul>
        @{
            TheodorHrEntities db = new TheodorHrEntities();
            var nodes = db.Cadres.ToList();
            foreach (var node in nodes)
            {
                Cadre root = new Cadre();
                root.Id = node.Id;
                if (@Model.RuleElementCadres.Select(e => e).Where(e => e.Cadre == node.Id).Count() > 0)
                {
                    <text>
                        <li id="Cnode_@node.Id" data-jstree='{ "selected" : true }'>
                    </text>
                }
                else
                {
                    <text>
                    <li id="Cnode_@node.Id">
                    </text>
                }

                        <a href="#">@node.Name</a>
                        <ul>
                            @{
                                var nodes1 = db.JobGroups.Where(jg => jg.CadreId == @node.Id).ToList();
                                foreach (var node1 in nodes1)
                                {
                                    Cadre root1 = new Cadre();
                                    root1.Id = node1.Id;
                                    <li id="Gnode_@node1.Id">
                                        <a href="#">@node1.Name</a>
                                        <ul>
                                            @{
                                                var nodes2 = db.JobGroupJobLevels.Where(jl => jl.JobGroup == @node1.Id).ToList();
                                                foreach (var node2 in nodes2)
                                                {
                                                    Cadre root2 = new Cadre();
                                                    root2.Id = node2.Id;
                                                    <li id="Lnode_@node2.Id">
                                                        <a href="#">@node2.JobLevel1.Name</a>
                                                        <ul></ul>
                                                    </li>
                                                }
                                            }
                                        </ul>
                                    </li>
                                }
                            }
                        </ul>
                </li>
            }
        }
    </ul>
</div>

samedi 3 décembre 2016

There are methods to tracking call's in MVC .NET?

I m working with a large project whith meets in mvc c# and looking for methods (plugins for visual studio, addons, frameworks) for tracking object in controller,views during the app works. Any methods exist for that ? I do not want use logging via nlog or log4net.

mercredi 30 novembre 2016

In EF stream is null when seed method run with data from CSV file

I have a large dataset formated CSV file type, I want to add all the data into my EF database from CSV file. But when run seed method, it creates error Error Message is

Value cannot be null. Parameter name: stream

protected override void Seed(Drug_Information_System.Context.DrugInformationContext context)
    {

        Assembly assembly = Assembly.GetExecutingAssembly();

        string resourceName = "Drug_Information_System.Domain.SeedData.PharmaCompanies.CSV";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                CsvReader csvReader = new CsvReader(reader);
                csvReader.Configuration.WillThrowOnMissingField = false;

                var records = csvReader.GetRecords<PharmaCompany>().ToArray();

                foreach (PharmaCompany values in records)
                {
                    context.PharmaCompanies.AddOrUpdate(values);
                }
            }
        }
        context.SaveChanges();
    }

I am not sure whats wrong in my code...

Add objects and save image C# fabric.js

js]1. using asp.net mvc3. i want to draw text and rectangle on the image as group. text and rectangle can be added multiple times. after adding groups i want to save that image, Accuracy is important
I had two choices . First choice is to use canvas.toJSON(). this approach i have to create object using C# graphics class which is painfull and not accurate. second is to export canvas as base64 which is accurate. .
Here is what i have done so far jsfiddle
here is the code giving exception

function SaveResultImage() {
  canvas.deactivateAll().renderAll();
  var base64String = canvas.toDataURL("image/jpg");
  if (!fabric.Canvas.supports('toDataURL')) {
    alert('This browser doesn\'t provide means to serialize canvas to an image');
  } else {
    console.log(base64String);
    // save image posting base64String using ajax// this is working fine
  }
}

exception: VM1226 fabric.min.js:4 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.(…)

lundi 28 novembre 2016

Value cannot be null. Parameter name: incomingMarkupParser

I have an MVC3 project that I need to work on and every time I try to run it I get this Compilation exception;

Value cannot be null. Parameter name: incomingMarkupParser

How do I fix this? It looks like a problem with Razor. My web.config in the Views folder is;

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler" />
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler" />
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>


  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="ITOC4.HtmlHelpers" />
        <add namespace="ITOC4.Models" />
        <add namespace="ITOC4.Web.Models" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="Omu.Awesome.Core"/>
        <add namespace="Omu.Awesome.Mvc.Helpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>
</configuration>

and in the main folder (with lines removed for brevity) the web.config is;

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="elmah">
  </configSections>
  <elmah>
  </elmah>
  <appSettings>
  </appSettings>
  <connectionStrings>
  </connectionStrings>
  <system.web>
    <customErrors mode="Off" defaultRedirect="~/Error/Unknown">
      <error statusCode="404" redirect="~/Error/NotFound" />
    </customErrors>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <sessionState timeout="2880"></sessionState>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership>
    </membership>
    <profile>
    </profile>
    <roleManager enabled="true">
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.WebPages" />
        <add namespace="Omu.Awesome.Core" />
        <add namespace="Omu.Awesome.Mvc.Helpers" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.10.0" newVersion="2.6.10.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="PagedList" publicKeyToken="abbb863e9397c5e1" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.17.0.0" newVersion="1.17.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
  </entityFramework>
</configuration>

And in the packages config I have these lines;

  <package id="Microsoft.AspNet.Mvc" version="3.0.50813.1" targetFramework="net40" />
  <package id="Microsoft.AspNet.Razor" version="1.0.20105.408" targetFramework="net40" />
  <package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" targetFramework="net40" />

mercredi 23 novembre 2016

mardi 22 novembre 2016

Error Format DateTime MVC

enter image description here

I set Format DateTime but have problem this error: LINQ to Entities does not recognize the method "System.String" ToString(System.String)

jeudi 17 novembre 2016

QR Code Scanner from android to web program

I've seen this LINK for reading a QR Code that generated. I am thinking that It is possible to use something like this but the scanner is from android phone and the output is in the web system. Just like the barcode reader it read the barcode and the output is in a Computers. Can this link be modify or can anyone point me to the right link on how to achieve my goal?. Please Thanks. I am searching this for a months

mercredi 16 novembre 2016

Not able to render label tag on a view dynamically

I have below piece of code in .cshtml file.

<div class="row">

            <input type="text" placeholder="Enter POR ID" id="porID" class="col-md-2 input-sm" name="porTextBox">
            <button class="btn btn-primary col-md-2 btn-sm" style="margin-left:15px;width:150px;" type="submit" id="btnCreateTFSItems"><strong>Create TFS Items</strong></button>
            @if (TempData["formState"] != null)
            {
                //@Html.Label("lblsuccess", "Successfully created TFS Work Items!")
                <label id="lblsuccess" style="color:green; visibility:visible">   Successfully created TFS Work Items!</label>
            }
        </div>

and the button is calling the below function in script tag :

<script type="text/javascript">
$(document).ready(function (e) {

    $('#btnCreateTFSItems').click(function () {
        var txt = $('#porID');
        var errorLabel = $('#lblError');
        if (txt.val() != null && txt.val() != '') {
            //alert('clicked');

            $.ajax({
                url: '@Url.Action("CreateWorkItems", "Tables")',
                type: 'POST',
                data: { 'porTextBox': $('#porID').val() }
            });
           // alert('Successfully added');
        }
        else {
            errorLabel.text("Please enter valid PORID");
            return false;
        }
    });

    $("#porID").keypress(function (e) {
        var errorLabel = $('#lblError');
        errorLabel.text("");
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
});

The problem is in .cshtml file, it is checking the condition but its not adding the label. The reason may be because page is not refreshing to render the label. I am new to UI development so I have tried certain options which i found on net but wasn't able to make it work. Is there any way i can achieve this ?

mardi 15 novembre 2016

MVC JQuery Grid Server side pagination

I'm working on a MVC 3 project that uses jq Grid. I want to use server side pagination. The ultimate goals are to return a row count, let the user filter by a few fields, populate the grid with the first page of records (20 records), have the next icon at the bottom of the grid run a Linq to SQL query that populates the next page, and I want to use the built in search functionality to filter the grid and so I need to override that functionality with custom code. I've written a stored procedure that will return the data for the specified page. I need help with the rest.

Rate product on the basis of comment

I faced difficulty in rate the product. My website has different products and every product has comment box. So how can i rate the product on the basis of comments instead of manually rate the product. Is there any source from where i learn this. My basic problem is rate the product on the basis of comments that is given by user.

lundi 14 novembre 2016

How to send mail automatically asp.net mvc

How to send mail automatically before 2 day and after deactivate of user account

Poblem adding reference to System.Web.Mvc 3.0.0.1

I got an old a .net application that is not mine. It was using the MVC 3.0.0.0 but I upgraded to the MVC 3.0.0.1. I am trying to make it run but I can not add the reference to System.Web.Mvc. I added the reference but next time I open it is unchecked.

I have to add that I am new with asp.net and MVC so maybe I am missing something obvious.

How should I add all the reference that I am missing ?

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.1" />
  </dependentAssembly>
</assemblyBinding>

Attach Model to Existing View

I am new to MVC. Developing MVC case study, I have created the view without attaching the model and done few design on that.

Now we would like to attach model to the existing view, how to attach the model to that.

I have tried to open the model attaching dialog box. I could not open the model attaching dialog box, if i creating new view its displaying the dialog box to attach the model. i can not do the same thing for the already created view

how to attach the model for existing View?

dimanche 13 novembre 2016

How to recover data through a foreign key

I have 2 tables Users and Services, linked by an associative table called contract wich conatain id_User and id_Service as foreign keys. I want to recover those two foreign keys by clicking on a button wich create a new contract, not only the FK but also some values such as service name for id_Service, cuz table Contract take this attribut as his name too, and how to pass his value in the controller!!? plz any solutions??

jeudi 10 novembre 2016

C# - "An element with the same key was already added"

I work in ASP.NET MVC and I am blocked(surrounded) in my model with this damned error " an element with the same key was already added", I understand not at all why while I have almost the same code with different requests in other methods of my model.

And I do not think that the problem can come from the request because I have already used her(it) as before in another project..

Here is the code of my model:

public Dictionary<string,string> getDonnee()
{
    Dictionary<string, string> list = new Dictionary<string, string>();

    SqlConnection cn;
    SqlDataAdapter da;
    DataSet ds;

    cn = new SqlConnection(CS_DW);
    cn.Open();

    da = new SqlDataAdapter("select distinct(ltrim(rtrim(cpic))) as code, cpic as lib from [DW].[dbo].[PIC_PROD_S001] ", cn);
    ds = new DataSet();
    da.Fill(ds, "code");

    list.Add("REEL", "REEL");
    foreach (DataRow row in ds.Tables["code"].Rows)
    {
        list.Add(row["code"].ToString(), row["lib"].ToString());
    }

    cn.Close();
    return list;
 }

My controller :

public ActionResult rspic002()
{
   ViewData["Ddl_donnee"]  = model.getDonnee();

   return View();
}

My view :

List<SelectListItem> listDonnee = new List<SelectListItem>();

foreach (KeyValuePair<string, string> key in ViewData["Ddl_donnee"] as Dictionary<string, string>)
{
        SelectListItem donnee = new SelectListItem();
        donnee.Value = key.Key;
        donnee.Text = key.Value;
        listDonnee.Add(donnee);
}

Thank you in advance for your help

mardi 8 novembre 2016

How to exclude asp.net identity default table and How to use Asp.net Identity in asp.net API

I have tried to remove deafault table of asp.net identity.I need to create user in asp.net table customized table.How can do ?

DatePicker in asp.net mvc visual basic

Helo, I'm working on a small Project with Visual Studio 2015, ASP.NET 5, MVC. I need to know how to develop in visual basic to use a datepicker to enter dates using a calendar in the date fields.

lundi 7 novembre 2016

Getting error "the element 'httpCookies' has been locked in a higher level configuration"

I'm getting the error "The element 'httpCookies' has been locked in a higher level configuration" when i try to access an asp.net mvc 3 application. This happens when i add the line below inside my <system.web> section.

<httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" />

This is happening on windows server 2003 (IIS 6). The error doesn't occur on windows 7 & Windows 2008 R2 (IIS 7 & above)

I have checked the machine.config file on both the windows 2003 server and my windows 7 development machine and it contains below line on both machines.

<section name="httpCookies" type="System.Web.Configuration.HttpCookiesSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

dimanche 6 novembre 2016

Creating an IF - Else Statement in MVC Razor [duplicate]

This question already has an answer here:

I am getting an error Object reference not set to an instance of an object. in running my MVC Html Razor. I search on google on how to create an IF-Else in razor and found some good answer. But in my case I am getting an error.

My Code

<td  style="text-align: left" >
                    <div id="divEBSN">
                    @if (Model.RCEducationalBackground.School.SchooldName != null)
                    {
                       <span style="color: Red">@Html.DisplayFor(model => model.RCEducationalBackground.School.SchooldName)</span>    
                    }
                    else { 
                        <span style ="color:Red">@Html.DisplayFor(model => model.RCEducationalBackground.SchoolNameEducBG)</span>
                    }
                    </div>
                </td>

samedi 5 novembre 2016

how to create a link in one page that when you click on. will change another page

i'm using mvc.net and i would like to create a links in my homepage that when i click on, will changes some information in the about page. and of curse moves me to the about page. i tried to create an action link but it wouldn't solve the problem. tank you for the help!!!

vendredi 4 novembre 2016

Equivalent of ViewData["MenuItem.StoreMenuId"] using ViewBag? ViewBag.MenuItem.StoreMenuId doesn't work

Is it possible to convert ViewData["MenuItem.StoreMenuId"] to ViewBag? I use ViewBags to store IEnumerable<SelectListItem> so I can bind to @Html.DropdownListFor in my views. This works fine if its a simple property that isn't nested (i.e., StoreMenuId):

ViewBag:

ViewBag.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.StoreMenuId, null, "", new { @class = "form-control" })


But what if the property is nested (i.e., MenuItem.StoreMenuId)? This doesn't work:

ViewBag:

ViewBag.MenuItem.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })


What ends up working is changing ViewBag.MenuItem.StoreMenuId to ViewData["MenuItem.StoreMenuId"] This works:

ViewData:

ViewData["MenuItem.StoreMenuId"] = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })

There is no ViewData item of type 'IEnumerable

Controller

DepartmentLevel departmentlevel = new DepartmentLevel();
ViewBag.DepartmentLevel = new SelectList(db.DepartmentLevels, "DepartmentLevelId", "DepartmentLevelDesc", departmentlevel.DepartmentLevelId).OrderBy(a => a.Text);

HTML

 @Html.DropDownList("DepartmentLevel", ViewData["DepartmentLevel"] as SelectList, "All Department", new { @style = "width:200px;" })

What is the problem?.

jeudi 3 novembre 2016

Error SQLSERVER attempt to attach an auto-named database

this Error: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: An attempt to attach an auto-named database for file C:\Program Files (x86)\IIS Express\DB Report.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC

mycoding :

Help me plase .. I have problem a few day

How to generate authentication token after FormsAuthentication success in mvc 2

I'm developing MVC 2 web application. I'm using FormsAuthentication for sign in users to my application. I want to generate an authentication token after users are successfully login to the application. I have to pass that authentication token to another application. Are there any best ways to accomplish this task using MVC2(.net framework 4.0). Please help me to solve this problem.

Page Index is always 0 in devexpress gridview

Page Index is showing always zero.

I have implemented the Grid like the below Url: http://ift.tt/2egNxTW

and in the above url User's issue is resolved by using the below line of code
ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder(); (in Global.asax.cs) but it did not work for me.

Implementation is not exactly the same like in the above link provided but overall it is same.

@{

Html.EnableClientValidation();

Html.EnableUnobtrusiveJavaScript();

    var grid = Html.DevExpress().GridView(settings => {

        settings.Name = "GridView1";

        settings.KeyFieldName = "StudentId";

        settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };

        settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };

        settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };

        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
        settings.SettingsBehavior.ConfirmDelete = true;

        settings.SettingsPager.PageSize = 20;


        settings.CommandColumn.Visible = true;
        settings.CommandColumn.ShowNewButton = true;
        settings.CommandColumn.ShowDeleteButton = true;
        settings.CommandColumn.ShowEditButton = true;

        settings.SettingsPager.PageSizeItemSettings.Visible = true;
        settings.SettingsPager.PageSizeItemSettings.Items = new string[] { "10", "20" };

        settings.SettingsCookies.Enabled = true;
        settings.SettingsCookies.CookiesID = settings.Name;
        settings.SettingsCookies.StoreColumnsVisiblePosition = true;
        settings.SettingsCookies.StoreColumnsWidth = true;
        settings.SettingsCookies.StoreFiltering = true;
        settings.SettingsCookies.StoreGroupingAndSorting = true;
        settings.SettingsCookies.StorePaging = true;

        settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
        settings.Settings.ShowColumnHeaders = true;
        settings.Settings.ShowFilterRow = true;
        settings.Settings.ShowFilterRowMenu = true;
        settings.Settings.ShowFooter = true;
        settings.Settings.ShowGroupButtons = true;
        settings.Settings.ShowGroupedColumns = true;
        settings.Settings.ShowGroupPanel = true;
        settings.Settings.ShowHeaderFilterButton = true;
        settings.Settings.ShowTitlePanel = true;
        settings.Settings.UseFixedTableLayout = true;

        settings.HtmlRowPrepared = (s, e) =>
        {
            MVCxGridView g = s as MVCxGridView;
            var index = g.PageIndex;

        };
        settings.CustomBindingRouteValuesCollection.Add(
       GridViewOperationType.Paging,
       new { Controller = "CustomBinding", Action = "MyPagingAction" }
   );

        settings.CustomBindingRouteValuesCollection.Add(
        GridViewOperationType.Sorting,
        new { Controller = "CustomBinding", Action = "MySortingAction" }
    );


        settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
        settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
        settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
        settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
        settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;


        settings.Columns.Add("StudentName");
        settings.Columns.Add("StudentAge");
        settings.Columns.Add("StudentGrade");
        settings.Columns.Add("StudentAddress");


        settings.CellEditorInitialize = (s, e) =>
        {
            ASPxEdit editor = (ASPxEdit)e.Editor;
            editor.ValidationSettings.Display = Display.Dynamic;

        };
            });
        if (ViewData["EditError"] != null){
        grid.SetEditErrorText((string)ViewData["EditError"]);
        }
}
@grid.BindToCustomData(Model).GetHtml()

Please suggest

mercredi 2 novembre 2016

CSHTML Redirect to Another CSHTML

I am new to MVC and working on my own project. I have a small question regarding redirect to another page. Now the CSHTML is in same view folder. I am passing some data from SQL so every click has a different parameter. How do I set it to where the CSHTML knows to change the parameter itself.

CSHTML

@Html.ActionLink(Html.DisplayFor(modelItem => item.PlayerName).ToHtmlString(), "Details", new { sortOrder = ViewBag.BrandSortParm }) <br />

This only gets me to main page without the parameter of the specific record.

'The network path was not found' every first attempt to Azure SQL Server

I am developing a web application, using Visual Studio 2013 and a SQL SERVER database created on Azure.

Almost every time that I took more than 30 seconds to build and re-run the application (F5) I get this error below. The connection sql connection to SQL Timed-out and this is the error raised.

[Win32Exception (0x80004005): The network path was not found]

I retry the connection and the problem goes away. The point is that I am loosing so much time on this issue.

I have two SQL connections, to the same server, one for OWIN context, and another used by Entity Framework 6. Both MARS enable.

What I tried:

  • Disabled AVG Components
  • Disabled Windows Firewall for Home/Enterprise networks
  • Changed my dns to Google's dns (8.8.8.8/8.8.4.4), if I open nslookup and try to resolve my database path, it works every time.
  • Changed my sql connection parameters: "Connection Timeout=3;ConnectRetryCount=3;ConnectRetryInterval=1", so it takes less time to raise the error, and I can retry faster and not loose so much time.

Azure doesn't permit me "pinging" the server, since never returns. So, I am really in trouble on how to troubleshoot/monitor this issue.

Any suggestions on how to troubleshoot this are appreciated.

Getting exception StartEdit on DevExpress Grid

I have a patial view with following code(with custom data binding):

Partial View @{

Html.EnableClientValidation();

Html.EnableUnobtrusiveJavaScript();

    var grid = Html.DevExpress().GridView(settings => {
        settings.Name = "GridView1";
        settings.KeyFieldName = "StudentId";
        settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };

        settings.CustomActionRouteValues = new { Controller = "Editing", Action = "ChangeEditModePartial" };

        settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };

        settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };
        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
        settings.SettingsBehavior.ConfirmDelete = true;
        settings.SettingsPopup.EditForm.Width = 600;

        settings.CommandColumn.Visible = true;
        settings.CommandColumn.ShowNewButton = true;
        settings.CommandColumn.ShowDeleteButton = true;
        settings.CommandColumn.ShowEditButton = true;


        settings.CustomBindingRouteValuesCollection.Add(
       GridViewOperationType.Paging,
       new { Controller = "MyController", Action = "MyPagingAction" }
   );

        settings.CustomBindingRouteValuesCollection.Add(
        GridViewOperationType.Sorting,
        new { Controller = "MyController", Action = "MySortingAction" }
    );
        settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
        settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
        settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
        settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
        settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;


        settings.Columns.Add("StudentId");
        settings.Columns.Add("StudentName");
        settings.Columns.Add("StudentAge");
        settings.Columns.Add("StudentGrade");
        settings.Columns.Add("StudentAddress");

        settings.PreRender = (sender, e) =>
        {

            ((MVCxGridView)sender).StartEdit(0);/**//This is the Exception line**
        };
        settings.CellEditorInitialize = (s, e) =>
        {
            ASPxEdit editor = (ASPxEdit)e.Editor;
            editor.ValidationSettings.Display = Display.Dynamic;

        };
            });
        if (ViewData["EditError"] != null){
        grid.SetEditErrorText((string)ViewData["EditError"]);
    }
}
@grid.BindToCustomData(Model).GetHtml()///Custom binding

Please suggest the solutions:

Exception: A primary key field specified via the KeyFieldName property is not found in the underlying data source. Make sure the field name is spelled correctly. Pay attention to the character case.

mardi 1 novembre 2016

How to DownLoad Mail Attachment by using EWS in Exchange

I am using ASP.Net MVC.

using (ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding())
            {
                ICredentials creds = new NetworkCredential("username", "password");
                exchangeServer.Credentials = creds;
                exchangeServer.Url = "http://ift.tt/2e0ZAJw";

                FindItemType findItemRequest = new FindItemType();
                findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

                // define which item properties are returned in the response
                ItemResponseShapeType itemProperties = new ItemResponseShapeType();
                itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
                findItemRequest.ItemShape = itemProperties;

                // identify which folder to search
                DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
                folderIDArray[0] = new DistinguishedFolderIdType();
                folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

                // add folders to request
                findItemRequest.ParentFolderIds = folderIDArray;

                // find the messages
                FindItemResponseType findItemResponse = exchangeServer.FindItem(findItemRequest);

                // read returned
                FindItemResponseMessageType folder = (FindItemResponseMessageType)findItemResponse.ResponseMessages.Items[0];
                ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
                folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
                ItemType[] items = folderContents.Items;

                // if no messages were found, then return null -- we're done
                if (items == null || items.Count() <= 0)
                { return null; }


                // FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
                BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
                for (int i = 0; i < items.Count(); i++)
                {
                    itemIds[i] = items[i].ItemId;
                }


                GetItemType getItemType = new GetItemType();
                getItemType.ItemIds = itemIds;
                getItemType.ItemShape = new ItemResponseShapeType();
                getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
                getItemType.ItemShape.BodyType = BodyTypeResponseType.HTML;
                getItemType.ItemShape.BodyTypeSpecified = true;

                GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemType);
                ItemType[] messages = new ItemType[getItemResponse.ResponseMessages.Items.Count()];
                List<MailRecipientModel> model = new List<MailRecipientModel>();
                for (int j = 0; j < messages.Count(); j++)
                {
                    messages[j] = ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[j]).Items.Items[0];
                    MailRecipientModel model1 = new MailRecipientModel();

                    model1.Subject = messages[j].Subject;
                    model1.FromAddress = messages[j].Sender.Item.EmailAddress;
                    model1.DisplayName = messages[j].Sender.Item.Name;
                    model1.Date = messages[j].DateTimeReceived.Date.ToString();
                    model1.MailBody = messages[j].Body.Value;
                    model1.MsgId = messages[j].ItemId.Id;
                    if (messages[j].Attachments != null) {
                     //
                    }
                    model.Add(model1);
                }              

                return model;
            }

This my code I wanna download attachment file and if attachment file is image so its display in browser.

I am using Microsoft ActiveSync Exchange Server.

If you know how to do so please help me.

How replace '~' symbol in MVC with physical path

In Mvc application if the Layout is added with

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery") .

Need a solution to replace the

~

symbol .So that Output should not be like /Content/themes/base/jquery.ui.core.css in render page .

Instead

localhost:xxxxx/Content/themes/base/jquery.ui.core.css .

This Localhost need to be added when mvc application is run under IISExpress wherein It get modified to hosted application path when hosted into the server

samedi 29 octobre 2016

Visual Studios 2015 Keeps Launching with my domain name not localhost

I have an old website(asp.net mvc 3) that I have to move since one of my msdn subscriptions ran out on Azure. I loaded up the solution and hit F5 and it launched my browser but it is pointing to my domain name not my local host.

Then I just see a 500 error. I want to get back to local host and see if it works locally first before I deploy on a Vm I know have.

vendredi 28 octobre 2016

Why we have only two data structure "stack" and "heap"?

Why we have only two data structure "stack" and "heap"? like int value will be stored in stack and similarly reference type value will be stored in heap.

Why we cannot use some other data structure? Is there any specific reason to use only two these stack and heap.

Thanks a lot.

jeudi 27 octobre 2016

MVC 3 Editorfor template for dynamic property

I am trying to use the EditorFor template with a dynamic view

my view looks like

@model dynamic
.....
.....
<div class="form-group">
    @Html.LabelFor(x => x.AddressLine1, new { @class = "control-label" })
    <div class="input-field">
         @Html.TextBoxFor(x => x.AddressLine1, new { @class = "form-control" })
    <div class="help-block with-errors">
         @Html.ValidationMessageFor(x => x.AddressLine1)
    </div>
    </div>
</div>

But I am running into the error

CS1963 An expression tree may not contain a dynamic operation

Is it possible to use editorfor templates with dynamic views ? If so how could I get this to work

thanks

Multiple view models in Razor view

What would be the best way to for a razor view to handle multiple models? for an MVC3 application.

I have two models, both similar, but the Postcode field is required for one model and not for another

public class IrelandPostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [DisplayName("Eircode")]
    public string Postcode { get; set; }

}

public class PostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [Required(ErrorMessage = "Please enter your postcode")]
    [DisplayName("PostCode")]
    public string Postcode { get; set; }

}

In the controller I want to use a particular view model depending on a country I am passed. Something like

public virtual ActionResult PostcodeLookup(string country)
{
    if (country == Country.UnitedKingdom)
         return View(new PostcodeLookupViewModel());
    else
         return View(new IrelandPostcodeLookupViewModel());
}

I was handling this in the view with

@model dynamic

The problem I have with this is my view contains partial views

@Html.Partial("~/Views/Shared/_Progress.cshtml", Model.Progress)

and I run into the error 'HtmlHelper' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched'

Can anyone advise how I can handle the Partial View?

Thanks

ibm watson speech to text api for pure jquery/javascript

am complete new to the IBM watson Speech to Text and also not good at sending live audio files from html to server.

The intention is to integrate IBM watson speech to text (free version) in a web application to allow for dictation and note taking . have previously implemented the HTML speech api but the organization doesnt seem happy with its accuracy level .

as said that have only yet seen their demo which seems to show that live transcription is a possibility but cannot seem to find a sample code to use.

primarily intend to use on javascript code for the purpose (the application is however built in ASP MVC 3) .

it would be a great help if any guidance can be given or any step by step guide to implement speech to text in a web app that is free for use

any help appreciated.

mardi 25 octobre 2016

How to Pass javascript:window.open as Asp.net MVC @URL.action

I have this url which i am trying to access but it is not working on MVC

Can anyone convert it to @url.action below

  <td> <a href="javascript:window.open('../AspNetForms/P4C/P4CGeneric.aspx?appId=@item.Hivrp_app_name_fk&P=@item.rpt_path','mywindow','width=1100,height=800')">View/Run</a></td>

What is the best approch to be good at it so quickly?

i'm kind of new to asp.net. what is the best approch to be good at it so quickly?

vendredi 21 octobre 2016

ASP.NET MVC/WEB API Exception handling

I understand that there are multiple ways by which this can be achieved (try...catch...finally, OnException or ExceptionFilter) but my question is, can we just implement one strategy for controller and rest is OK?

What I mean to say is, say for example, I have an assembly "A" which is being called from my MVC application. now if I implement OnException for exception logging, will it take care all exceptions that are generated in assembly "A" and also in Controller? (Here we can assume that, the only way to access assembly "A" is by any action method from controller).

I just want to make sure by this is that MY ASP.NET application must not crash when hosted on IIS just because too many unhandled exceptions are generated. (The one that I don't know which will be ignore by OnException or ExceptionFilter)

Cannot convert from 'System.Web.Mvc.ModelStateDictionary' to 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary'

I have getting below errors

CS1503 Argument 3: cannot convert from 'System.Web.Mvc.ModelStateDictionary' to 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary'

When i try to build my WEB API project on MS VS 2015.

javascript - Highcharts - Type Bar - How to set different starting for each bar

I have bar chart, in which I want each bar to start different value. Now they all starts from 0. I have only find how to change the starting point, that would be the same for each. Like all staring from 1.

But I need the First to be draw like 1-2, Second: 1-4 and Third: 7-10. How can I vary it for different cases?

var chart = new Highcharts.Chart({
chart: {
        type: 'bar',
        renderTo: 'container'
 },
 xAxis: {
        categories: ['First', 'Second', 'Third']
 },
 series: [{
        data: [{
            name: 'Point 1',
            y: 2
        }, {
            name: 'Point 2',
            y: 4
        }, {
            name: 'Point 3',
            y: 10
        }]
 }]
 });

jeudi 20 octobre 2016

Split is not working in IE9

Split function is not working in IE9

Here is my code

 <script type="text/javascript">
        var currURL = window.location.href;
        $(document).ready(function () {
            var hasFilters = currURL.split('?')[1];
            alert(hasFilters);    
            if (hasFilters) {
                abc(currURL);
            }
        });
</script>

When I am running this script in IE9 at that time, in alert showing "undefined" while at other browser in alert shows concate string for currurl for ex : "abc=def:ijk!!a!!".

So I want to do same in IE9.

Maybe somebody can point me to the right answer? Thx

Sending List from View to Controller results in null List in MVC

I'm trying to create a List of users in MVC, where there's a button to add users generated randomly and there's a delete button for each user to erase them from the list. I send it from the Controller to the View and it generates one user. When I try to add one more, it just changes it. I guess it deletes the items in the List. I'm trying to pass the list back to the Controller, but it doesn't work. Can someone help please?

My Model:

public class UsersClass
{
    public int Code { get; set; }
    public string Name { get; set; }

    public UsersClass(int Code, string Name)
    {
        this.Code = Code;
        this.Name = Name;
    }
}

My Controllers:

List<UsersClass> UsersList = new List<UsersClass>();
public ActionResult Index()
{
    return View(UsersList);
}

[HttpPost]
    public ActionResult AddUser(List<UsersClass> UsersList)
    {
        if (UsersList == null)
        {
            int a = 123;
            UsersList = new List<UsersClass>();
        }
        Random generator = new Random();

        string[] vez_nevek = new string[10] { "Kovács", "Szekeres", "Király", "Szabó", "Vicha", "Kozma", "Ferencz", "Pócsi", "Tinka", "Horváth" };
        string[] ker_nevek = new string[10] { "Lajos", "Barnabás", "Róbert", "Balázs", "János", "Béla", "Petra", "Anna", "Ferenc", "Attila" };

        string vezetek_nev = vez_nevek[generator.Next(vez_nevek.Length)];
        string kereszt_nev = ker_nevek[generator.Next(ker_nevek.Length)];

        UsersList.Add(new UsersClass(generator.Next(100000, 999999), vezetek_nev + " " + kereszt_nev)); 

        return View("~/Views/UserManagement/Index.cshtml", UsersList);
    }

And my View to add a user:

<h2>User Management</h2>

@using (Html.BeginForm("AddUser", "UserManagement", FormMethod.Post)) {

int index = 0;
foreach (var item in Model)
{
    Html.Hidden("item[" + index + "].Code", item.Code);
    Html.TextBox("item[" + index + "].Name", item.Name);
    index++;
}
<input type="submit" value="Add User" />

}

mercredi 19 octobre 2016

How to get LinkedIn person posts feed

I have a requirement where i need to render LinkedIn posts feed on MVC application.I have created the Acccesstoken but the information when calling the API is as per the below but not the posts which i have shared .

Any suggestion on the same will be highly appreciated

{ "firstName": "xxxxx", "headline": "aaaa", "id": "bbb", "lastName": "ccccc", "siteStandardProfileRequest": {"url": "http://ift.tt/2eRCi8X"} }

How to change url segments in mvc?

Default behavior is that whether to append id at the end or url as url segment or not. I have two other parameter i.e. "NewYork" and "address" instead of id. How to make routing url in RouteConfig.cs to work something it like http://ift.tt/2ehwsfp.

dimanche 16 octobre 2016

How to take year 2016 onwards?

I have this code below working fine w/o the condition in the line payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 because it gives me an error Invalid cast from 'Boolean' to 'DateTime'. and the code that I added is return a boolean

var per = (from p in db.Periods select new { periodId = p.PeriodId, periodStart = p.StartDate, periodEnd = p.EndDate, payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 });
var periods = (from p in per.AsEnumerable() select new { perId = p.periodId, PayrollEndDate = Convert.ToDateTime(p.payrollEndDate).ToShortDateString() }).AsQueryable();
ViewBag.PeriodEndDate = new SelectList(periods, "PayrollEndDate", "PayrollEndDate", null);

How to take the year 2016 onwards?

HTML.BeginForm pass in arugment

I am new to MVC. A bit late to the game but I am trying to learn. I am sure this has been asked, but I am having trouble.

I want the form to post to

~/search/index/{argument}

For example:

http://localhost:53967/Search/index/foobar

The {argument} is the value of the textbox.

I have the following in my shared _Layout.chtml. The view is not bound to any Model as it will be a text field for searching.

<ul class="nav navbar-nav navbar-right">
   <li>
      @*/Search/index/{argument}*@
      @using (@Html.BeginForm("Index", "Search",  FormMethod.Get, new { @class = "navbar-form navbar-right" }))
      {
      <div class="input-group col-md-12 col-sm-12">                                
         @Html.TextBox("phrase", (String)ViewBag.Message, new { placeholder = "Search", @class = "form-control" })
         <span class="input-group-btn">
           <button class="btn btn-danger" type="button">
             <span class="glyphicon glyphicon-search"></span>
           </button>
         </span>
      </div>
      }                      
   </li>
</ul>

Here is my controller:

public class SearchController : Controller
    {
        // GET: /search/index/{argument}
        // example = http://localhost:53967/Search/index/foobar
        public ActionResult Index(String phrase)
        {
            String _phrase = phrase.Encode();

            ViewBag.Message = _phrase;

            return View();
        }

        [HttpPost] // post back
        public ActionResult Index(SearchModel model) {


            return View();
        }
    }

vendredi 14 octobre 2016

Unity resolver error using config

I am using Unity.MVC3 IOC container for DI. Trying to set up it using Unity configuration. With this configuration in place it is throwing " The type name or alias ExcelWriter could not be resolved. Please check your configuration file and verify this type name." error when it tries to resolves.

Interfaces are declared in a library: Framework
Namespace: Framework.Interfaces

namespace Framework.Interfaces
{
    public interface IExcelWriter
    {
        byte[] Write(DataTable dataTable);

        byte[] Write<T>(T data);
    }
}

Implemented classes are in separate library: ExcelUtility
Namespace: ExcelWorker

namespace ExcelWorker
{
    public class ExcelWriter : IExcelWriter
    {
        public byte[] Write(DataTable dt)
        {
            throw new NotImplementedException();
        }


        public byte[] Write<T>(T data)
        {
            throw new NotImplementedException();
        }
    }
}

And my configuration looks like :

<unity xmlns="http://ift.tt/1g8Zbje">
    <alias alias="IExcelWriter" type="Framework.Interfaces.IExcelWriter, Framework" ></alias>
    <assembly name="Framework" />
    <assembly name="ExcelUtility" />        
    <namespace name="ExcelUtility.ExcelWorker" ></namespace>
    <container>
      <register type="IExcelWriter" mapTo="ExcelWriter" />
    </container>
  </unity>

Cannot authenticate a call to ASP.NET MVC3 service with a self-signed client certificate

I have an ASP.NET MVC3 service running in IIS 7.5 with .NET Framework 4.5 where I want to secure access to one of the subpaths with a client certificate. For that subpath I crafted a controller with is labeled with a specially crafted attribute which would access the request client certificate

public class CheckCertAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add(
            "CheckCertAttribute", "entered");
        var cert = filterContext.HttpContext.Request.ClientCertificate;
        // check the cert here, optionally return HTTP 403
    }
}

Initially OnActionExecuting() is being invoked but Certificate is null. Turns out I need to enable SslNegotiateCert in web.config:

<location path="PathOfInterest">
<system.webServer>
  <security>
    <access sslFlags="SslNegotiateCert"/>
  </security>
</system.webServer>
</location>

Once I do this the client always receives HTTP 403 and the attribute is no longer invoked.

The client certificate is self-signed and exported as .pfx (with a private key) so I guess the problem is that once it arrives on the server side the server doesn't like it and refuses to accept it and pass through. The client side uses HttpWebRequest:

var cert = new X509Certificate2(pathToPfx, password);
var request = (HttpWebRequest)WebRequest.Create("http://ift.tt/2e22U4z");
request.ClientCertificates.Add(cert);
request.GetResponse();

I've already used this approach earlier and it worked. The first case was when the client certificate was not self-signed but was signed by an intermediate certificate which in turn was signed by some trusted root authority - in this case my service configured very similarly would receive it just fine. The second case was using a self-signed client certificate to make Azure Management Service calls but in this case I have no idea how the server side is configured.

I therefore came to conclusion that it's a self-signed nature of the certificate which makes it "not working". I have so do something extra - perhaps add something into web.config or add the certificate into some certificate store on the server side. I just have no idea what this should be.

How do I make this setup work?

jeudi 13 octobre 2016

ASP.net MVC dynamic bundling of CSS

We are working on one requirement where we need to bundle CSS according to clients.

e.g. client1 will have style1 and client2 will have style2 folders and based on clients we need to bundle CSS. We can have N numbers of clients.

/MyApp/client1 - should have style1 CSS with bundling and minification

/myApp/client2 - should have style2 CSS with bundling and minification

from URL we are getting client ID parameter to decide which style folder needs to be load but how to achieve dynamic bundling and minification at runtime for loaded CSS?

Access to the path XXX is denied while uploading video in MVC

I have MVC application throwing error 'Access to path XXX denied' while uploading video. Error is not thrown when image is being uploaded.

Any thing wring in my code?

  [HttpPost]
        public ActionResult Index(HttpPostedFileBase video)
        {
            //var httpPostedFile = Request.Files[0];
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();   
            //ffMpeg.GetVideoThumbnail(Server.MapPath("~/Images"), "video_thumbnail.jpg");           

            var fileName = Path.GetFileName(video.FileName);
            var path = Server.MapPath("~/Images");
            video.SaveAs(path);
            ffMpeg.GetVideoThumbnail(path, "video_thumbnail.jpg");       


            return View();
        }

Validation for multiple partial views not working

I have a view with Tuple model. I'm loading 4 partial views in this main view as below

  1. @Html.Partial("~/Views/Partial/_Tab1Input.cshtml", Model.Item1.Tab1Input)
  2. @Html.Partial("~/Views/Partial/_Tab2Input.cshtml", Model.Item1.Tab2Input)
  3. @Html.Partial("~/Views/Partial/_Tab3Input.cshtml", Model.Item1.Tab3Input)
  4. @Html.Partial("~/Views/Partial/_Tab4Input.cshtml", Model.Item1.Tab4Input)

I'm loading these partial views on tab click. On click of submit, only active Tab is getting validated. Means if I'm in tab 2 partial view and clicked on submit, then required field validation will happen, but tab 1 partial view's validation will be ignored, and the form is getting Posted.

Please assist me so that on click of submit, all 4 partial views required field validation should happen.

Populating a View Model with a foreach loop when one field could be null?

I have some old tables from an old database which I am trying to use to populate a View Model. The controller action looks for records in one old table where the email matches the current users email and then populates the View Model based on a list derived from those matches. This is my controller action:

public PartialViewResult OldCourses()
    {
        var email = User.Identity.GetEmail();

        var reglist = nb.old_register
            .Where(i => i.email == email).ToList();

        if (reglist != null)
        {
            var viewModel = new OldCourseViewModel();

            foreach (var reg in reglist)
            {
                viewModel.StudentID = reg.studentid;
                viewModel.CourseTitle = nb.old_courses.FirstOrDefault(j => j.courseid == nb.old_Cohorts.FirstOrDefault(h => h.cohortname == reg.cohort).modulename).coursetitle;
                viewModel.Cohort = reg.cohort;
                viewModel.Progpct = nb.student_progress.FirstOrDefault(k => k.studentid == reg.studentid).percentage;
            };


            return PartialView("OldCourses", viewModel);
        }

It is possible for viewModel.Progpct to return null as there may not be an entry in the student_progress table for each record in reglist. This means I get an error, Object reference not set to an instance of an object.

The View Model is as follows:

public class OldCourseViewModel
{
    public int StudentID { get; set; }
    public string CourseTitle { get; set; }
    public string Cohort { get; set; }
    public decimal? Progpct { get; set; }
    public string icon_class { get; set; }
    public string icon_colour_class { get; set; }
    public string titleabbrev { get; set; }

}

The field 'percentage' from the old table is as follows:

public Nullable<decimal> percentage { get; set; }

None of the old tables have foreign key relationships and I can't change any of those tables in any way.

I appreciate that the foreach loop can't handle the null, even though the field is nullable in the View Model.

My first question is what is the best way to handle this situation so that this field can be returned null when it is null?

My second question is, if there are multiple records in the reglist, how can I make the foreach loop cycle through each record in the reglist and generate a new record in the View Model for each of those in the reglist?

Edit - On Stephen's suggestion, I did the following:

var pctcheck = nb.student_progress.FirstOrDefault(k => k.studentid == reg.studentid);

                if (pctcheck != null)
                {
                    viewModel.Progpct = pctcheck.percentage;
                }          

This answers my first question correctly.

Unexpected "foreach" keyword after "@" character. Once inside code, you do not need to prefix constructs like "foreach" with "@"

I am a beginner in .net I have an error in the following lines. I am not able to find out why the error actually arises.

@if(Model.FilteredDevice.Count()>0)
{
@foreach(FModel d in Model.FilteredDevice)
{
// other statements
}
}
else
{
<td> no text matching </td>
}

The complete error message is : An exception of type 'System.Web.HttpParseException' occurred in System.Web.WebPages.Razor.dll but was not handled in user code

Additional information: Unexpected "foreach" keyword after "@" character. Once inside code, you do not need to prefix constructs like "foreach" with "@".

mercredi 12 octobre 2016

Why is my controller action filter no longer invoked once I override SSL settings with a "location" element?

I have an ASP.NET MVC3 application with an action filter attribute applied to a controller:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add(
            "MyFilterAttribute", "entered" );
    }

    public override void OnResultExecuted(
        ResultExecutedContext filterContext)
    {
         filterContext.HttpContext.Response.Headers.Add(
             "MyFilterAttribute", "exited" );
    }
}

[MyFilter]
public class MyController : Controller
{
    public ActionResult MyAction()
    {
        return new EmptyResult();
    }
}

MVC routing maps /MyPath/MyAction to the controller-action pair above.

and the client code invokes http://ift.tt/2dVY8oV and dumps the response headers.

Initially it works - I see that the response received on the client contains two MyFilterAttribute headers as expected.

Then I add a location element to web.config:

<configuration>
  // lots of stuff, then
  <location path="MyPath">
    <system.webServer>
      <security>
         <access sslFlags="SslNegotiateCert"/>
      </security>
    </system.webServer>
  </location>
</configuration>

and once I redeploy with these changes the response headers no longer contain the two MyFilterAttribute items.

Adding location to web.config is the only change. Once I remove it the old expected behavior is back.

It looks like adding a location elements somehow breaks MVC attributes.

What might be causing this behavior?

Is signalR is for chat application website only?

I found this blog which is implementing signalr to asp.net mvc3.

Is there any function of signalr like real time updating/reloading a jqgrid?

Scenario for jqgrid

I have to PC. PC1 is for Client and PC2 is for Server. PC2 is already open the view(included the jqgrid) that he needed to confirm the request from the PC1. What my project is doing so far is when requesting from PC1 the view from PC2 is needed to be refresh in order see the requested data from PC1.

If signalr don't support this what else is the best way to achieve my problem?.

mardi 11 octobre 2016

In ASP.NET is _bin_deployableAssemblies obsolete for ASP.NET MVC version 4+

I have been tabbed with upgrading an older ASP.NET MVC 3.0 application to ASP.NET MVC 5.0. In the solution there is a _bin_deployableAssemblies that contains some subset of ASP.NET MVC assemblies.

At the very least I need to upgrade the versions, but when I complete my upgrade can I do away with this and rely on nuget to bring the right versions of these to the bin folder?

samedi 8 octobre 2016

trying for user authentication for a web app project in .Net

I am trying to build a bank web app as part of our course project, but I get this error regarding user : System.InvalidOperationException: The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://ift.tt/WvrniC). When I try to migrate it gives error : The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.WishLists_dbo.Accounts_AccountId". The conflict occurred in database "db_9b1d65373e9b4f0faa8eecf677186e7d", table "dbo.Accounts", column 'Id'. Plz help

vendredi 7 octobre 2016

Display same data again and again in asp.net mvc

this is my linq code--------->     
     var coursename = Session["course"].ToString();
                var location = Session["location"].ToString();
                var result = (from insti in db.Institute_Master
                              join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
                              join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
                              join  facility in db.Facility_Detail  on insti.InstituteId  equals facility.InstituteId
                              join  masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
                              where coursemaster.CourseName == coursename || insti.City == location
                              select new
                              {
                                  //Id = insti.InstituteId,
                                  name = insti.InstituteName,
                                  university = insti.University,
                                  Contact = insti.ContactNo,
                                  address = insti.Address,
                                  email = insti.EmailId,
                                  zipcode = insti.Zipcode,
                                  country = insti.Country,
                                  state = insti.State,
                                  city = insti.City,
                                  start = insti.EstablishOn,
                                  image = insti.ProfilePhoto,
                                  fees = course.TotalFees,
                                  mode = course.Mode,
                                  coursename = coursemaster.CourseName,
                                  duaration = coursemaster.duration,
                                  discription = coursemaster.Discription,
                                  eligibility = coursemaster.Eligibility,
                                  recognization = coursemaster.Recognization,
                                  facility  = masterfacility.FacilityName


                              }).Distinct();

--> I Am Using AngularJs To display a data --> And my Record Is repeating for particular facility

this is my tables This is a problem that display same record again for his facility

Can Any One Help Me in this

Dynamic Model in MVC 4.0

Our Application is developed using MVC 4.0. We have a MVC view that's is attached to Dynamic Model.(@model dynamic)

When we submit the view , the dynamic model is posted as an object to Submit Action. Inside Submit Action, we are trying to capture this dynamic model and cast to a typed model. But it's not working, we tried all suggestions provided online but still no luck.

MVC View --> Attached to dynamic model (@model dynamic) On Submit click ---> Call Submit Action Result Method Submit Action Result ---> Catch the posted dynamic model and cast it to typed model. Let's say we have a typed model call product.cs. All we need to do is cast the posted dynamic model to product.cs in the submit action result!!!

jeudi 6 octobre 2016

string concatenation in aspx view engine using local variable. Not Razor mvc views

How can I string concatenate in ASPX view engine? I want to use my variable in generating ids dynamically(in below example, allow ability to add multiple education details).I want to replace (<%=CurrentEducation%>) with id count. I can easily do this in Razor but not in aspx views. Can you also point me the syntax declarations for <% %> things in aspx view engine please? I can find examples only in razor examples.

 <% dim currentEducation = 1 %>
                                <% for each item As EducationDetailsViewModel in Model.EducationDetails %>
                                <div class="row">
                                    <div class="col-md-11">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <%= Html.LabelFor(Function(x) item.Educationlevel, New With {.class = "control-label" + "test", .id="EducationDetails_(<%=CurrentEducation%>)_EducationLevel"})%><span class="text-danger">*</span>

                                                <%= Html.TextBoxFor(Function(x) item.Educationlevel,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-4">
                                                <%= Html.LabelFor(Function(x) item.SchoolName, New With {.class = "control-label"})%><span class="text-danger">*</span>
                                                <%= Html.TextBoxFor(Function(x) item.SchoolName,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-3">
                                                <%= Html.LabelFor(Function(x) item.YearsAttended, New With {.class = "control-label"})%>
                                                <%= Html.TextBoxFor(Function(x) item.YearsAttended,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-2">
                                                <%= Html.LabelFor(Function(x) item.IsGraduated, New With {.class = "control-label"})%>
                                                <%= Html.RadioButtonFor(Function(x) item.isGraduated, False, new with {.style="width:auto"})%>No:
                                            <%= Html.RadioButtonFor(Function(x) item.isGraduated, True, new with {.style="width:auto"})%>Yes:
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <%= Html.LabelFor(Function(x) item.AreaOfStudy, New With {.class = "control-label"})%>
                                                <div class="">
                                                    <%= Html.TextBoxFor(Function(x) item.AreaOfStudy,New With{.class="form-control"})%>
                                                </div>
                                            </div>
                                        </div>
                                        <br />
                                    </div>
                                    <div class="col-md-1">
                                        <span class="text-danger">X</span>
                                    </div>
                                </div>
                                <% currentEducation = currentEducation + 1 %>
                                <% next %>

mardi 4 octobre 2016

How to get the value of Hiddenfield Gridview in OnUpdate function?

My database is connected with the Gridview. I am using hidden field to get the unique element of the table for update query. After editing a row, when I want to execute the update query, I cant access the unique element of the table which in result will update the whole database table with same records. Kindly resolve!

lundi 3 octobre 2016

why my app has stopped working in asus phone with intel processor?

My app running in arm processor but it can't run in intel processor, I have built my app in android studio.

how to display the comments under the post

I Have problem in my project i'm new in MVC so plz help me out. I have problem to display the comments under the relevant the Post like we have post in face book and we comment just under the post and it display, I Have displayed and listed all the posts and under this i have displayed the comments field, i just want to know how the relevant comment can be displayed, View

    @foreach (Post item in Model.posts)
{
    foreach(Comment c in Model.comments)
    {
<div>

    <p>
        @item.Body
    </p>
    <p>@item.timeDate</p>
    <p>@c.Body</p>

</div>   
    using (Html.BeginForm("CreateComment", "Posts", FormMethod.Post))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Comment</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Name)
            @Html.ValidationMessageFor(model => model.comment.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Email)
            @Html.ValidationMessageFor(model => model.comment.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Body)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Body)
            @Html.ValidationMessageFor(model => model.comment.Body)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.dateTime)
        </div>
        <div class="editor-field">
           @Html.TextBoxFor(model => model.comment.dateTime, new { id = "datepicker", @Value = @DateTime.Now })
           @Html.ValidationMessageFor(model => model.post.timeDate)
        </div>       
        <div class="editor-field">
           <input type ="text" hidden="hidden" value="@item.Id" name="txtpostId"/>
            @Html.ValidationMessageFor(model => model.comment.PostId)
        </div>

        <p>
            <input type="submit" value="Create"/>
        </p>
    </fieldset>
    }
  }
}

Controller

 public ActionResult Index()
    {
        objVmPost.comment = new Comment();
        objVmPost.post = new Post();
        List<Post> mylist = db.Posts.ToList();
        objVmPost.posts = mylist;
        List<Comment> cmntlist = db.Comments.ToList();
        objVmPost.comments = cmntlist;
        return View("Index",objVmPost);
    }
 [HttpPost]
    public ActionResult CreateComment(VmPost objVmpost)
    {
        objVmpost.comment.PostId = Convert.ToInt32(Request.Form["txtpostId"]);
        db.Comments.Add(objVmpost.comment);
        db.SaveChanges();
        List<Post> mylist = objPostDb.GetAll().ToList();
        objVmpost.posts = mylist;
        return View("index", objVmpost);
    }

Model

public partial class Comment
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Body { get; set; }
    public System.DateTime dateTime { get; set; }
    public int PostId { get; set; }

    public virtual Post Post { get; set; }
}

public partial class Post
    {
        public Post()
        {
            this.Comments = new HashSet<Comment>();
            this.Tags = new HashSet<Tag>();
        }

        public int Id { get; set; }
        public System.DateTime timeDate { get; set; }
        public string Body { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
    }