dimanche 31 janvier 2016

Entity Framework 5 disable object mocking

My apologies in advance that I am not an EF export. My team have inherited a MVC3 project using EF5 on .NET 4.0. There are a lot of mock objects automatically generated by TT(?) template. We have multiple developers working on the project and constantly causing conflicting errors on the mock objects and we wonder if it is possible to tweak EDMX NOT to generate the mock objects? We tried to delete the test files but they seem to get generated every time we updates the EDMX.
We know that it's a good practice to automate the unit testing but we are running out of time and the budget would not allow us to spend too much time automating unit tests. Thanks in advance.

vendredi 29 janvier 2016

MVC validation only border highlight without text error message

Hello I would like to only highlight the border of the text box without any error message near it, I have tried the following

    [Required(ErrorMessage = "")]
    [Display(Name = "Email")]
    public string Email { get; set; }

Before 1

After 2

filter DropDownList with viewbag in mvc3

I have two tables: Persons and Activities. First I create the persons. When I want to create an activity for that person, I have a DropDownList from which I choose the persons. What I want is to filter the DropDownList so that if a person is already linked to an activity, I don't want her to appear in the DropDownList. In the Activities table I have a column Called STATUS and I want to filter by this column. Here is what I have in Controller:

ViewBag.SelectListPers = new SelectList
(
from c in p.ToList()
where dbContext.Activities.Any(k=>k.STATUS=='0')
select new 
{
ID_PERS=c.ID_PERS,
FullName=c.FirstName+""+c.Surname
},"ID_PERS", "FulName"
);

And in View:

<%: Html.DropDownListFor(model=>model.ID_PERS,ViewBag.SelectListPers as SelectList, "Select a person")%>

This is not working. Could you help me?

jeudi 28 janvier 2016

submitting a form works in some instances, but returns error 403 in other instances

I have an mvc3 application which makes use of an ajaxsubmit to a controller action. The <form> opening tag in my page appears like this:

<form action="/application/home/Save?Length=0" class="form-horizontal" data ajax="true" data-ajax-method="POST" data-ajax-mode="after" data-ajax update="#jsonResult" enctype="multipart/form-data" id="inputForm" method="post" role="form">

If i submit this form from within the network that the server is based, the post request will always work. But if i submit the form externally, on occasions i get this generic error:

403 Forbidden: You don't have permission to access /application/home/Save on this server.

The above error doesnt always occur. only in particular instances.

Upon analysing the request headers, The only difference i see is Content-length:

They have the following:enter image description here

The only other difference that i think could be the cause of this issue is in one of the fields in the request payload.

Now one of the fields i pass to the server is in a special code that has tilders and carrot symbols. Here is an example:

------WebKitFormBoundaryvvviIpe8b82tAvOd
Content-Disposition: form-data; name="udfArray"

["1~d^testfield~d^R"]

Whenever the form submit fails, it happens to have the above form data. When it succeeds, the field is set to []

The trouble is, i dont understand why having the code set to ["1~d^testfield~d^R"] should be an issue if it works within the network.

If anyone could point me in the right direction for making this work externally that would be great.

Here is my submit code:

      //options for submit action
        var options = {
            data: {
                udfArray: ko.toJSON(self.TempArray()),
                title: self.title(),
                given_name: self.givenName(),
                //... other fields
            },
            uploadProgress: function () {
            },
            dataType: "json",
            success: function (result) {
              //do something
            }
        };

        $('#inputForm').ajaxForm();
        $('#inputForm').unbind('submit').submit(function () {

            $('#loadingDiv').show();
            $(this).ajaxSubmit(options);
            return false;
        });

Could not load file or assembly 'Microsoft.Xrm.Sdk, The located assembly's manifest definition does not match the assembly reference

I am getting an issue when i call a action method on that Action Method i am getting contact details through CRM, on that time i am getting this issue " Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

My Action Methods: public ActionResult Contact() {

        Xrm.XrmServiceContext xrm = new XrmServiceContext(CrmService.Service);
        IQueryable<Contact> contacts = xrm.ContactSet;
        List<ContactModel> model = new List<ContactModel>();
        model.Add(new ContactModel { FirstName = "prathyu", LastName = "Reddy", Email = "p@gmail.com", Phone = "123457896" });
        model.Add(new ContactModel { FirstName = "siva", LastName = "Reddy", Email = "p@gmail.com", Phone = "123457896" });
        model.Add(new ContactModel { FirstName = "prathyusha", LastName = "Reddy", Email = "s@gmail.com", Phone = "123457896" });
        model.Add(new ContactModel { FirstName = "mallu", LastName = "dinesh", Email = "s@gmail.com", Phone = "123457896" });
        model.Add(new ContactModel { FirstName = "priya", LastName = "Reddy", Email = "acfyh@gmail.com", Phone = "123457896" });

        ViewBag.Contacts = contacts;



        return View(contacts);
    }
    public ActionResult GetContacts([DataSourceRequest]DataSourceRequest request)
    {
        Xrm.XrmServiceContext xrm = new XrmServiceContext(CrmService.Service);
        IQueryable<Contact> contacts = xrm.ContactSet;
        DataSourceResult result = contacts.ToDataSourceResult(request);
        return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
    }

Please any one clarify my dought Thanks in Advance

mercredi 27 janvier 2016

Implementing reCaptcha into MVC3 failed because connected host failed to respond

Been attempting to implement reCaptcha into a contact form, which seems to work fine when hosted locally, but when uploaded it gives this error;

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.58.199.68:443

    [SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.58.199.68:443]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +208
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +464

The error happens after I submit the contact form, so possibly an issue with the verification to google?

This is the code i'm just testing with at the moment. When hosted through Visual Studio I get an error because the SMTP server i'm using doesnt exist since it's not being hosted.

But when it's Hosted live, it receives the above error.

Controller - 

[HttpPost]
        [ActionName("ContactUs")]
        public ActionResult validate(string name, string company, string phone, string email, string subject, string body, bool? remember)
        {
            var r = Request.Params["g-recaptcha-response"];
            using (var wc = new WebClient())
            {
                var validateString = string.Format(
                    "http://ift.tt/1xSi4Qj}",
                   "MY_KEY_USUALLY_GOES_HERE",    // secret recaptcha key
                   r); // recaptcha value
                // Get result of recaptcha
                var recaptcha_result = wc.DownloadString(validateString);
                // Just check if request make by user or bot
                if (recaptcha_result.ToLower().Contains("false"))
                {
                    return RedirectToAction("ContactFailed");
                }

                else
                {
                    Do stuff to send the contact message
                }
            }

My first guess would be that it's an issue with my Web Hosts blocking the connection but I'm pretty stumped.

Thanks

make an MVC 3 application compatible with IE11

I have an ASP.NetMVC3 appliaction with VS2010 in .Net Framework 4.0, its working fine in IE8 version, but Its not working in IE11 version, Browser compatibility, please kindly help me on this, if it is possible pls provide me the solution steps what we need to do or else if it is not possible let me know

How to change the URL of @Html.BeginForm

there some tab have its own form,the form1 in tab-1 looks like code below, the url will be like http://localhost/view/Display?Airline=CA when I click any tab for searching, so I want to change the URL when I click the button for example in tabs-2, so the URL should be http://localhost/view/Display?Airline=CA#tabs-2, then it could back to tab 2, so how can I change the URL? Thanks!

@using (@Html.BeginForm("Display", "Manual", FormMethod.Get, new { id = "searchForm1", enctype = "multipart/form-data" }))
{                                
    <span><b>Airline:</b></span>
    @Html.TextBox("Airline", Model.Airline??"", new { @class = "public_input1", style = "width: 60px;" })    
}

<input class="btnSubmit" id="searchNote1" type="button" value="search" />

$("#searchNote" + index).click(function () {
    var searchFormElement = "#searchForm" + index;
    $(searchFormElement).attr("action", "/View/Display");
    $(searchFormElement).submit();
    return true;
});

mardi 26 janvier 2016

Cooki Valua and ExpireDate are wrong - MVC

I have a ASP.NET MVC 5 project. I have two languages in my project, to set language I use the code below:

BaseController

  protected override void ExecuteCore()
    {
        HttpCookie cookie;
        if (RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
        {
            var lang = RouteData.Values["lang"].ToString();
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        }
        else
        {
            cookie = HttpContext.Request.Cookies["imen.lang"];
            string langHeader;
            if (cookie != null)
            {
                langHeader = cookie.Value;
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
            }
            else
            {
                langHeader = "fa-IR";
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
            }

            RouteData.Values["lang"] = langHeader;
        }

        cookie = new HttpCookie("imen.lang", Thread.CurrentThread.CurrentUICulture.Name) { Expires = DateTime.Now.AddYears(1) };
        if (HttpContext.Response.RedirectLocation == null)
            HttpContext.Response.SetCookie(cookie);
        base.ExecuteCore();
    }

It works fine, but I cache a methods by lang and User below code in Global.asax like this :

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if ("lang".Equals(custom))
        {
            var cookie = HttpContext.Current.Request.Cookies["imen.lang"];
            var culture = cookie != null
                              ? CultureInfo.CreateSpecificCulture(cookie.Value).Name
                              : Guid.NewGuid().ToString();  
            return culture;

        }
        return base.GetVaryByCustomString(context, custom);
    }

Problems :

1- when Read Cooki in GetVaryByCustomString in Global ExpireDate is 01/01/0001 12:00:00 AM

2- when change Language , firstTime Cooki value is not same to current Language and it equals to Previour Language.

whats Problem ?

Sorting is not working in mvc MVCGrid.net

I'm using MVCGrid.net grid to show data from my data base. The problem is that sort option is not working Here is my MVCGrid code

       IEnumerable<State> st = null;
        MVCGridDefinitionTable.Add("StateGrid", new MVCGridBuilder<State>()
            .WithAuthorizationType(AuthorizationType.AllowAnonymous)
            .AddColumns(cols =>
            {
                cols.Add("StateCode").WithSorting(false)
                            .WithValueExpression(p => p.StateCode);
                cols.Add("StateName").WithHeaderText("State Name")
                    .WithValueExpression(p => p.StateName);                    
            })
            .WithSorting(true, "StateName")

Returning a sitecore item with populated model from controller action

I have a controller rendering on my homepage which is a search box.

My controller action looks like this

public ActionResult Search(SearchResultModel model)
    {
        //TODO bind to model to form
        SearchModel resultModel = new SearchModel
        {
            Keyword = Request.Form["keyword"]
        };
        var results = new List<SearchResultModel>();
        results = FoundResults(resultModel.Keyword);
        resultModel.SearchResults = results;

        return View(resultModel);
   }

What is it I want? I want to fill in a keyword in the input box have it processed ( and posted ) and return a page ( item ) in sitecore with my model. Something like return item and give it my model.

Question. Is this possible ?

If not? What would be the best way to tackle this issue?

I need some help here folks :).

I have already read :

http://ift.tt/1KC94jN

and other articles from Martina but I seem to not be getting anywhere closer.

CRUD operation using Umbraco MVC

can anyone have idea about how to develop CRUD using UmbracoCms with MVC 3?

Thanks in advance.

lundi 25 janvier 2016

In MvC when Enable role manager what is the provider Name?

I have error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

cross domain issues prevent action when reload parent page

its me...

i was wondering if you could help me with this issue on cross domain thing. i'm trying to reload the parent page from another domain. i achieved the reload on parent page when closing the child, but once i reload, the action on "onclick" event triggers again. my questions is how can i prevent window.open once it reloads?

see my code:

// here ive tried to put return false but it fails to prevent the popup

 <asp:HyperLink ID="HyperLink1" runat="server"  onclick="return myopen('http://ift.tt/20or9uJ', 'VieworUploadDocs','toolbar=no,location=no,directories=no,status=no,menubar=no,position=center,width=700px,height=850px');return false;" Text="Click Here" />

this is my script:

<script type="text/javascript">

         //open window
         var myWindow = null;
         var myTimer = null;

         myopen = function (url) {
             myWindow = open(url, 'VieworUploadDocs', 'toolbar=no,location=no,directories=no,status=no,menubar=no,position=center,width=700px,height=850px');
             myTimer = setInterval(function (e) {
                 if (myWindow == null || myWindow.closed) {

                     alert('Please wait while page loads.');
                     location.reload();
                     clearInterval(myTimer);
                     e.stopPropagation();
                 }
             }, 5000);
         }
         </script>

i tried to put this on my code

return false;
e.preventDefault();
e.stopPropagation();

thanks in advance hope anyone could help me. have a good day! struggle is real.

How to Send Mail Without using Password

I want to sent mail without using password of the mailid,Currently i use this code to sent mail.....i hardcode the mail id and pwd

i want to pass the frommail and tomail as parameter, and i dont want a password to send a mail

        System.Net.NetworkCredential cred = new System.Net.NetworkCredential("demo@outlook.com", "demo1234");
        SmtpClient smtp = new SmtpClient("smtp-mail.outlook.com", 587);
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = cred;
        smtp.Send(message);

Please Help Me

samedi 23 janvier 2016

MVC HTML Text Showing

I have HTML text inside database which I have saved using HTML TextBox Now I want to show html text on my page which is also I am doing using @Html.Raw

but actually I want to show only 100 characters of HTML text on razor page.

How it is possible please help

vendredi 22 janvier 2016

caching frameworks for .net 4.5.1 [.net core (dnx)]

We are trying to build an application in asp.net 5 which is built on .net core. What are the in-memory caching options available to us. We tried creating a POC using Redis (open source caching server), but it was unsuccessful as we could not get it to work with .net core. What are the different options we can consider? We want the application to be platform independent and hence we have selected asp.net 5. My question may seem noobish ;) but even we have not invested sufficient time in understanding the new asp.net 5 due to a very strict deadline. Any suggestion would be welcome.

jeudi 21 janvier 2016

edit user profile image with usermanager

I'm following this tutorial to add profile picture once account create.

that edit has following snippet,

Student student = db.Students.Include(s => s.Files).SingleOrDefault(s => s.ID == id);

In above example it applied to table call Student in my case I want to go with AspNetUser table , but then I have to go with UserManger feature , Once I try to Include a file then it popping that error in compile time.

But in my scenario I'm trying to include in AspNetUser or UserManager

So to populate uploaded picture. I need include following code in user manager

var user = await UserManager.Include(s => s.Files).FindByIdAsync(userid);

but then getting following error

'ApplicationUserManager' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'ApplicationUserManager'

How to ignore and include files

EDIT:

These are the changes I've done in Model classes

File

public class File
{
    public int FileId { get; set; }
    ..

    public virtual ApplicationUser UserManager { get; set; }
}

FilePath

    public class FilePath
{
    public int FilePathId { get; set; }
    ..

    public virtual ApplicationUser UserManager { get; set; }
}

ApplicationUser

public class ApplicationUser : IdentityUser
{
        ....

        public virtual ICollection<File> Files { get; set; }
        public virtual ICollection<FilePath> FilePaths { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
       ....
    }
}

AspNetUser

public partial class AspNetUser
{

    public AspNetUser()
    {
       ..
    }
    ....

    public virtual ICollection<File> Files { get; set; }
    public virtual ICollection<FilePath> FilePaths { get; set; }
}

then try to add migration to the project by typing the following into the PMC:

add-migration File

add-migration FilePaths

then getting following error in console

No migrations configuration type was found in the assembly 'Project_Name'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

Asp.net MVC Authorize Attribute not working Anonymous users can see contents

I have the following code for a simple asp.net mvc authentication

[ExcludeFromCodeCoverage]
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
            });
        }
    }

global.asax app start

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Ejecuta la inicializacion de la base de datos
            Database.SetInitializer<ComisionesContext>(new ComisionesInitializer());
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

             UnityConfig.RegisterComponents();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
        }

unityconfig

[ExcludeFromCodeCoverage]
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType<IAccount, Account>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }

Then, our view which should be protected from anonymous users.

 @model List<xx.Models.TipoDeCanal>
@using PowerData.Comisiones.Models
@{
    ViewBag.Title = "Tipos de Canal";
}

<h2>Tipos de Canal</h2>

@(Html.Kendo().Grid<TipoDeCanal>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Descripcion).Title("Descripcion");
        columns.Command(command => { command.Edit(); command.Destroy(); });
    })
    .ToolBar(toolbar => toolbar.Create())   
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()  
    .DataSource(dataSource => dataSource
        .WebApi()
        //.Ajax()
        //.ServerOperation(false)
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.ID);
            model.Field(p => p.ID).Editable(false);
        })
        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales" }))) // Action invoked when the user saves a new data item
            .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales" }))) // Action invoked when the grid needs data
            .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales", id = "{0}" })))  // Action invoked when the user saves an updated data item
            .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales", id = "{0}" }))) // Action invoked when the user removes a data item

        //.Create(update => update.Action("Create", "TipoDeCanales"))
        //.Read(read => read.Action("Read", "TipoDeCanales"))
        //.Update(update => update.Action("Edit", "TipoDeCanales"))
        //.Destroy(update => update.Action("Delete", "TipoDeCanales"))
    )
)
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            toastr.error(message)
            //alert(message);
        }
    }
</script>

the main controller with the authorize attribute\

 [Authorize]
    public class TipoDeCanalesController : GenericController
    {
        public System.Web.Mvc.ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }

and the api controller also have the authorize attribute

[System.Web.Mvc.Authorize]
    public class TipoDeCanalesController : GenericApiController
    {
        private UnitOfWork unitOfWork = new UnitOfWork();

        // GET api/TipoDeCanal/5
        public TipoDeCanal GetTipoDeCanal(int id)
        {
            TipoDeCanal tipoDeCanal = unitOfWork.TipoDeCanalRepository.GetByID(id);
            if (tipoDeCanal == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return tipoDeCanal;
        }

        // GET api/TiposDeCanal
        public DataSourceResult GetTiposDeCanal([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
        {
            TipoDeCanal[] tiposDeCanal = unitOfWork.TipoDeCanalRepository.Get().ToArray();
            DataSourceResult result = tiposDeCanal.ToDataSourceResult(request);
            return result;
        }

        // PUT api/TipoDeCanal/            edit
        public HttpResponseMessage PutTipoDeCanal(int id, TipoDeCanal tipoDeCanal)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != tipoDeCanal.ID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            try
            {
                unitOfWork.TipoDeCanalRepository.Update(tipoDeCanal);
                unitOfWork.Save();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/TiposDeCanal   add
        public HttpResponseMessage PostTipoDeCanal(TipoDeCanal tipoDeCanal)
        {
            if (ModelState.IsValid)
            {
                unitOfWork.TipoDeCanalRepository.Insert(tipoDeCanal);
                unitOfWork.Save();

                DataSourceResult result = new DataSourceResult
                {
                    Data = new[] { tipoDeCanal },
                    Total = 1
                };
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, result);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new {Controller="TipoDeCanalesController", id = tipoDeCanal.ID}));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // DELETE api/TipoDeCanal/5
        public HttpResponseMessage DeleteTipoDeCanal(int id)
            {
            TipoDeCanal tipoDeCanal= unitOfWork.TipoDeCanalRepository.GetByID(id);
            if (tipoDeCanal == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            unitOfWork.TipoDeCanalRepository.Delete(tipoDeCanal.ID);           

            try
            {
                unitOfWork.Save();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, tipoDeCanal);
        }   

        protected override void Dispose(bool disposing)
        {
            unitOfWork.Dispose();
            base.Dispose(disposing);
        }
    }

However, as an anonymous user when I go to htttp://localhost/TiposDeCanales

which executes the Index action of that controller, the user can still see the contents of the page and the records in the database.

ModelState.isvalid is false when trying to save an entity, error says a field is required in a related entity

I have this code to save an entity

 public class TipoDeProducto
    {
        [Key]
        [ScaffoldColumn(false)]
        public int TipoDeProductoId{ get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "El nombre debe tener como máximo 50 caractéres")]
        public string Nombre { get; set; }

        [Required]
        public bool Estado { get; set; }

        public virtual ICollection<Producto> Productos { get; set; }
    }

and Product

 public class Producto
    {
        [Key]
        [ScaffoldColumn(false)]
        public int ProductoId { get; set; }

        public int TipoDeProductoId { get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "El nombre debe tener como máximo 50 caractéres")]
        public string NombreProducto { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        [MaxLength(300, ErrorMessage = "La descripción debe tener como máximo 300 caractéres")]
        public string Descripcion { get; set; }

        public bool Estado { get; set; }


        [ForeignKey("TipoDeProductoId")]
        public virtual TipoDeProducto TipoDeProducto { get; set; }
    }

The edit (POST) is this:

  public HttpResponseMessage PutTipoDeProducto(int id, TipoDeProducto tipoDeProducto)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != tipoDeProducto.TipoDeProductoId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            try
            {
                unitOfWork.TipoDeProductoRepository.Update(tipoDeProducto);
                unitOfWork.Save();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

My index view is like this:

@model List<PowerData.Comisiones.Models.TipoDeProducto>
    @using PowerData.Comisiones.Models
    @{
        ViewBag.Title = "Tipos de producto";
    }

    <h2>Tipos de producto</h2>

    @(Html.Kendo().Grid<TipoDeProducto>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Estado).Title("Estado");
        columns.Command(command => { command.Edit(); });
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.PopUp))

    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()
    .DataSource(dataSource => dataSource
        .WebApi()
        //.Ajax()
        //.ServerOperation(false)
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.TipoDeProductoId);
            model.Field(p => p.TipoDeProductoId).Editable(false);
        })

        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos" }))) // Action invoked when the user saves a new data item
                    .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos" }))) // Action invoked when the grid needs data
                    .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos", id = "{0}" })))  // Action invoked when the user saves an updated data item
                    .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeProductos", id = "{0}" }))) // Action invoked when the user removes a data item

        //.Create(update => update.Action("Create", "TipoDeCanales"))
            //.Read(read => read.Action("Read", "TipoDeCanales"))
            //.Update(update => update.Action("Edit", "TipoDeCanales"))
            //.Destroy(update => update.Action("Delete", "TipoDeCanales"))
    )
    )
    <script type="text/javascript">
        function error_handler(e) {
            if (e.errors) {
                var message = "Errors:\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function () {
                            message += this + "\n";
                        });
                    }
                });
                toastr.error(message)
                //alert(message);
            }
        }
    </script>

However, after I add items, and then try to edit an existing row, the Model.Isvalid = false, and when I check the validation errors, it says ProductName is required, which is not even a field on the table I am trying to save, its a related list of entitties

What are needed in the computer server for deploying ASP.NET web application?

Hi I'm kinda new in building web application using ASP.NET MVC, and I'm planning on deploying my application on the server. And my question is what things are needed to be installed in the server so that my ASP.NET web app can run?

I've listed some few things:

  1. ASP.NET Framework 4
  2. SQL Server 2008
  3. IIS as web server
  4. ASP.NET MVC 3
  5. ASP.NET Web Pages

Any other things I need to install in my server? And the app that I'm building is a multi user app (around 100 users), what is the recommended specification for the server?

Thanks for your response!

ASP.NET MVC How to display Image from folder outside webroot

Individual Folder create for each user when they register on website outside the webroot folder.I am able to upload the image and store Image path in database.However,I am unable to display the Image. I am trying to get the path of Image from database using LINQ and display in VIEW but it does not work. I can view only one(from the list of Image)Image when FILESTREAM the image path and retrun using FILESTREAMRESULT

Can anyone please guide me how to achieve it? All I want to do is create folder for each respective user when they register in external folder. Upload Image and display.

mercredi 20 janvier 2016

how to print the data of my html table without database or data set?

I have a situation here that I want to print the data in my html table to any printable app or program without using database or dataset. For the reason that I want to customized it on my own.

so, this is the table that I want to print.

enter image description here

I hope it is posible in mvc c#.

Performance Issue While Fecthing the Record and Displaying in Grid?

Actually i am fetching the records from two table One is VehicleDetails and other one is Barcodedetails. 1)Vehicle Details Contains 10,000 records and Barcode Details Contains 11Lakhs records and Each vehicle is Mapped to a specific Bardcode.

currently what iam doing is first iam getting all the BarcodeDetails from BarcodeDetailsTable and its take 8sec's to complete it,

   List<VTSBarCodeDetail> barCodeDetailMaster = barCodeDetailRepository.Get(null, null) as List<VTSBarCodeDetail>;

then i will get the Vehicle Details

 List<VTSVehicleRegistrationObject> vehicleRegObject = (Some  Simple query to get the VehicleRegobject)

and then i am running a for loop in this for loop iam adding barcodeno passtype etc details to a list. this for loop is taking 1 min of time to complete it for 6k records. here is my code and log file have a look at this.

  foreach (VTSVehicleRegistrationObject item in vehicleRegObject)
        {
  barCodeDetails = barCodeDetailMaster.Where(x => x.VehicleId == Convert.ToInt32(item.VehicleId) && x.BarCodeId == item.BarCodeId).FirstOrDefault();
 { 
 //some Logic add item to this list.
  }

Changing the home page is not working

In my project the initial route config was like below

 public static void RegisterRoutes(RouteCollection routes)
  {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   routes.MapRoute(
   name: "Default",
  url: "{controller}/{action}/{id}",
 defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
            );
        }

Now I changed to

 public static void RegisterRoutes(RouteCollection routes)
  {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   routes.MapRoute(
   name: "Default",
  url: "{controller}/{action}/{id}",
 defaults: new { controller = "Pro123", action = "Index", id = UrlParameter.Optional }
            );
        }

Then I rebuild the solution and run it again @ local system. Still it is going to Login view of the Home controller. Am I missing anything?

mardi 19 janvier 2016

C# MVC4 Chart Changing Series Color

I am trying to change series colors when I add them. Currently, MVC4's chart seems to default to Blue, Yellow, then Red. I am trying to change it to default to Red, Yellow, then Green. I have several graphs where I add more and more series and I want it to follow that pattern. Does anyone know how to change the line colors? I tried color: "Red", for instance in a series and it errored.

var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Blue)
.AddTitle("Line Graph")
.AddSeries(
  name: "Current",
  chartType: "Line",
  xValue: new[] { @test.ReportDate[1], @test.ReportDate[2], @test.ReportDate[3], @test.ReportDate[4], @test.ReportDate[5], @test.ReportDate[6] },
  yValues: new[] { @test.typea[1], @test.typea[2], @test.typea[3], @test.typea[4], @test.typea[5], @test.typea[6] }
)
.AddSeries(
  name: "New",
  chartType: "Line",
  xValue: new[] { @test.ReportDate[1], @test.ReportDate[2], @test.ReportDate[2], @test.ReportDate[4], @test.ReportDate[5], @test.ReportDate[6] },
  yValues: new[] { @test.typeb[1], @test.typeb[2], @test.typeb[3], @test.typeb[4], @test.typeb[5], @test.typeb[6] }
)
.AddSeries(
  name: "Orignal",
  chartType: "Line",
  xValue: new[] { @test.ReportDate[1], @test.ReportDate[2], @test.ReportDate[3], @test.ReportDate[4], @test.ReportDate[5], @test.ReportDate[6] },
  yValues: new[] { @test.typec[1], @test.typec[2], @test.typec[3], @test.typec[4], @test.typec[5], @test.typec[6] }
)
.AddLegend()
.Save(path: @Server.MapPath("~/chart/chart.png"));


// Chart Theme Blue
public const string Blue = "<Chart BackColor=\"#D3DFF0\" BackGradientStyle=\"TopBottom\" BackSecondaryColor=\"White\" BorderColor=\"26, 59, 105\" BorderlineDashStyle=\"Solid\" BorderWidth=\"2\" Palette=\"BrightPastel\">\r\n    <ChartAreas>\r\n        <ChartArea Name=\"Default\" _Template_=\"All\" BackColor=\"64, 165, 191, 228\" BackGradientStyle=\"TopBottom\" BackSecondaryColor=\"White\" BorderColor=\"64, 64, 64, 64\" BorderDashStyle=\"Solid\" ShadowColor=\"Transparent\" /> \r\n    </ChartAreas>\r\n    <Legends>\r\n        <Legend _Template_=\"All\" BackColor=\"Transparent\" Font=\"Trebuchet MS, 8.25pt, style=Bold\" IsTextAutoFit=\"False\" /> \r\n    </Legends>\r\n    <BorderSkin SkinStyle=\"Emboss\" /> \r\n  </Chart>";

MVC 3 to MVC 5 project issue

I do not use on a daily basis MVC and I have a strange error.

System.Data.SqlClient.SqlException: Invalid column name 'ytworkspace_sharesOption_enum'.

Invalid column name 'ytworkspace_optimisationObjective_enum'.

except that

Public Enum_ShareTypes.Enums ytworkspace_sharesOption_enum 
{
get {return Enum_ShareTypes.getEnum (ytworkspace_sharesOption); }
set {this.ytworkspace_sharesOption = Enum_ShareTypes.getNumber (value); }
}

Public Enum_OptimisationObjective.EnumO ytworkspace_optimisationObjective_enum       
{
get {return Enum_OptimisationObjective.getEnum (ytworkspace_optimisationObjective); }
set {this.ytworkspace_optimisationObjective = Enum_OptimisationObjective.getNumber (value); }
}

                                           

Previously, it was the MVC version 3.0.0 and it worked but after moving the new version 5.0.0 MVC stopped working. I had to change the variable names because they clung to Enum types. Thanks for the help

Daniel

How to render images as a video without html5 (web application)

I have the following scenario: I have a camera that have a function to send me photo when I ask it for.(this is the only way I can work with this camera)

I keep application in a loop:

 $(function () {
        setInterval(function () {    
            var link = '@Url.Content("~/Home/Hello")';    
            var txt = Math.random();    
            link += '?';
            link += 'text=' + txt;

            document.getElementById('imgDiv').innerHTML = '<img src="' + link + '" alt="' + txt + '" />';    
        }, 200);    
    });

This doen't work, it's slow, work only in LAN, but I have a WCF that returns this image as a stream so I return it to client like this:

public ActionResult Hello(string text)
        {
            //Create new image
            Image img = new Bitmap(500, 500);
            Graphics g = Graphics.FromImage(img);

            //Do some drawing
            Font font = new Font("Arial", 24);
            PointF drawingPoint = new PointF(10, 10);

            g.DrawString(text, font, Brushes.Black, drawingPoint);

            //Return Image
            MemoryStream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Png);

            ms.Position = 0;

            return new FileStreamResult(ms, "image/png");
        }

I have digged for some solution and then I realize that I'm doing this in a completely wrong way.

I don't have to call images from server, it should send me, like sockets do.

Another part of solution is to create a buffer of pictures (not showing 1 by 1), and then transform the buffer into a video and show it while store more pictures parallely

But to do this I have to use html5, and my server does not suport it, I am working in windows server 2008.

So my quetion is:

Is this the way I should do this, if not, could you guys provide some other solutions.

Ps: I can't use html5

MVC application not logging in when binded on subdomain

I have my application in Asp.net MVC3, i have published my application on VPS. My application has some pages that are open and do not need admin login, but there are some other functional areas in the application that needs the admin login. The issue im getting is while creating the binding on IIS when i bind the application on local port like 8015,8016 etc. the application runs fine and gets logged In, but when i change the binding of the application to a certain subdomain then the application is executed but do not login with the same credential.

My efforts : Have checked the web.config there are no filters added that stops subdomain to login

Have checked the setting in the IIS for this application and nothing of the sort is identified.

Let me know what i can do to solve the issue

lundi 18 janvier 2016

How to display string from action result

there is a action: /Home/GetName, and return a string "Mike", the controller and action like:

public class HomeController : Controller
{
    public string GetName()
    {
        return "Mike";
    }
}

how can I display this action result in view? (without ajax is better)

How to bind Data to the Template/View in Umbraco MVC

I am using Umbraco 6.2.1 with MVC3 and I Created one Document Type as Index and also template by the same name and My Umbraco Structure is as follows: Here I am trying to Render the View(CNOReplacement)and binding the Model data to the View on the submission on Index View. My Code is as follows:

@using Umbraco_POCTest.Controllers;
@using Umbraco_POCTest.Models;
@using Umbraco.Web;
@inherits Umbraco.Web.Mvc.UmbracoViewPage<MasterViewModel>
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@using (Html.BeginUmbracoForm<CNOPOCController>("CNOReplacementSubmit"))
    {
<div class="form-group col-md-6">
     <label class="control-label"> Phone</label>
     <input type="text" name="Phone"  id="Phone" class = "form-control" placeholder = "Phone" style="width:100px;" />
</div>
<div class="form-group  col-md-6">
     <label class="control-label">Email</label>
     <input type="text" name="Email" id="Email" class = "form-control" placeholder = "Email" style="width:100px;" />
 </div>
}

and My CNOReplacement View is as follows:

@using Umbraco_POCTest.Controllers;
@using Umbraco_POCTest.Models;
@using Umbraco.Web;
@inherits Umbraco.Web.Mvc.UmbracoViewPage<MasterViewModel>
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = "Master.cshtml";
}
 @using (Html.BeginUmbracoForm<CNOPOCController>("CNOBeneficiary"))
 {
<div class="form-group col-md-6">
         <label class="control-label"> Phone</label>
         <input type="text" name="Phone"  id="Phone" class = "form-control" placeholder = "Phone" style="width:100px;" />
    </div>
    <div class="form-group  col-md-6">
         <label class="control-label">Email</label>
         <input type="text" name="Email" id="Email" class = "form-control" placeholder = "Email" style="width:100px;" />
     </div>
    }

enter image description here

I have filled 3 dropdowns (Type List

My question is how can i cascade those dropdowns so that when i choose in first dropdown some value i get second dropdown, and when i choose value in that second dropdown i get shown third dropdown

ViewModel:

    {
        List<KeyValuePair<string, int>> typeList = new List<KeyValuePair<string, int>>();

        foreach (var building in buildings)
        {
            if (building == 13)
            {
                typeList.Add(new KeyValuePair<string, int>("Airport City - Building 1300", (int)Buildings.Zgrada1));
            }
            else if (building == 15)
            {
                typeList.Add(new KeyValuePair<string, int>("Airport City - Building 1500", (int)Buildings.Zgrada2));
            }
            else if (building == 31)
            {
                typeList.Add(new KeyValuePair<string, int>("Novi Sad Development Centar", (int)Buildings.Zgrada3));
            }
        }
        return typeList;
    }


    {
        List<KeyValuePair<string, int>> designZonesFor1300 = new List<KeyValuePair<string, int>>();

        designZonesFor1300.Add(new KeyValuePair<string, int>("O", (int)DesignZones.O));
        designZonesFor1300.Add(new KeyValuePair<string, int>("Avisto", (int)DesignZones.Avisto));
        designZonesFor1300.Add(new KeyValuePair<string, int>("TES", (int)DesignZones.TES));

        return designZonesFor1300;
    }

    private List<KeyValuePair<string, int>> CreateDesignZonesForBuilding1500()
    {
        List<KeyValuePair<string, int>> designZonesFor1500 = new List<KeyValuePair<string, int>>();

        designZonesFor1500.Add(new KeyValuePair<string, int>("O", (int)DesignZones.O));
        designZonesFor1500.Add(new KeyValuePair<string, int>("Elsys", (int)DesignZones.Elsys));
        designZonesFor1500.Add(new KeyValuePair<string, int>("Altera", (int)DesignZones.Altera));
        designZonesFor1500.Add(new KeyValuePair<string, int>("ST", (int)DesignZones.ST));
        designZonesFor1500.Add(new KeyValuePair<string, int>("Texas Instruments", (int)DesignZones.TexasInstruments));

        return designZonesFor1500;
    }

Controller:

    {
        List<int> buildings = new List<int>();

        buildings.Add(13);
        buildings.Add(15);
        buildings.Add(31);

        OfficeLocationReportViewModel viewModel = new OfficeLocationReportViewModel(buildings);

        return PartialView("~/Views/Report/_OfficeLocationReportFilterings.cshtml", viewModel);          
    }

View:

    <div>
        @Html.DropDownList("officeLocationBuildings", new SelectList(Model.ListOfBuildings, "Value", "Key", 1), "-- Select Building --")
    </div>

    <div>
        @Html.DropDownList("officeLocationDesignZones", new SelectList(Model.DesignZonesForBuilding1300, "Value", "Key", 1), new { @class = "dropdown1" })
    </div>

I want second dropdown to generate values and show itself when i choose value in my first dropdown

How to transfer data from View(javascript) to Model in MVC

My implementation in Model

namespace Project.Models
{
    public class Book_model
    {
        public static string GetJsonFileString(string section)
        {
            try
            {
                string Data;
                string selectedSection = "Home";
                string home = System.Web.HttpContext.Current.Server.MapPath(@"~/Dictionary//home.json");
                string school = System.Web.HttpContext.Current.Server.MapPath(@"~/Dictionary//school.json");
                if (selectedSection == "Home")
                {
                    Data = File.ReadAllText(home);
                }
                else if (selectedLanguage == "School")
                {
                    Data = File.ReadAllText(school);
                }
                else
                {
                    Data = "Default";
                }
                return Data;
            }
            catch
            {
                return null;
            }
        }
    }
}

View

Context Menu of Selection for Home, School,Cooking

Controller

 [RequireHttps]
        public ActionResult GetBookData(string strSymbol)
        {
            var data = Book_model.GetJsonFileString(strSymbol);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

As you can see in my Model, I hard coded selectedLanguage to "Home", what I want is to have a dynamic context Menu of Selection. How can I implement it ? Thanks in advance

dimanche 17 janvier 2016

How to join two model and display them in view in mvc 3.0 EF 5

I have two tables which have primary and foriegn key concept. I want to get the combined data on behalf of those keys. i don't know how to bind both the table into single model and display it into view.

Model

public class TVSerialModel
{
    public Int32 Serial_ID { get; set; } // primary key
    public string Serial_Name { get; set; }                 
    public int? Release_Year { get; set; }           
}

public class TVSerialEpisodeModel
{
    public Int64 Video_ID { get; set; } 
    public Int32 Serial_ID { get; set; }// foriegn key
    public string Episode_Name { get; set; }
    public string Description { get; set; }        
    public DateTime Uploaded_Time { get; set; }
}

public class TVSerial_Episode_VM
{
    public IEnumerable<TVSerialEpisodeModel> tvserialEpisode { get; set; }
    public IEnumerable<TVSerialModel> Tvserial { get; set; }
}

Controller

public ActionResult NewEpisodeReleased()
{
    cDBContext tvContext = new cDBContext();

    TVSerial_Episode_VM tves=new TVSerial_Episode_VM(); 
    tves= tvContext.dbTvSerialEpisodes.
    Join(tvContext.dbTvSerials, p => p.Serial_ID, r => r.Serial_ID,(p, r) => new { p, r }).
Select(o => new TVSerial_Episode_VM
            { ****what should i write here to get all columns from both table**** }).
Take(9).ToList();            
    return View(tves);
}

Expected Result

enter image description here

Initializing objects using this operator in constructors

As I was trying to implement code first approach using repository patterns in MVC, I have come across some difficulties as below:

I have a Interface that have few methods declared as below :

public interface IRepository
    {
        User Getuserdetail(int UserId);
        void Save(User Obj);
        void delete(int Userid);
        void update(User user);
    }

Then I have a Repository class which could be using the above interface to define all the methods and will create a seperate layer of Entity Framework:

public class Repository : IRepository
    {
            RepoDBContext _context;
            Repository(RepoDBContext Context)
            {
                this._context = Context;
            }

        public User Getuserdetail(int Userid)
        {
            var user = _context.User.Where(m => m.id == Userid).FirstOrDefault();
            return user;
        }
        public void Save(User user)
        {
            _context.User.Add(user);
            _context.SaveChanges();
        }
}

Now could you please check the constructor of this class. The variable this constructor is initializing is type of "RepoDBContext" and the reference type it is using to assign it is also of "RepoDBContext". Is it internally performing like below?

RepoDBContext _context=new RepoDBContext();

My RepoDBContext class is below:

  public class RepoDBContext : DbContext
            {
                public DbSet<User> User { get; set; }
            }

Moreover if is the right way to perform then how will i have to call this class in my controller to do some functionality over my user interface. Please guide regarding the same and please don't mind my english. Thanks

vendredi 15 janvier 2016

Logoff Action Not Being Hit

Salaamun Alekum

I Have A MVC Action Of LogOff Which Is Not Being Hit By Form Using JavaScript My View Page Do Get Refresh On Form Submit But The Action Is Not Being Hit ( It Tried To Check Via Placing A Break Point For Debugging Inside LogOff() Action

This Is Portion Of Partial View (Full Partial View Can Be Found In Previous Edit Of This Post

    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right navbarText" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }

This Is My LogOff Action

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            Session["LoggedInPersonId"] = null;
            //AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return RedirectToAction("Index", "Home");
        }

I Need Guidance On This

Thank You

jeudi 14 janvier 2016

MVC paging doesnt include list items if size is less than page size

I have the following scenario where if user selects a value in the filter for example id which is a property of the IEnumerable domain object in the view model and if the current page is for example 2 and the resulting query count is less than the static page size 10, there is some sort of error in the paging and viewmodel IEnumerable list will be empty even before the paging and the query has results.

It only works for result sets which are greater than 10 and it doesn't matter on what page the filters were applied. It seems that following line is causing smaller results to be excluded. If the filter is applied on the first page with results less than 10 it works.

ErrorCode = errocodeViewModel.ToList().Skip((page - 1) * PageSize).Take(PageSize),

 [HttpPost]
        public ActionResult List(int PageNo, string ActiveErrors, ErrorCodeFilter errorCodeFilter = null)
        {
            if (PageNo == 0)
                PageNo = 1;
            int page = PageNo;


            if (ActiveErrors == "N")
                page = 1;

            var errocodeViewModel = GetErrorCodeListQuery(errorCodeFilter, ActiveErrors).ToList();
            var totalErrorCodeCount = errocodeViewModel.Count();

            ErrorCodesListViewModel viewModel = new ErrorCodesListViewModel()
            {
                ErrorCode = errocodeViewModel.ToList().Skip((page - 1) * PageSize).Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = Convert.ToInt32(page),
                    ItemsPerPage = PageSize,
                    TotalItems = totalErrorCodeCount
                }
            };

            return View(viewModel);
        }


public class ErrorCodesListViewModel
    {
        public IEnumerable<ErrorCodeViewModel> ErrorCode { get; set; }
        public PagingInfo PagingInfo { get; set; }
        public ErrorCodeFilter ErrorCodeFilter;
        public int PageNo;
}

Required attribute NULL in database

I've been trying to add additional attributes to the Identity model, but I want them to be obligatory. But, setting them as Required are causing 2 problems

  1. Attribute is not being set as Not Null in database
  2. Application crashes instead of returning beautiful errors to be displayed in the register window

    public class User : IdentityUser
    {
        [Required]
        public string Name { get; set; }
    
        [Required]
        public virtual Brand Brand { get; set; }
    
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
     }
    
    

Could somebody help me? Thanks!

RenderModel along with MVC ViewModel Umbraco

Hi I want to know can we include both the Model in the single razor View as Follows when using Umbarco CMS

@inherits Umbraco.Web.Mvc.UmbracoViewPage<MasterViewModel>
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage 

Doing so I am not able to apply HTML helpers such as

@Html.TextBoxFor 
@Html.LabelFor etc

and If I am removing @inherits Umbraco.Web.Mvc.UmbracoTemplatePage I am getting following error The model item passed into the dictionary is of type Umbraco.Web.Models.RenderModel', but this dictionary requires a model item of type 'Umbraco_POCTest.Models.MasterViewModel'

Suggest on this.

mercredi 13 janvier 2016

Clear Button Name Parameter in ASP.net

Hi Im new to ASP and MVC3 and my question is how can i clear the button name parameter in my Post because everytime I refreshes my page after clicking the button with the button parameter , the Value of my last clicked button is still there, is there any way to clear this thing up after Submit or when refreshing the page in Controller or by using Jquery?

Thanks

Heres my Code Snippet:

[HttpPost]
    public ActionResult HistoryPage(HistoryModel model, string btnAction)
    {
        if (Session["HistoryId"] != null)
        {
            switch (btnAction)
            {
                case "Delete History":
                    DeleteHistory(model, ref deleteHistoryError, ref deleteHistorySucesss);
                    break;
                case "AddHistory":
                    AddHistory(model);
                    break;

            }
        }
        return View(model);
    }

mardi 12 janvier 2016

File uploading on live server failing

  byte[] bytes = Convert.FromBase64String(Picture);


    System.IO.File.WriteAllBytes(Server.MapPath("~/Content/" + Name), bytes);

This code work wlel on local server but when i try to run it on live server this give error and file is not uploading in content folder.

Data Annotation not working with Ajax Form Upload

I am unable to determine why my Razor View Page is not able to show Model Errors. I have applied Data Annotation to my model class. I am submitting the form using Ajax Form Upload Plugin (See Reference -> http://ift.tt/PEjYy2).

Model Class

public class Category
    {
        [Key]
        public int Id { get; set; }

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

        public string Description { get; set; }

        [FileExtensions(Extensions = ".jpeg,.jpg,.png",ErrorMessage ="Please upload valid image format.")]
        public string BannerImage { get; set; }

        [FileExtensions(Extensions = ".jpeg,.jpg,.png", ErrorMessage = "Please upload valid image format.")]
        public string ThumbImage { get; set; }

        private HttpPostedFileBase _bannerImageFile;

        [Display(Name = "Banner Image")]
        public HttpPostedFileBase BannerImageFile
        {
            get
            {
                return _bannerImageFile;
            }
            set
            {
                _bannerImageFile = value;
                if(value != null)
                    BannerImage = _bannerImageFile.FileName;
            }
        }

        private HttpPostedFileBase _thumbImageFile;

        [Display(Name = "Thumb Image")]
        public HttpPostedFileBase ThumbImageFile
        {
            get
            {
                return _thumbImageFile;
            }
            set
            {
                _thumbImageFile = value;
                if (value != null)
                    ThumbImage = _thumbImageFile.FileName;
            }
        }

        [Display(Name = "Meta Keywwords")]
        public string MetaKeywords { get; set; }

        [Display(Name = "Meta Description")]
        public string MetaDescription { get; set; }

        [Display(Name = "Created Date")]
        public string CreatedDate { get; set; }

        [Display(Name = "Last Updated Date")]
        public string LastUpdatedDate { get; set; }

        public bool Status { get; set; }

        public List<SubCategory> SubCategories { get; set; }

public bool IsSaved(string spNameOrSql, Dictionary<string, object> parameters, QueryType type = QueryType.SQL)
            {
                try
                {
                    if (type  == QueryType.StoredProcedure)
                    {
                        var p = new SqlParameter[parameters.Count];
                        var count = 0;
                        foreach (var item in parameters)
                        {
                            var key = item.Key;
                            var value = item.Value;
                            value = String.Join(" ", Convert.ToString(value).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries));
                            p[count++] = new SqlParameter("@" + key, value);
                        }
                        return Convert.ToBoolean(DataFunctions.ExecuteScalar(spNameOrSql, p, type));
                    }
                    return Convert.ToBoolean(DataFunctions.ExecuteScalar(spNameOrSql, type));
                }
                catch (Exception ex)
                {
                    Error.Log(GetType().Name, MethodBase.GetCurrentMethod().ToString(), ex.Message, ex.Source, ex.StackTrace);
                    return false;
                }
            }
}

Controller

public ActionResult AddCategory(Category model)
    {
        if (ModelState.IsValid)
        {

            var param = model.GetType().GetProperties().ToDictionary(prop => prop.Name,
                                                    prop => prop.GetValue(model, null));

            param.Remove(Nameof<Category>.Property(e => e.Id));
            param.Remove(Nameof<Category>.Property(e => e.BannerImageFile));
            param.Remove(Nameof<Category>.Property(e => e.ThumbImageFile));
            param.Remove(Nameof<Category>.Property(e => e.CreatedDate));
            param.Remove(Nameof<Category>.Property(e => e.LastUpdatedDate));

            var result = model.IsSaved(AppConstants.StoredProcedures.CATEGORY_ADD, param, QueryType.StoredProcedure);

            if (result)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    switch (Request.Files.Keys[i])
                    {
                        case "BannerImageFile":
                            UploadImage(Request.Files[i], AppConstants.FilePath.CATEGORY_BANNER_IMAGE_PATH);
                            break;
                        case "ThumbImageFile":
                            UploadImage(Request.Files[i], AppConstants.FilePath.CATEGORY_THUMB_IMAGE_PATH);
                            break;
                    }
                }
                ModelState.Clear();
            }
        }

        return PartialView("_PartialAddCategory",model);
    }

View

@model TristarJewelry.Shared.Models.Category
<script type="text/javascript">
    $(document).ready(function () {
        var options = {
            beforeSubmit: BeginLoader,
            success: OnSuccess,
            error: OnFailure,
            target: '#myForm'
        };
        $('#myForm').ajaxForm(options);
    });

    function OnSuccess() {
        $("#app_message").removeClass("alert-success alert-danger alert-warning alert-info");
        $("#app_message").addClass("alert-success");
        $("#app_message").html("Category Succesfully Added !");
        $("#app_message").fadeIn(2000).delay(2000).fadeOut(2000);
        StopLoader();
    }

    function OnFailure() {
        $("#app_message").html("Oops something went wrong ! Try after sometime. ");
        $("#app_message").removeClass("alert-success alert-danger alert-warning alert-info");
        $("#app_message").addClass("alert-danger");
        $("#app_message").fadeIn(2000).delay(3000).fadeOut(2000);
    }
    function BeginLoader() {
        $('#loader').modal({ toggle: "model", backdrop: 'static', keyboard: false });
    }
    function StopLoader() {
        $('#loader').modal("hide");
    }

</script>

<div id="page-wrapper">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">Add Category</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    Please fill all the details.
                </div>
                <div class="panel-body">
                    <div class="row">

    <form id="myForm" action="@Url.Action("AddCategory","Dashboard")" method="POST" enctype = "multipart/form-data">

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.Name)
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Name" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Description)
                @Html.TextAreaFor(model => model.Description, new { @class = "form-control", @placeholder = "Enter Description", @rows = "3", style = "resize:vertical" })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.ThumbImageFile)
                @Html.TextBoxFor(model => model.ThumbImageFile, new { type = "file" })
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.BannerImageFile)
                @Html.TextBoxFor(model => model.BannerImageFile, new { type = "file" })
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Status) &nbsp;&nbsp;
                @Html.CheckBoxFor(model => model.Status)
                @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
            </div>

            <button type="submit" class="btn btn-default">Submit Button</button>
            <button id="form_reset" type="reset" class="btn btn-default">Reset Button</button>
        </div>

        <!-- /.col-lg-6 (nested) -->

        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.MetaKeywords)
                @Html.EditorFor(model => model.MetaKeywords, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Meta Keywords" } })
                @Html.ValidationMessageFor(model => model.MetaKeywords, "", new { @class = "text-danger" })
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.MetaDescription)
                @Html.TextAreaFor(model => model.MetaDescription, new { @class = "form-control", @placeholder = "Enter Meta Description", @rows = "3", style = "resize:vertical" })
                @Html.ValidationMessageFor(model => model.MetaDescription, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- /.col-lg-6 (nested) -->
        </form>
</div>
                    <!-- /.row (nested) -->
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</div>

On Controller ,ModelState.IsValid becomes false if any of the model property doesn't validate but it is not displaying error on view page. Don't know why. can anybody tell me.

Note* : I am not using Ajax.BeginForm here because i can't able to upload files with this approach. So instead i am using jquery form upload puglin.

Any help would be appriciated. If you need to know anything let me know here.

Asp.Net MVC website loading slow at first time or inactivity of 30 min

GoDaddy's server idle timeout is 5 min. If my website will hit every 5 min automatically then it will not suspend.Is there is any way to hit on server after every 5 min so the server will not remove cache.

Umbraco 6.2.1 with MVC 3

I am pretty much good with MVC 3 and now have been searching to integrate my application using Umbraco CMS and I have Installed it in my solution but do not know how to integrate this and how to Use it.

Validation summary for multiple partial view / forms on a view

I have 3 partial views each view HTML.BeginForm() on my main view and each have submit button. You can consider them as Login, Registration and Search views. I am using data annotation for validation of partial views and invoking the submit button using $.ajax as shown below:

if (IsFormValid()) {
    $.ajax({
            url: '/MySite/Main/LogOn',
            type: 'POST',
            data: $('#pnlLogOnConsumer').serialize(),
            success: function (result) {
                // do nothing
            },
            error: function (req, status, errorObj) {
                alert('Error');
            }
    });
} 

function IsFormValid() {
    $.validator.unobtrusive.parse($("#form1"));
    $("#form1").validate();
    return $("#form1").valid();
}

Everything works fine if I use validationsummary inside partial views. But my requirement says to have validation summary below header for each page, outside partial views. When I place validationsummary outside form tag of partial views, it doesn't work. It doesn't work even if I place the validation summary inside another form tag in another partial view.

lundi 11 janvier 2016

Create from Existing MVC

So i have my model and i want to create a new plant from an existing plant selected from a drop down list with the same properties as the old plant except the scientific name.I created a function that will take the new plant name and the old plant and creates a new plant with old properties.I want to know what should i do in my controller and view in order to create this new plant from existing.

Here is my model

public class ExistingPlant
{

    public string selectedPlant { get; set; }
    public Dictionary<Guid,string> plantList { get; set; }
}

and here is my controller code

public ActionResult CreateFrom()
    {
        ExistingPlant existing = new ExistingPlant();

        Dictionary<Guid, string> plants = new Dictionary<Guid, string>();

        foreach(var item in context.Plants){

            plants.Add(item.PlantId , item.ScientificName);
             }

        existing.plantList = plants;
        existing.selectedPlant = "Value";

        var plant = context.Plants.Where(d => d.ScientificName == existing.selectedPlant);
        string temp = existing.selectedPlant;
        Plant p = (Plant) plant;
        CopyExisting(p,temp);

        return View(existing);
    }

and my view code :

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset id="field">
    <div>
        <label> Scientific Name:</label>
    </div>

    <div class="editor-field">
        @Html.EditorFor(m => m.selectedPlant)
        @Html.ValidationMessageFor(m =>m.selectedPlant)
    </div>

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

</fieldset>
@Html.DropDownListFor(
    m => m.selectedPlant,
    new SelectList(Model.plantList, "Key", "Value")
)

}

MVCRazorToPDF Adding page header and footer on every pages

Can i make a header and footer on every pages created using MVCRazorToPDF Library On PDFLayout.cshtml file i am making a section for the body of PDF as

<body>
@RenderBody()
</body>

And in controller i am calling the action like

return new PdfActionResult(model, (writer, document) =>
        {
            document.SetPageSize(new Rectangle(233, 842, 90));
            document.NewPage();
        });

And my View.cshtml is like a normla html page

@model PDFLAbApp.Models.PdfExample
@{
    Layout = "~/Views/Shared/_PdfLayout.cshtml";
}
<h1>@Model.Heading</h1>
<p>
paragraph content repeated n times based on the model content [ its a foreach loop and page size is more than 2 
</p>

dimanche 10 janvier 2016

How to join two model and display them in view in mvc 3.0 EF 5

I have two tables which have primary and foriegn key concept. I want to get the combined data on behalf of those keys. i don't know how to bind both the table into single model and display it into view.

Model

public class TVSerialModel
{
    public Int32 Serial_ID { get; set; } // primary key
    public string Serial_Name { get; set; }                 
    public int? Release_Year { get; set; }           
}

public class TVSerialEpisodeModel
{
    public Int64 Video_ID { get; set; } // foriegn key
    public Int32 Serial_ID { get; set; }
    public string Episode_Name { get; set; }
    public string Description { get; set; }        
    public DateTime Uploaded_Time { get; set; }
}

public class TVSerial_Episode_VM
{
    public IEnumerable<TVSerialEpisodeModel> tvserialEpisode { get; set; }
    public IEnumerable<TVSerialModel> Tvserial { get; set; }
}

Controller

public ActionResult NewEpisodeReleased()
{
    cDBContext tvContext = new cDBContext();

    TVSerial_Episode_VM tves=new TVSerial_Episode_VM(); 
    tves= tvContext.dbTvSerialEpisodes.
    Join(tvContext.dbTvSerials, p => p.Serial_ID, r => r.Serial_ID,(p, r) => new { p, r }).
Select(o => new TVSerial_Episode_VM
            { ****what should i write here to get all columns from both table**** }).
Take(9).ToList();            
    return View(tves);
}

Expected Result

enter image description here

Avoid Index form Url with string parameter in mvc3

I have a controler action like this

    [HttpGet]
    public ActionResult Index(string Id)
    {
    }

So actual call is like Report/Index/{string_param_value}

I want to avoid Index from this like Report/{string_param_value} and for that i did following change in Global.asax.cs

   routes.MapRoute(
      "Report_WithoutIndex",
      "Report/{Id}",
      new { controller = "Report", action = "Index" }
  );

But this one is not calling the Index action I tried this one then

routes.MapRoute(
            name: "Index",
            url: "{controller}/{id}",
            defaults: new { action = "Index" },
            constraints: new { action = "Index" }               
        );

And this one works for me But after this all other Actions are broken

SO what is the correct work around for making a call to Report controller wuthout mentioning Index in url

Can't get an Angular App to work inside a MVC Layout

I got a MVC Site that uses a layout, in the layout page i use an Angular App, Models and Controllers and everything works like it supposed to, in one of my pages (that is shown inside the layout) i want to use another Angular App & Controller with some really basic functions, you can see the main idea here: Plunker for example.

Some more info:

  • I refer to both of the .js files in the layout <head> tag:

    <script src="~/Scripts/AdminVM.js"></script>
    <script src="~/Scripts/ShopVM.js"></script>
    
    
  • All the code in my layout page that uses the first App is between two <div> tags, first one with ng-app = "FirstApp", second with ng-controller = "FirstController".

  • I tried both:

    1. Putting the two <div> tags with ng-app = "SecondApp", and ng-controller = "SecondController" inside my .cshtml file and in between putt my code.
    2. Putting the two <div> tags inside my layout page's body and between them putt the @RenderBody() tag.

I have no idea what am i doing wrong here, even the most simple thing isn't working:

ShopVM.js

var app = angular.module("ShopApp", []);
app.controller("ShopViewModel", function ($scope, $http) {
    $scope.test = "Test123";
});

Shop.cshtml (Not the layout file)

<div ng-app="ShopApp">
    <div ng-controller="ShopViewModel">
        <ul class="nav nav-tabs nav-justified">
            <li role="presentation" class="active"><a href="#">Home</a></li>
            <li role="presentation"><a href="#">Cat1</a></li>
            <li role="presentation"><a href="#">Cat2</a></li>
        </ul>
        <div>{{test}}</div>

        <input id="Text1" type="text" ng-model="Shop.Test"/>

    </div>
</div>

And what i see is a simple test: {{test}}

What is wrong with my code?

Cancel old page request on clicking new page

I have a ASP.Net web application.I it One of the pages loads videos it's taking long time then expected. when i click on other links to load new pages. it's not loading because the old page is still processing. how i can cancel the old page request after i click on new in the asp.net world.?

TIA

samedi 9 janvier 2016

session time out happening before the time mentioned in webconfig

In webconfig i mentioned the session timeout as 20 minutes

    <system.web>

        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" maxRequestLength="350000" enableVersionHeader="false" 
maxQueryStringLength="3584" executionTimeout="600"/>
        <sessionState mode="InProc" timeout="20"></sessionState>
            <globalization culture="en-GB" />
      </system.web>

but the website is getting logout before 20 minutes of idle time. Any thing i am missing in the code?

Add validation rules to dynamically added inputs in mvc project by jquery

Now i need to validate dynamically added fields by jquery and my form already has fields with validation in client side and in server side but in same form i added new dynamic inputs during page load but when i add validation to dynamic fields it works but eliminate validation of other fields (not dynamic)

jQuery(document).ready(function () {
$("#myform").valid();
        $("#i3m29_inpt_ttext").rules("add", {
            required: true,
            minlength: 2,
            messages: {
                required: "Required input",
                minlength: jQuery.validator.format("Please, at least {0} characters are necessary")
            }
        });});
$("#htmldv").append("<input id='i3m29_inpt_ttext' type='text'>");

So now i need to validate new dynamic fields without affect on validation of other fields that already exist in the form

vendredi 8 janvier 2016

MVC dynamic form controls binding to model

I'm trying to dynamically create a form with different types of fields. Then simply pass the user inputted data back to the controller and bind back to my model. I'm using a custom editor template for each control and was hoping it would bind properly in the controller. However, the property is NULL each time so I cannot retrieve the input values.

Model

public class ReceiptModel : ClassBase
{
    public int ReceiptId { get; set; }
    public List<CustomControlModel> CustomControlList { get; set; }
}

public class CustomControlModel 
{
    public string CustomControlName { get; set; }
    public CustomControlType CustomControlType { get; set; }
}

View

@foreach (CustomControlModel ccm in @Model.CustomControlList)
{
    if (!string.IsNullOrEmpty(ccm.PropertyName))
    {
        @Html.EditorFor(model => ccm, "CustomControlModel")
    }
}

Any help would be much appreciated. Thanks in advance.

Cannot insert explicit value for identity column in table

Salaamun Alekum I Am Getting NULL in file instance of action after posting a file in FORM

 public ActionResult CreateDoctorProfile(HttpPostedFileBase file)
        {

            int LoggedInPersonID = Convert.ToInt32(Session["LoggedInPersonId"]);
            erx_t_personnel PersonnelInformation = db.erx_t_personnel.Where(PersonnelInformation1 => PersonnelInformation1.Person_Id == LoggedInPersonID).FirstOrDefault();

            return View(PersonnelInformation);
        }

This Is My View

@model Doctors_Search_Engine.Models.erx_t_personnel

@{
    ViewBag.Title = "Personnel Registration";


}

<h2>Personnel Registration</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()


        <input type="file" name="Image" />
        <input type="submit" value="Create" class="btn btn-default" />
}

What Should I Do To Get Value In file Of Action Parameters. I Need Guidance On This

Thank You

What is the best way to print a cheque from an asp.net mvc app?

I need a way to send cheque parameters to an action method that returns a view containing a check with parameter values

Need List of Users into viewbag, whose Role is "xyz"

Roles

ApplicationId UNIQUEIDENTIFIER NOT NULL,
RoleId        UNIQUEIDENTIFIER NOT NULL,
RoleName      NVARCHAR (256) NOT NULL,
Description   NVARCHAR (256),
PRIMARY KEY (RoleId),

Users

ApplicationId    UNIQUEIDENTIFIER NOT NULL,
UserId           UNIQUEIDENTIFIER NOT NULL,
UserName         NVARCHAR (50) NOT NULL,
IsAnonymous      BIT NOT NULL,
LastActivityDate DATETIME NOT NULL,
PRIMARY KEY (UserId),

UsersInRoles

UserId UNIQUEIDENTIFIER NOT NULL,
RoleId UNIQUEIDENTIFIER NOT NULL,
PRIMARY KEY (UserId, RoleId),
CONSTRAINT UsersInRoleRole FOREIGN KEY (RoleId) REFERENCES dbo.Roles (RoleId),
CONSTRAINT UsersInRoleUser FOREIGN KEY (UserId) REFERENCES dbo.Users (UserId)

i need all the username from users table whose rolename is like xyz into a viewbag, so i can display the Usenames in dropdopwn

jeudi 7 janvier 2016

How to bind a telerik grid to a controller action

The following code is returning me the data in JSON in the browser, but its not displaying the telerik mvc grid.

public class TipoDeCanalesController : GenericController
{
    private UnitOfWork unitOfWork = new UnitOfWork();

    // GET: TipoDeCanales
    public ActionResult Index([DataSourceRequest] DataSourceRequest request)
    {
        return Json(unitOfWork.TipoDeCanalRepository.Get(),JsonRequestBehavior.AllowGet);
    }

and the view

@model IEnumerable<powerdata.comisiones.models.tipodecanal>

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    @(Html.Kendo().Grid(Model)
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ID);
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Descripcion).Title("Descripcion");
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ID))
        .Create(update => update.Action("EditingPopup_Create", "Grid"))
        .Read(read => read.Action("Index", "Grid"))
        .Update(update => update.Action("EditingPopup_Update", "Grid"))
        .Destroy(update => update.Action("EditingPopup_Destroy", "Grid"))
     )
    )
    %>
    <script type="text/javascript">
        function error_handler(e) {
            if (e.errors) {
                var message = "Errors:\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function () {
                            message += this + "\n";
                        });
                    }
                });
                alert(message);
            }
        }
    </script>

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[TipoDeCanal]',

I have this error when passing data from controller to view

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[TipoDeCanal]', but this dictionary requires a model item of type TipoDeCanal'.

     public class TipoDeCanalesController : GenericController
        {
            private UnitOfWork unitOfWork = new UnitOfWork();

            // GET: TipoDeCanales
            public ActionResult Index([DataSourceRequest] DataSourceRequest request)
            {
                //return Json(unitOfWork.TipoDeCanalRepository.Get(),JsonRequestBehavior.AllowGet);
                return View(unitOfWork.TipoDeCanalRepository.Get());
            }


@model ..Models.TipoDeCanal
@using ..Models
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@(Html.Kendo().Grid<TipoDeCanal>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ID);
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Descripcion).Title("Descripcion");
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ID))
        .Create(update => update.Action("EditingPopup_Create", "Grid"))
        .Read(read => read.Action("Index", "Grid"))
        .Update(update => update.Action("EditingPopup_Update", "Grid"))
        .Destroy(update => update.Action("EditingPopup_Destroy", "Grid"))
    )
)
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>

Web.site map file is called on "enter key"

Our application is developed using asp.net MVC4 and using a web.site map file for navigation. What happens is web.site map is called even when the user is hitting the enter key and navigates to the first action in the web.site map file. Wondering if there is a way to stop calling web.site map file in MVC4?

mercredi 6 janvier 2016

invoke a session inside a method where that session create

I'm trying to reuse a session inside a method where that session created.

    public ActionResult Add_Product(AddNewProduct sample)
    {
        //create the session
        TempData["AddNewProduct"] = sample;

        //create the object of AddNewProduct and invoking the session
        AddNewProduct book = TempData["AddNewProduct"] as AddNewProduct;

        AddNewProduct model = new AddNewProduct();

        model.FirstName = "XXX";

        sample = model;

        return View(model);

    }

In this view page I have button to call to this Action again, once I click and debug the code I can see session getting null

mardi 5 janvier 2016

create session to use values inside the same method

This is code snippet for load 15 text areas into an Add_New_Product form page.

this is the view enter image description here

Since in this form page has many text areas(like 15) ,I limited with pagination , one text area per one page.

    public ActionResult Add_Product(int? page)
    {
        var dummyItems = db.AB_ProductTypeCategoryField;
        var pager = new PaginationModel.Pager(dummyItems.Count(), page);

        var model = new AddNewProduct
        {
            ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
            Pager = pager
        };

        return View(model);
}

I want use above ListProductFields data iteratvely inside same above method. Since , once I insert the data to first text area and then go to next text area , again then I click previous button , then those initially added values for first text area are disappearing .I decided to come up with sessions , So I changed above code as follows

    public ActionResult Add_Product(int? page, AddNewProduct sample)
    {
        AddNewProduct newmodel = sample;                       

        AddNewProduct newmodels = Session["TemplateData"] as AddNewProduct;

        var dummyItems = db.AB_ProductTypeCategoryField;
        var pager = new PaginationModel.Pager(dummyItems.Count(), page);

        var model = new AddNewProduct
        {
            ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
            Pager = pager
        };

        Session["TemplateData"] = model;

        return View(model);

    }

But it doesn't keep any value

lundi 4 janvier 2016

Bundling with one file

I have view with several partial views. The view loads several javascript file as a single bundle. but one js file differ based on the partial view.

Can i bundle one file in my partial, will it improve performance. or how can i minify that file in order to improve performance.

Parameters in MVC not being correctly passed into the view from routing

I'm teaching myself MVC and have an issue with routing correctly

I have a controller named "ClipsController" and 1 view inside with the name "Index" (boring, i know)

I have my routeconfig file configured with the following route:

routes.MapRoute(
    "Clips",
    "Clips/{id}",
    new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);

which is Before the "Default" route. When i go to /Clips/ExampleID it does hit the correct route, and does start the Index action in the Clips controller. What i'm having trouble with is the parameter 'ID' fails to pass through into the Index page, but i end up on the index action of the Clips controller, with the URL http://ift.tt/1OHOSxv

I attempt to get the ID parameter with

httpcontext.current.request.querystring["id"]

which always returns a null. My actionresult in the controller is as follows:

public ActionResult Index(string id)
{
    return view()
}

To reiterate, I'm not able to see the querystring id on the index view, even though the URL does the correct route, and the actionresult in the controller is to my kowledge correct. If i have done something critically wrong or you need more information please let me know, Thanks.

How to convert ErrorCode to String with ASP.NET MVC5?

I am trying to convert the ERRORCODE to String with ASP.NET MVC5,

with ASP.NET MVC3 we can convert the error code to String using this code:

// Attempt to register the user
MembershipCreateStatus createStatus;
ErrorCodeToString(createStatus);

but with ASP.NET MVC5, it shows an error using the ErrorCodeToString because it is undefined.

Is there a new way?

New Edit :::::::::: this is enter image description here

CRUD operations with multiple lists in view model

I have a view model that has multiple lists that I want users to administer from a single screen. Here is my view model:

    public int EmployerId { get; set; }
    public string EmailAddress { get; set; }
    public string Password { get; set; }
    public bool IsEnabled { get; set; }
    public string SecurityQuestionAnswer { get; set; }

    public List<BillData> BillingIds { get; set; }
    public List<GroupAccess> Groups { get; set; } 

The goal is to allow CRUD operations for email address, pwd, etc.. as well as the 2 lists. When a user saves, all of the data will post to the controller, saving all of the data. I can't find a way to do this without editing the 2 lists in another view and commiting to the database. I've looked at several grid components but they also commit the lists individually, not tying to the view model.

I want the view to allow CRUD operations for all data elements from the same screen and the updated viewmodel to be returned to the controller for saving.

How would you do something like this without going to another view?

Google Maps API - Map not showing on second initialize

I have implemented in MVC page load Google Map and also draw route map between to cities.

In address parameter I have two cities,first time loading map coming fine but next any time not coming only gray color screen display.

Second time in place of google map gray screen coming.
var map = '';
function ShowTrack(address) {
    markers = [];
    debugger;
    var lst = address.split('~');
    GetMarkers(address);
    document.getElementById("dvMap").innerHTML = '';
    {
        if (lst.length > 1) {
            var mapOptions = {
                center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };         
           map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); 
            var infoWindow = new google.maps.InfoWindow();
            var lat_lng = new Array();
            var latlngbounds = new google.maps.LatLngBounds();
            for (i = 0; i < markers.length; i++) {
                var data = markers[i]
                var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                lat_lng.push(myLatlng);
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: data.title
                });
                latlngbounds.extend(marker.position);
                (function (marker, data) {


                    google.maps.event.addListener(marker, "click", function (e) {
                        infoWindow.setContent(data.description);
                        infoWindow.open(map, marker);
                    });
                })(marker, data);
            }
            map.setCenter(latlngbounds.getCenter());
            map.fitBounds(latlngbounds);

            //***********ROUTING****************//
            //Initialize the Path Array
            var path = new google.maps.MVCArray();
            //Initialize the Direction Service
            var service = new google.maps.DirectionsService();
            //Set the Path Stroke Color
            var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });

            //Loop and Draw Path Route between the Points on MAP
            for (var i = 0; i < lat_lng.length; i++) {
                if ((i + 1) < lat_lng.length) {
                    var src = lat_lng[i];
                    var des = lat_lng[i + 1];
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function (result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });
                }
            }
        }
    }
}