jeudi 31 mars 2016

get match value and line number from xml file(STRING ARRAY) using regex in c#

<article id="test" article-type="research-article" dtd-version="3.0" xml:lang="en">
    <front>
    <contrib-group>
    <contrib contrib-type="author"><name><surname>Guthrie</surname><given-Organization, Peabody College of Vanderbil University, 230 Appleton Place, @ Nashville, TN 37203-5721, E-mail: 
    <email xlink="jwgxiii@sbcglobal.net">jwgxiii@sbcglobal.net</email></aff>@</contrib>
    @
    <a>
    @
    </a>
    <b>@
    </b>
    <a>
    @</a>
    <a>@</a>
    <c type="@">
    </c>
    </contrib-group>
    <pub-date pub-type="ppub">
    <day>1 </day>
    <month>1</month>
    <year>2006</year>
    @
    <string-date>Winter 2006</string-date>
    </pub-date>
    </front>
    </article>

How to add bootstrap glyphicon inside html.actionlink?

Currently I am using bootstrap buttons for my following code and it is working fine:

    @Html.ActionLink("Bookmark this carpark!", "../Bookmarks/Create", new { carparkId = Model.id, address = Model.address }, new { @class = "btn btn-warning" })

However, I would like to also add in a glyphicon icon bookmark together. Any idea how do I do it ?

How to avoid refresh of layout view when navigating between pages

If I have a more than one pages, all using the same layout page, is there a way I can navigate between the pages and only refresh the body part of the layout page. For example if I have a list page and select an item to go to the detail page and they both contain the same layout view, I don't want the layout which contains the menu and footer to reload, just the @RenderBody() should reload. I am building this in Mvc 3. I am a beginner to Mvc so help we with some examples. Thanks.

mercredi 30 mars 2016

Ajax.BeginForm returning PartialView not updating target div [duplicate]

This question already has an answer here:

I have the following view, Index.cshtml:

@using (Ajax.BeginForm("Foo", "Profile", new AjaxOptions
{
    UpdateTargetId = "UpdateTarget"
}))
{
    <h2>Index</h2>
    <input type="submit" value="Submit" />
    <div id="UpdateTarget"></div>
}

As well as the partial view IndexPartial.cshtml:

@model String
<label>Server result: </label>
<span>@Model</span>

And ProfileController.cs:

using System.Web.Mvc;
namespace WebSandbox.Controllers
{
    public class ProfileController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Foo()
        {
            var result = "foobar";
            return PartialView("IndexPartial", result);
        }
    }
}

When I click submit I currently get a new view which contains "Server result: foobar", and my header and button disappear. What I am trying to achieve is for this markup to appear within my UpdateTarget div on submit, underneath my header and button.

Why is this code redirecting to a new view rather than updating the part of Index.cshtml specified by my UpdateTargetId?

ASP.NET MVC 3 - getting duplicate Rows

I'm currently using MVC 3 with Entity Framework 5. So this is my controller that is called MachineController:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gestion_Machines.Models;

namespace Gestion_Machines.Controllers
{ 
    public class MachineController : Controller
    {
        private RTTV5Entities db = new RTTV5Entities();

        //
        // GET: /Machine/

        public ViewResult Index()
        {
            return View(db.tMachines.ToList());
        }

        //
        // GET: /Machine/Details/5

        public ViewResult Details(string id)
        {
            tMachines tmachines = db.tMachines.Find(id);
            return View(tmachines);
        }

        //
        // GET: /Machine/Create

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

        //
        // POST: /Machine/Create

        [HttpPost]
        public ActionResult Create(tMachines tmachines)
        {
            if (ModelState.IsValid)
            {
                db.tMachines.Add(tmachines);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(tmachines);
        }

        //
        // GET: /Machine/Edit/5

        public ActionResult Edit(string id)
        {
            tMachines tmachines = db.tMachines.Find(id);
            return View(tmachines);
        }

        //
        // POST: /Machine/Edit/5

        [HttpPost]
        public ActionResult Edit(tMachines tmachines)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tmachines).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tmachines);
        }

        //
        // GET: /Machine/Delete/5

        public ActionResult Delete(string id)
        {
            tMachines tmachines = db.tMachines.Find(id);
            return View(tmachines);
        }

        //
        // POST: /Machine/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {            
            tMachines tmachines = db.tMachines.Find(id);
            db.tMachines.Remove(tmachines);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

This is my Index View that was automatically generated after creating the controller along with create, delete, details and Edit:

@model IEnumerable<Gestion_Machines.Models.tMachines>

@{
    ViewBag.Title = "Index";
}

<link href="../../Content/machine.css" rel="stylesheet" />
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            NomMachine
        </th>
        <th>
            Fabriquant
        </th>
        <th>
            MachineSection
        </th>
        <th>
            TypeMachine
        </th>
        <th>
            VitesseMaxi
        </th>
        <th>
            NbPistes
        </th>
        <th>
            UniteVitesse
        </th>
        <th>
            UniteEntrante
        </th>
        <th>
            UniteSortante
        </th>
        <th>
            Efficience
        </th>
        <th>
            EfficienceGlobale
        </th>
        <th>
            VitesseMoy
        </th>
        <th>
            TauxPanne
        </th>
        <th>
            TauxArret
        </th>
        <th>
            RunM2
        </th>
        <th>
            RunML
        </th>
        <th>
            TCO
        </th>
        <th>
            Section
        </th>
        <th>
            Atelier
        </th>
        <th>
            TransfertFocus
        </th>
        <th>
            MagasinEntree
        </th>
        <th>
            MagasinSortie
        </th>
        <th>
            NbPalettes
        </th>
        <th>
            MagasinSortieWIP
        </th>
        <th>
            MagasinSortieSF
        </th>
        <th>
            MagasinSortieFG
        </th>
        <th>
            Qualite
        </th>
        <th>
            BlistersPerCarton
        </th>
        <th>
            SeuilProdAtteint
        </th>
        <th>
            TpsChgmtOf
        </th>
        <th>
            QteProdSaisie
        </th>
        <th>
            Active
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.NomMachine)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Fabriquant)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MachineSection)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TypeMachine)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VitesseMaxi)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.NbPistes)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UniteVitesse)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UniteEntrante)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UniteSortante)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Efficience)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EfficienceGlobale)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VitesseMoy)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TauxPanne)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TauxArret)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.RunM2)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.RunML)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TCO)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Section)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Atelier)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TransfertFocus)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MagasinEntree)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MagasinSortie)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.NbPalettes)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MagasinSortieWIP)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MagasinSortieSF)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MagasinSortieFG)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Qualite)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BlistersPerCarton)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SeuilProdAtteint)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TpsChgmtOf)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.QteProdSaisie)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Active)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

So my problem is when I access /Machine/Index I do get the appropriate table, only It contains duplicated records while other ones are missing.

ps: my database doesn't contain any duplicated ones.

mardi 29 mars 2016

Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0 with difference mvc version

My MVC 4 project(use System.Web.Mvc.DLL version 4) was working,but now suddenly I get an error(without anything).That error occurs in my controller which call EF code first code from data layer

This is the line causing the error in MVC 4 Project:

var cultures = db.Cultures.Select(c => c.Code).ToArray();//call from data layer

In my mvc project I have deleted the data layer and added it again it again and then I set that DLL copy local to true but the error was not fixed.

My MVC project use System.Web.Mvc, Version=4.0.0.0 and copy local is true And Data layer use System.Web.Mvc, Version=3.0.0.0 and copy local is true

I looked error inner exception it give that error

Could not load file or assembly 'System.Web.Mvc, Version=3.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)

EF code first Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information

My mvc project was work very well.But suddenly I get error.That error occure In my mvc project controller in EF code first(EF code first is a different layer.it is name data layer) line.It give that error

    Unable to load one or more of the requested types
 Retrieve the LoaderExceptions property for more information.

error occur in this or other ef code first line

var cultures = db.Cultures.Select(c => c.Code).ToArray();

In my mvc project I deleted data layer and add it again it again and then I set copy local to true but error was not fixed

ASP.NET MVC adding an existing database

I'm currently in the process of learning ASP.NET MVC so bare with me. My problem is, I'm trying to add a database table from SQL Server to my ASP.NET MVC 3 Project. I already know how to add a new one, but I can't figure out how to add an existing one.

Thanks in advance.

MVC3 windows authentication, Custom Roles Provider and custom AuthorizeAttribute

I'm implementing a custom AuthorizeAttribute in my mvc3 application. I have a Custom Roles Provider with my GetRolesForUser. I add cacheRolesInCookie in a web.config

<roleManager enabled="true" defaultProvider="CustomRolesProvider" cacheRolesInCookie="true" cookieProtection="All">
      <providers>
        <clear />
        <add name="CustomRolesProvider" type="Prisma.Security.CustomRolesProvider" />
      </providers>
    </roleManager>

In my AuthorizeAttribute I check roles for user with command filterContext.HttpContext.User.IsInRole.

Each call to this method called GetRolesForUser and its implementation. I can use the data in cookies?

lundi 28 mars 2016

Web API in MVC project (Authentication)

I have ASP.NET MVC project and using Form Authentication (Cookie base) with ASP.NET Identity. I added WEB API controller into that project. Now What I want is for MVC project it should use Form Authentication using Cookie but for API it should use token base, How I can configure it.

Regards, Imran Ahmad

Partial view not refreshing in my asp.net mvc 4 application

Hello Guys can anyone help me out?

I am using this code to refresh the partial view in my page. but it seems like its not working as expecting when I am sending the updated model to update only partial view.

Here is my code.

 public ActionResult Index(string sname)
        {
            ViewBag.PageTitle = "Page1";
             _vm.SecurityLevelInfo = GetOperationalHome(sname);
            return View(_vm);
        }

Partial view Action

 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult OperationsView(string sname)
        {
            ViewBag.PageTitle = "This is the page title";

           _vm.SecurityLevelInfo = GetOperationalHome(sname);
            return PartialView("OperationsView",_vm);
        }

Here is my view which I am using to load the partial view.

 $(document).ready(function () {
        $('input[type=radio][name=SourceName]').change(function () {
            var sval = $(this).val();
            $("#myPartialViewContainer").load('@Url.Action("OperationsView", "Home")' + '?sname=' + sval);
        });
    });
<div id="myPartialViewContainer">
                    @Html.Partial("OperationsView", Model.SecurityLevelInfo);
                    </div>

On dropdown selection change I am trying to update the partial view. Initial load when its hitting to Index page its working good without any problem. But when I am trying to update the partial view on dropdown selection change its not working as expecting.

Thanks for quick help on this guys..

Using LINQ to access IEnumerable list in Model object to perform a Select and Where

I am working on an ASP.NET MVC view. I am passed the Model to the View and trying to access the property but I am having issue with access the IEnumerble collection in the model object.

@Model.Detail.Owners

Owners can contain multiple records and defined as

public IEnumerable Owners { get; set; }

I am trying to get the Owner full name with the where clause

@Model.Detail.Owners.Select(s=> s.)

but when I typed s. the intellisense does not display the property like FullName for Owner. Instead I get a list of ExecuteAsync and IfNotNull options.

I would like something like the following to work

@Model.Detail.Owners.Select(s => s.FullName).Where(w => w.Type == "Manager")

Any help is greatly appreaciated.

Thanks.

jeudi 24 mars 2016

How can I load controller data into javascript array?

Hello everyone I am newbie,

I am developing an election app via MVC3(Due to some restrictions). I did everything. It works fine. However, I need some charts to visualize my app.

Found something, working fine with 'static numbers'. I want to load my own data which comes from database. I am not good at Javascript. Here is where I have troubles.

var barChartData = {
               labels: ["App1", "App2", "App3", "App3", "App4", "App5", "Soru6"],
               datasets: [
                                   {
                                       fillColor: "rgba(233, 78, 2, 0.9)",
                                       strokeColor: "rgba(233, 78, 2, 0.9)",
                                       highlightFill: "#e94e02",
                                       highlightStroke: "#e94e02",
                                       data: [65, 59, 90, 81, 56, 55, 40]
                                   },
                                   {
                                       fillColor: "rgba(79, 82, 186, 0.9)",
                                       strokeColor: "rgba(79, 82, 186, 0.9)",
                                       highlightFill: "#4F52BA",
                                       highlightStroke: "#4F52BA",
                                       data: [40, 70, 55, 20, 45, 70, 60]
                                   }
                               ]

           };

First, I want to load some labels into Labels array from db . (Table: User, Column Apps) Then, I want to load some data into data array. (Table UserQuestion, Column QuestionAnswerRate)

I am able to get both of these data via Model or ViewBag. However can't load into array.

How can I do this?

public ActionResult Index() {

        ViewBag.Mevzuatlar = _mevzuat.SelectAll(); //First Chart



        return View(_user.Find(f => f.Rol == true && f.KatildiMi == true)); //Second Chart
    }

stop create,update,details,delete T4 Template to automatically genrate

Currently I am working in Customize and modify original behaviour of codetemplate Here is picture of MvcControlWithContext

In the above link you can see this in MvcView folder have create,details,delete,edit etc. view...

what I am doing

Right click on controller folder -> Add -> Controller -> Mvc5 Controller With views using entity framework

it render all 5 views

what I want

I want to stop them from being render can I do this ?

Note: i can modify the output of views but do not want details views so can i stop them from being create. if I delete the details view it still create please help me

Thanks

mercredi 23 mars 2016

MVC: Password value is seen from page source

I have a very simple password box bind to a property. When user edit existing password, it displays as "......." we all know. The code is:

@Html.PasswordFor(m => m.Password, new { value = Model.Password })

However if you righ click and 'view page source', you will see the password in plain text, which seems cause security concern. Is there anyway to hide that? Thanks a lot!

Render Razor Code inside HTML

I have some HTML that is saved on my DB, this is later modified and saved on a variable and finally it's printed on my view using @Html.Raw( Model.Page.Html ).

The problem is, this HTML possess some Razor codes like ViewBag.Email. How could i render this Razor code before printing the HTML ? I have already tried to put that on an Partial View and call it inside the HTML and then print it but it also won't work.

Some people pointed me the RazorEngine lib but i couldn't make that work, i installed the version 3.7.7 but the documentation is a little confusing for me.

If RazorEngine is my best option could anyone please include an example of how to render my HTML before printing it ?

mardi 22 mars 2016

memebreship.validateuser() returns false

In my Project If I entered a user Information Through Application Membership.validateUser() returns true but if I Insert A User Information Through a stored Procedure it returns false.why it is happening?

What are the Pros and Cons of using JQuery DatePicker/datetimepicker?

We are using jQuery DatePicker/DateTimePicker as well as Kendo UI dateTimePicker in our project. But now we need to implement one of them in the entire project. We got to implement a lot of extension methods to suit our requirements. So which among the two would prove to be a wiser choice ? As we know Kendo uses jQuery Validation in MVC we need to implement validations manually.

lundi 21 mars 2016

Unable to Display PDF file in Browser using MVC

I am facing an issue, in which I am not able to display PDF file in any web browser using MCV. I am not getting any error but just shows me D�*�PV�B/���S�zi ������������

I am using Bootstrap, Jquery and MVC. Bellow is sample code to display PDF.

    public FileResult OpenDocument(int Id)
    {
        byte[] data = lst.File; // retrieve byte from db.
        string mimeType = "application/pdf";
        if (mimeType != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", data.Length.ToString());
            //Response.BinaryWrite(data);
        }
        return File(mimeType, mimeType);
    }

Please help me or Suggest me. Thanks in advance.

How to add framework MVC 3 .NET 4 to monodevelop? Ubuntu 14.04

I have project from my client with ASP.NET, in their server they have IIS 6, and the requirements are .NET 4 and MVC 3. But I don't have windows os, I use ubuntu 14.04, and install monodevelop (http://ift.tt/1C2pwIU). I get version 5.1 monodevelop. enter image description here

Nah.. and then I try to create new solution project in monodevelop. I choose ASP.NET MVC project And then I running it.. but wush.. I got MVC 5.2

I've looked it up on google many times, "how to add MVC3 project to monodevelop", but I could not find what I'm looking for. And I almost frustrating. Please.. anyone can give me solution for my problem??

Thanks..

dimanche 20 mars 2016

Change the x,y positions of the elements/nodes using dagre JS

Can we change the x,y positions of the nodes and edges of dagre layout?

My requirement is to right align the nodes and edges of the layout with type of the node. Is this possible with dagre?

If yes, Let me know how can it be achieved?

Thanks in advance

samedi 19 mars 2016

How to export data with Grid.mvc in ASP.NET MVC

I have data in Grid.MVC and now i want export data after filted or sorted. I don't know how to do it. Please help me. Thank all. I need to export the data in Grid.MVC to Excel. I used the solution in this link: http://ift.tt/1Ly8QQT It working but i have a problem, i want export data after filted or sorted.

Multiple OutputCache in MVC

Can we have multiple OutputCache defined for an action? For ex. say I want to store OutputCache copy one in Server and another one in Client. I know that this we can do with Location=OutputCacheLocation.ServerAndClient but say I want to specify different Duration for Client and Server, having a bigger Duration for Server and smaller Duration for Client? So with this requirement can I have it as below?

[OutputCache(Duration = 3600, Location = OutputCacheLocation.Server, VaryByParam = "propertyID", NoStore = true)] //Server Cache for 1 hour
[OutputCache(Duration = 600, Location = OutputCacheLocation.Client, VaryByParam = "propertyID", NoStore = true)] //Client Cache for 10 minutes
public ActionResult GetProjectDetails(string propertyID)
{
    //some code
    return View(model);
}

Will this be valid to have or MVC takes latest OutputCache into consideration?

In asp.net mvc How to use and style links as html helper links

Im building a website using Asp.Net Mvc. Ive a few links and buttons styled using html and css. I need to convert these into htmlhelper links. Please help. Below is my html and css code.

index.html

<div class="header">
    <div class="container">
        <div class="menu">
            <ul class="nav">
                <li class="active" role="presentation"><a href="#">Home</a>   </li>
                <li role="presentation" class="dropdown">
                    <a class="dropbtn" href="#">Destinations</a>
                    <div class="dropdown-menu">
                        <a href="#">Attractions</a>
                        <a href="#">Popular Destinations</a>
                    </div>
                </li>
                <li role="presentation"><a href="#">Seasons</a></li>
            </ul>
        </div>

 <div class="main">
    <div class="container">
        <a href="Reach.cshtml" class="btn btn-default" role="button">Explore</a>
    </div>
</div>

style.css

.header .menu{
float:right;
}
.header .menu ul{
    list-style-type:none;
    display:inline-block;
}
.header .menu ul li{
    display:inline-block;
    color:#f2f2f2;
    margin-right:20px;
}
.header .menu ul li a{
    color:#f2f2f2;
}
.header .menu ul li.active{
    background-color:#7b278e;
    color:#f2f2f2;/*#0d4869;*/

}
.header .menu li a:hover{
    background-color:#7b278e;
    color:#f2f2f2;
}

li.dropdown{
    display:inline-block;
}
.dropdown-menu{
    display: none;
    position: absolute;
    background-color: #7b278e;
    min-width: 160px;
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
}
.dropdown-menu a{
    text-decoration:none;
    display:block;
    text-align:left;
    color:#f2f2f2;
    padding:12px 16px;
}
.dropdown-menu a:hover{
    background-color:#7b278e;
    color:#0d4869;
}
.dropdown:hover .dropdown-menu{
    display:block;
}

.main .btn{
background-color:#7b278e;
color:#f2f2f2;
margin-left:600px;
}

Im aware of using @Html.ActionLink, but ive no idea about styling the links. Please advice.

vendredi 18 mars 2016

@Html.DropDownList() SelectListItems disabled &/ Select

SelectList items appear to have a Selected & Disabled attribute. But when I drop my SelectList into a DropDownList neither of these two attributes ever show up in the HTML no matter what I try.

Please understand my page has more of a purpose than to narrowly exists to host the dropdown. This dropdown is one of many fields which constitute the purpose of the page ~ therefore a mush larger model is already attached to the page.

I've implemented this dropdown as being populated from a ViewBag. Is there perhaps a better way to create this one field than to use a ViewBag?

How do I create a list for a dropdown that can dynamically have enabled/disabled items in the list? I only need to set the list item disabled attribute when the page/object is created ~ I don’t need to the dynamically change the disabled attribute on list items in the any point in the middle of the life of the page.

MVC Cloning Controller Context

I'm having some problem to implement a clonable version of the ControllerContext. I need this because i'm trying to cache it and access it later in a part of my system that can't access this information and i can't pass it as a parameter. This is what i have achieved:

public class ControllerContextClonable : ControllerContext, ICloneable
{
    public object Clone()
    {
        var cloneContext = (ControllerContext)MemberwiseClone();

        return cloneContext;
    }

    public static List<ControllerContextClonable> ToList( ControllerContextClonable context )
    {
        return new List<ControllerContextClonable>{ context };
    }
}

The problem is: When i'm caching it, i have the ControllerContext but i need to pass to my caching method a ControllerContextClonable object. How can i convert my ControllerContext to ControllerContextClonable ? This is how i'm trying to pass it and the caching methods:

//If i try to call my method with the safe convertion i get a null object
CacheMethods.SetContextCache( context as ControllerContextClonable );

public static void SetContextCache( ControllerContextClonable context, string cacheKey = "SiteContext" )
{
    CacheList<ControllerContextClonable>.RemoveCache( cacheKey );
    CacheList<ControllerContextClonable>.Add( new List<ControllerContextClonable> { context } );
    CacheList<ControllerContextClonable>.CacheIt( cacheKey );
}

public static ControllerContextClonable GetCachedContext( string cacheKey = "SiteContext" )
{
    CacheList<ControllerContextClonable>.LoadCached( cacheKey );

    if( CacheList<ControllerContextClonable>.LoadCached( cacheKey ) )
    {
        return CacheList<ControllerContextClonable>.DataList.FirstOrDefault();
    }

    return null;
}

How can i correctly convert the executing ControllerContext to my ControllerContextClonable class to be used on the cache ? Also if i'm doing this wrong could anyone point me the right way ?

Weird filename when downloading file from Internet Explorer

I have a webapplication that is set up with a link, and when this link is pressed then a file is downloaded. The file location right now i is on my own HDD. It works when I download the file from Google Chrome, but when i use IE i get a weird scrambled filename. This is my code:

[HttpGet]
public HttpResponseMessage GetFile(string filename, string environment)
{
    _requestLogger.LogRequest(Request);

    var validateResult = new InputValidator().ValidateInput(filename);
    if (!validateResult.IsValid)
    {
        return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = validateResult.ErrorMessage };
    }

    filename = SanitizeFileName(filename);

    var filePath = _settings.ResolveFilePath(environment, filename);

    if (!File.Exists(filePath))
    {
        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

    //Get file
    var stream = new FileStream(filePath, FileMode.Open);

    //Create result
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    //Add content to result
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
} 

Here is a link to an image of the weird filename

I cant seem to figure out why this is happening. Can anyone help ?

jeudi 17 mars 2016

How to change slider images dynamically to particular date in mvc

  • i have header slider banner in MVC it show promotion images. how can i change this slide to dynamic.

example :promotion date 05-01-2016 to 03-02-2016 it should show some promotion images

after the promotion date end it display another promotion images. how can we do this in dynamically in Asp.net Mvc.

Please help

Thanks in Advance.

Custom filtering on Jquery Data table and reassigning AjaxSource

My application is in Asp.net MVC3, i have added Jquery Datatable, it works fine on default load. But I want to add custom filtering to the Index page on which the data-table is implemented. Below is the sample code, but this is exactly how I implement my index View with Data-table.

  var oTable1 = $('.My_Table_Class').dataTable({
            "bServerSide": true,
            "sAjaxSource": "/CityMaster/AjaxCityFill",
            "bProcessing": true,
            "sScrollY": "300px",
            aaSorting: [[0, 'desc']],
            "b$UI": true,
            "bAutoWidth": true,
            "sPaginationType": "full_numbers",
            "sDom": '<"dtShowPer"l><"dtFilter"f><"#dataTables_filter_search_button"><"dtInfo"i><"dtPagination"p><"dtTables">rt<"dtInfo"i><"dtPagination"p><"F">',
            "oLanguage": {
                "sLengthMenu": "Display _MENU_ records per page",
                "sZeroRecords": "Nothing found - sorry",
                "sInfo": "Showing _START_ to _END_ of _TOTAL_ records",
                "sInfoEmpty": "Showing 0 to 0 of 0 records",
                "sInfoFiltered": ""
            }
        });

The Above method will get the data from query like this

"Select * from CityMaster"

There will be selection filter above the Index View like CountryName, CityName, CountryCode What i want to achieve is:

  1. I want to reassign url to sAjaxSource which will get the data from a method that will accept parameters like "CountryName" , "CityName" like this

    sAjaxSource": "/CityMaster/AjaxCityFillWithFilter?CountryName=India&CityName=Maharashtra,
    
    

Below are the things that i have tried

 1. var oSettings = oTable1.fnSettings();
    oSettings.sAjaxSource  = "/CityMaster/AjaxCityFillWithFilter?  CountryName=India&CityName=Maharashtra;

 2. oTable1.ajax.url("/CityMaster/AjaxCityFillWithFilter?        CountryName=India&CityName=Maharashtra).load();

None of the above methods are working.

tree-view using some thing like text-area

I want to show my tree-view in text-area or something like that. I want tree-view in a small room with scroll function. what should i use?

How to call a Bootstrap Modal in ASP.Net MVC?

I created a sample project that whenever i click a button link, it should call a View which contains my Modal Pop Up. I was able to call the View but the modal in it doesn't appear. What can i do to fix it? Can anybody help me please?

This is my code. The link should call the "Create_Business_Info" that contains the modal

@{
    ViewBag.Title = "Business_Info";
}

<div class="container-fluid">

    <a href='@Url.Action("Create_Business_Info", "Maintenance")'>
    Business INFO!
    </a>

    </div>

<script>
    $(document).ready(function () {
        $("#myModal").show();

    });

</script>

This is the code of the Modal that should appear.

<div id="myModal" class="modal fade" data-backdrop="static" data-     keyboard="false">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header modal-header-employee">

            <button type="button" class="close" data-dismiss="modal">&times;    </button>
            <h3 class="modal-title">Business Information</h3>
        </div>
        <br />

        <div class="modal-body">

            <div class="form-group row">
                <label class="col-xs-4 col-sm-offset-1 col-sm-4 control-label">Business Name:</label>
                <div class="col-xs-8 col-sm-6">
                    <input class="form-control" type="text">
                </div>
            </div>

            <div class="form-group row">
                <label class="col-xs-4 col-sm-offset-1 col-sm-4 control-label">Address:</label>
                <div class="col-xs-8 col-sm-6">
                    <textarea class="form-control" rows="5"></textarea>
                </div>
            </div>

            <div class="form-group row">
                <label class="col-xs-4 col-sm-offset-1 col-sm-4 control-label">Contact No:</label>
                <div class="col-xs-8 col-sm-6">
                    <input class="form-control" type="text">
                </div>
            </div>

            <div class="form-group row">
                <label class="col-xs-4 col-sm-offset-1 col-sm-4 control-label">Website:</label>
                <div class="col-xs-8 col-sm-6">
                    <input class="form-control" type="text">
                </div>
            </div>

            <div class="form-group row">
                <label class="col-xs-4 col-sm-offset-1 col-sm-4 control-label">Email Address:</label>
                <div class="col-xs-8 col-sm-6">
                    <input class="form-control" type="text">
                </div>
            </div>
        </div><!--modal body-->
        <div class="modal-footer">
            <button type="button" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-default">Clear</button>

            </div><!--modal footer-->
        </div><!--modal content-->
    </div><!--modal dialog-->
</div><!--business_info-->



<script>
    $(document).ready(function () {
        $("#myModal").show();

    });



</script>

Someone help me please. Thank you so much.

mercredi 16 mars 2016

Jquery Dialog MVC 3 Post form

I'm currently learning Jquery and I have the following code to open a dialog box and display a partial view. The dialog box opens but does not display partial view.

How do I:

  • display the partial view
  • submit the form
  • close dialog box

        $(document).ready(function ()
    
    {
        $(function() {
    
            $("div.dialog").dialog(
                {
                    autoOpen: false
                }
            );
    
            $("a.opendialog").click(function ()
            {
                $("div.dialog").dialog("open");
                var newTitle = $(this).attr("title");
                $("div.dialog").dialog('option', 'title', newTitle);
                var urlToInvoke = $(this).attr("data-url-to-invoke");});
    
        })
    })
    
    

mardi 15 mars 2016

Angularjs: Cannot display array items using ng-repeat

I am using AngularJs to retrieve the data from ASP.Net Controller. The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:

  var app = angular.module('Appp', []);
        app.controller('metadataCtrl', function ($scope, $http) {

       
            $scope.lookupItems = {};
            $http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
                $scope.lookupItems = response;
                console.log($scope.lookupItems);
            },
               function (error) { alert("error"); });

           // console.log($scope.listItems);

        });
   <form name="myForm" ng-controller="metadataCtrl" class="my-form">
   
          <div ng-repeat="item in lookupItems">
              {{$index}}
              {{item.ListValueID}}
        </div>
   </form>

The Json Retrieved from the server:

[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
 
 {"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
 
 
 {"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]

Nested webgrid MVC 3, what is wrong?

I don't understand why my code doesn't work... I'm trying to do some nesting webgrid... See Below:

@dataTopGrid.GetHtml(tableStyle: "webgrid-stock-table",
    headerStyle: "webgrid-stock-header",
    alternatingRowStyle: "webgrid-stock-alternating-row",
    rowStyle: "webgrid-stock-row-style",
    mode: WebGridPagerModes.All,
    columns: dataTopGrid.Columns(
    dataTopGrid.Column(columnName: "Magasin", header: "Magasin", canSort: true),
    dataTopGrid.Column(columnName:"TypeMagList", format : (item) =>
        {
            WebGrid subGrid = new WebGrid(item.TypeMagList);
            return (subGrid.GetHtml(
                columns: subGrid.Columns(
                    subGrid.Column("LotsList", format: (item2) =>
                    {
                        WebGrid subSubGrid = new WebGrid(item2.LotsList);
                        return subSubGrid.GetHtml(columns:
                        subSubGrid.Column(columnName: "ArticleRef.Name", header: "Article", canSort: true)
                        ,
                        subSubGrid.Column(columnName: "Name", header: "Lot", canSort: true),
                        subSubGrid.Column(columnName: "StockDispoStr", header: "Quantité", canSort: true),
                        subSubGrid.Column(columnName: "ArticleRef.UniteMesure", header: "Unité", canSort: true),
                        subSubGrid.Column(columnName: "StatutLot", header: "Statut", canSort: false)
                        );
                    }
                                        )
                                  )
                                ));

        })
        )
)

The compilator says :CS1738: Named argument specifications must appear after all fixed arguments have been specified

Could you please help me to understand what is wrong? Thanks for your help!

lundi 14 mars 2016

Unable to login to the MVC3 application in client server Once server is restarted working fine. Its occurring every 15 days

We hosted MVC3 application in client server. After hosting working fine. But after few days we are unable to login to the application. We get the login page, once we enter the credentials it redirects to login page. To resolve this issue we restart the server its working fine. This issue occurring every 15 days.

use of unassigned local variable mvc model

There is an error occured when i declare variable of model class EmailModel use of unassigned local variable

EmailModel emailModel;

                string Data = RenderPartialViewToString(this, "ChangePasswordemail", emailModel);

                string name = WebSecurity.CurrentUserName;
                Data = Data.Replace("Name", emailModel.FirstName);
                Data = Data.Replace("Email", emailModel.Email);

How to save items of field list table in database in controller post method?

I am working student issue book form.in that i am getting values,i have field list table in which i added multiple books of a particular student,when i am submitting it is saving only single book.In database i have create multiple columns to save book id's of each book in each column.how to solve this. here is my controller post method

[HttpPost]
        public ActionResult Create(Student_Issue_Book Student_Issue_BookObj)
        {
            var rollNoRecord = db.Student_Issue_Book.FirstOrDefault(a => a.Delete_Flag == false && a.Issue_Return_Id == Student_Issue_BookObj.Issue_Return_Id );
            if (rollNoRecord == null)
            {
                Student_Issue_BookObj.Last_Updated_By = CurrentUserID;
                Student_Issue_BookObj.Last_Updated_Date = DateTime.Now.ToUniversalTime();
                Student_Issue_BookObj.Created_By = CurrentUserID;
                Student_Issue_BookObj.Creation_Date = DateTime.Now.ToUniversalTime();
                // ViewBag.EMPLOYEE_ID = new SelectList(db.Student_Registration, "Registration_Id", "Student_First_Name");
                if (_CRUDrepository.CreateNewObject(Student_Issue_BookObj))
                {
                    return RedirectToAction("Index");
                }
            }
            FillViewBag();
            //ModelState.AddModelError("", "The authentication provider returned an error. Please verify your entry and try again.");
            ModelState.AddModelError("", "This book is not there in library.");
            return View();
        }

dimanche 13 mars 2016

How to set status on Custom Authorize attribute in ASP.NET Web API/MVC

Right now when we use authorize attribute with asp.net Web API if token unauthorized then it is sending back to the login screen and returning status 200. Instead of that, we want to have status 401 and our custom view. How we can do it.

I have already tried doing below but does not have any success.

public class CustomAPIAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response.StatusCode = HttpStatusCode.Unauthorized;
        base.HandleUnauthorizedRequest(actionContext);
    }
}

Any help will be appreciated.

Ho to convert a mysql datetime string to c# datetime string

i get "10/1/15" 12:00:00 AM time string from mysql db. how to convert this to a c# system.datetime by the parseExact method?

Want generic chart helper to display in partial views

Want to show multiple charts(Bar,Pie) on asp.net mvc webpage using partial views. I want centralized charts for my application.

public ActionResult DrawChart()
{
    var chart = new Chart(width: 300, height: 200)
        .AddSeries(
            chartType: "bar",
            xValue: new[] { "10 Records", "20 Records", "30 Records", "40 Records" },
            yValues: new[] { "50", "60", "78", "80" }
        ).GetBytes("png");
    return File(chart, "image/bytes");
}

samedi 12 mars 2016

Dropdown with selectedValue is not working in MVC

I am binding the dropdown list from a viewbag object. while converting the object to select list am using the 4th overload method which has list, string, string, object as param.

The selection of dropdown is not working. the 4th param of this SelectList is not working.

Here is the code:

 @Html.DropDownList("mylist", new SelectList(ViewBag.MyList, "Value", "Text", selectedValue: "3"));

ViewBag.Mylist contains a list of my object:

public class DDL
{
    public string SelectedItem { set; get; }
    public List<MyList> list { set; get; }
}

public class Values
{
    public string Text { set; get; }
    public string Value { set; get; }
}

Let me know why this overloaded method is not working? OR am i using this wrongly?

vendredi 11 mars 2016

How do i return a value form method of controller to particular view?

I have method in controller,in that i getting on value form database.I need that value in one of the view of that controller ,how to do this? here is my method

public ActionResult BookSet(long? ClassId)
{
    List<BKselect> Bk = new List<BKselect>();
    Bk = (from a in db.Student_Book_Allow_Quantity
          where a.Class_Id == ClassId
          select new BKselect()
          {
              Class_Id = a.Class_Id,
              Student_Book_Allow_Quantity_Id = a.Student_Book_Allow_Quantity_Id,
              Book_Quantity=a.Book_Quantity
          }).OrderBy(a => a.Student_Book_Allow_Quantity_Id).ToList();
    ViewBag.BKselect = Bk.ToList();
    return View();
}

webgrid paging click makes grid state goes wrong

screen shot shows webgrid state after paging number clicked

Paging working, grid add/update/delete working as expected. Ajaxcontainer working fine which replaces only grid on page click not entire page replaced with only webgrid. Only thing is grid mode is collapsed? where i am missing.

Partial View

<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
    <a href="javascript://" id="btnAddNew">Add New(+)</a>

    @{
        var grid = new WebGrid(source: Model, canPage: true, defaultSort: "QuestionID", rowsPerPage: 3, ajaxUpdateContainerId: "gridposition");
    }

    <div id="gridContent" style="padding-right: 30%;">
        @grid.GetHtml(htmlAttributes: new { id = "result" },  
         tableStyle: "wGrid",
         fillEmptyRows: false,
         alternatingRowStyle: "alt",
         headerStyle: "gridHeader",
         mode: WebGridPagerModes.All,
         firstText: "<< First",
         previousText: " < Previous",
         nextText: "Next >",
         lastText: "Last >>",
        emptyRowCellValue: null,
    columns:
        grid.Columns( ....

Partial view contains script for grid button click events and also this line

 $('.edit-mode').hide();

Main View

var url = '@Url.Action("Filter","AddSurveyQuestions")';
        $.get(url, { campaignid: campaignid, languagename: languagename }, function (result) {

            $('#SurveyViewGrid').html(result);
        }); ....

Main View calling partial view

<div id="SurveyViewGrid">
                @Html.Partial("SurveyView", Model.SurveyQuestions)
            </div>

jeudi 10 mars 2016

IE only form submit error: The page was not displayed because the request entity is too large

I have a c# mvc application with a form.

The form has an input[type=file] that i use to upload smallish jpg images around 10kb to about 700kb.

Everytime i do a form submit in Chrome, the submission works. There are no errors being returned by the server.

If however i do the exact same form submit with the same data in Internet Explorer, i get a 413 error (The page was not displayed because the request entity is too large.)

Any ideas where i need to look to resolve this?

mercredi 9 mars 2016

can we use html tags in asp.net mvc

I want to use following html tags in asp.net mvc,is it possible?

<form action="demo_form.asp">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

Export to excel using Response.TransmitFile() is not working properly

I have written some content to excel file using openxml and I tried to transmit the file using reponse.transmitfile but it is nor working. I am attaching piece of code which I used to transmit excel file as response. Please see the attached code. When I debug the code it is not throwing any exception also.

Code:-

string filename = "Book1.xlsx";

            try
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                Response.ClearContent();
                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Length", Server.MapPath("~/" + filename).Length.ToString());
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.TransmitFile(Server.MapPath("~/"+filename));
                Response.Flush();
                Response.End();
            }
            catch (Exception e) {
                Console.WriteLine(e);

            }

Null reference Exception when i using html worker

Parser Error

Hi:

When i use the html worker iam getting null reference exception error during convert the html page to pdf in mvc

iam getting error during parse into html worker

i dont know where iam getting null value,can any one pls help me to solve this issue

JQuery Dialog - Close from controller

I updated JQuery on an existing MVC 3 website application to jquery-2.1.4.js. The index page can create/update a profile through a dialog.

View Page

<a href="#" class="opendialog" title="update" data-url-to-invoke="@Url.Action("Update","Profile", new {Id = profile.Id})">Update</a>

<div id="newsform" class="dialog" title="Profile" data-height="350" data-width="570px">
        <div class="dialogcontent"></div>        
    </div>

$("a.opendialog").click(function ()
    {
        $("div.dialog").dialog("open");
        var newTitle = $(this).attr("title");
        $("div.dialog").dialog('option', 'title', newTitle);
        var urlToInvoke = $(this).attr("data-url-to-invoke");

        $.get(urlToInvoke, function (data)
        {
            $("div.dialogcontent").html(data);
            jQuery.validator.unobtrusive.parse("div.dialog");
        });
    });

Controller

if (profile.IsValid())
{
                return PartialView("UiDialogClose");

}

UiDialogClose

 <script type="text/javascript">
        $(document).ready(function () {
            $("div.dialog").html("");
            $("div.dialog").dialog("close");
        });
    </script>

Everything works exactly the same as before except when the save button is clicked and form is valid, the dialog closes but does not return the index page as it did before. It displays a blank create/update page.

Can this be fixed?

How to read properties of a document(Doc,Docx,XLS,XLSX) without using Interop as Office is not installed

How Can i read properties for example Title,Author of a document (doc,docx,ppt,pptx..) without using Microsoft.Office.Interop as Office is not installed in the pc

i could not able to use ajax cal to insert data without postback in mvc? please help me

actually i added model using ado.net entity datamodel,i want to insert data in database table without postback so that i used ajax and jquery but am not getting output please help me,am new to mvc ajax.

**this is my view file**
@model ajaxJquery.Models.register

@{
    ViewBag.Title = "Index";
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#Register").click(function () {
            //var studentid = $("#studnt_id").val();
            var Name = $("#name").val();

            var Qualification = $("#qualification").val();

            var Branch = $("#branch").val();

            var Gender = $("#gender").val();

            var State = $("#state").val();

            var LoginId = $("#login_id").val();

            var Password = $("#password").val();


                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("Index","Home")',

                    data: "{'name':'" + Name + "','studentId':'" + studentid + "','qualification':'" + Qualification + "','branch':'" + Branch + "','gender':'" + Gender + "','state':'" + State + "','loginid':'" + LoginId + "','password':'" + Password + "'}",
                    success: function (data) {
                        if (data == true) {

                            $("#divresult").text("recorded successfully");
                        }
                        else {

                            $("#divresult").text("couldnot save record");
                        }
                    },
                    error: function () {
                        //Show error message(if occured)
                        $('#divresult').text("Error: ");
                    }



                });

                return false;


            });



    });



    </script>
<h2>Index</h2>

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

    <fieldset>
        <legend>register</legend>

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

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

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

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

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

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

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

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

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


    </fieldset>
}
<div id="divresult"></div>
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

**and this is my controller**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ajaxJquery.Models;

namespace ajaxJquery.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Index( string name, string qualification, string branch, string gender, string state, string loginid, string Password)
        {
            ajaxcontext db = new ajaxcontext();
            register reg = new register();
            //reg.studnt_id = studentId;
            reg.name = name;
            reg.qualification = qualification;
            reg.branch = branch;
            reg.gender = gender;
            reg.state = state;
            reg.login_id = loginid;
            reg.password = Password;
            db.registers.Add(reg);
            db.SaveChanges();
            return View();
        }

    }
}

mardi 8 mars 2016

How to draw crystal report table(Box) based on database values

As shown the image, have to draw the table(Box) in crystal report based on the database values. height and width are fixed(14X72) for total table. and inside the small boxes varies the size based on database values. Please suggest how can i process.

Using MVC3 and JQuery to dynamically and mantain the DataAnnotations

I have a problem similar to this: Using MVC and JQuery to dynamically & consistently add values to a table , but the difference is:

I have table and I'm cloning the last row (to keep the same format) with: var $tableBody = $('#record').find("tbody"); $trLast = $tableBody.find("tr:last"); $trNew = $trLast.clone(); $trLast.after($trNew);

The rows are created succesfully, but the validations are binded to the first row (inputs, selects and textarea)

Inspecting the elment, are displayed:

    <td>
<!--Code generated with the jquery .clone() -->
    <input data-val="true" data-val-required="Es necesario agregar una fecha." id="Salidas_0__Fecha" name="Salidas[1].Fecha" type="datetime" value="" autocomplete="off" class="hasDatepicker input-validation-error">
    <span class="field-validation-valid" data-valmsg-for="Salidas[1].Fecha" data-valmsg-replace="true"></span>
    </td>

But the field-validation-valid is not binded to the input. Exist a way to do that?

How to generate .edmx from existing sql Server Database programmatically

i have an existant database ,and i want to know how to generate the model (.edmx) automatically from the controller . The question is how to generate the .edmx from a database with a bloc of code without using the wizzard if is it possible?

Process to debug existing mvc3 app that spins up and grabs memory

I've inherited an MVC3 website that when hit a few times spins up and eats up a ton of memory then hovers between 10 and 30% CPU. The site uses EF and returns a large chunk of JSON to a calling ascx.cs file in another site that calls it synchronously.

The site was built in Visual Studio 2012 and I have the source and the PDB files that were deployed to production. I pulled a dmp file of the W3WP at its peak and then have tried various ways to run it through windbg or Visual Studio and have concluded that I simply don't know where to start with this thing.

What diagnostic process should I use to determine what's causing the memory and cpu use? I have a version on a test server, but as I'm new with MVC, I'm not sure where to start debugging that either.

I'd like to at least start by being able to explain using the dump what the site is "doing" that accounts for the huge CPU and memory use.

Create table from 3 another mvc

I have tables enter image description here

I have in the View 3 dropdown list

  1. TeamName
  2. Username
  3. RoleName

When I click on Submit I need create table TeamUser in SQL try this - doesn t work

[HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        User user = new User();
        TeamUser tuser = new TeamUser();
        Session["userId"] = user.UserID;
        int.Parse(Session["userId"].ToString());
        Role rolUser = entity_dal.SelectRoleByName(Reguest.Form["roleId"]);
        tuser.RoleID = rolUser.RoleID; 
        tuser.CreateOn = DateTime.Now;
        tuser.TeamID = user.UserID;
        tuser.TeamID = int.Parse(Request.Form["teamId"]);
        try
        {
           entity_dal.InsertUser(tuser);
        }
        catch (Exception Exception) { ViewBag.error = Exception.InnerException + "--" + Exception.Message; }


        return View();
    }

and next View I need input table like (all users belong that Team)

| User Name | TeamName | Delete | Edit

Thank you

lundi 7 mars 2016

Errror in linking while using AddLink() method of DataServiceContext in Odata web api

In web api service I have two models Product and Supplier having one to many relationship between them...So when i am going to add Product and supplier and then want to create link between them it is throwing exception...

Here are Product and Supplier Models:

 public class Supplier
    {
        [Key]
        public string Key { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }



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

        [ForeignKey("Supplier")]
        public string SupplierId { get; set; }
        public virtual Supplier Supplier { get; set; }
    }

At client side i m using web api service to add product which is done in following function:

public void CreateProduct(ProductViewModel product)
      {
         var productToAdd = new ProductSupplierReference.Product();
         Mapper.Map(product, productToAdd);

        _container.AddToSuppliers(productToAdd.Supplier);
        _container.AddToProducts(productToAdd);
       _container.AddLink(productToAdd.Supplier, "Products", productToAdd);
       _container.SetLink(productToAdd, "Supplier", productToAdd.Supplier);
        var serviceResponce = _container.SaveChanges();
     }

Now the problem is Product and Supplier records are added in database but the mapping between these two objects has not been done..and it shows following error on page:

<m:error xmlns:m="http://ift.tt/1dtZymv">
<m:code/>
<m:message xml:lang="en-US">
No HTTP resource was found that matches the request URI 'http://localhost:61865/odata/Suppliers('hgfddyh')/$links/Products''.
</m:message>
<m:innererror>
<m:message>
No routing convention was found to select an action for the OData path with template '~/entityset/key/$links/unresolved'.
</m:message>
<m:type/>
<m:stacktrace/>
</m:innererror>
</m:error>

LTI Samples not working

i downloaded sample LTI files from this URL http://ift.tt/1X8ZviF

Then open new project and run the sample code the below error comes.

enter image description here

cannot create an instance using UserStore

I'm going to create a instance as follows.

var store = new UserStore<ApplicationUser>(new ProjectEntities());

but getting following error

The type 'project_name.Models.ApplicationUser' cannot be used as type parameter 'TUser' in the generic type or method 'UserStore'. There is no implicit reference conversion from 'project_name.Models.ApplicationUser' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'.

'using' scope in 'foreach'

I'm profiling a Razor template (MVC3). It has several nested levels, roughly (pseudocode):

var profiler = MiniProfiler.Current;
var report = ViewBag.report as IEnumerable<Question>;

using (profiler.Step("Parent template"))
{        
    foreach (Question question in report)
    {
        using (profiler.Step("Question " + question.Id))
        {
            foreach (Question subquestion in question)
            {
                using (profiler.Step("Subquestion " + subquestion.Id))
                {
                   ....
                }
            }
        }
    }
}

Only the top level works. Not the nested ones. I tried redeclaring var profiler = MiniProfiler.Current; with different variable names in each level to prevent name clashes, to no avail.

How would I do it?

ASP .MVC null reference error for foreach row

controller

namespace CodeFirstApproach.Controllers
 {
   public class StudentController : Controller
   {
    //
    // GET: /Student/
    StudentContent objContext;
    public StudentController()
    {
         objContext=new StudentContent();
    }


    public ActionResult Index()
    {
        var students = objContext.students.ToList();
        return View();
    }

    public ViewResult Details(int ID)

    {
        Student student = objContext.students.Where(x => x.ID == ID).SingleOrDefault();
        return View(student);
    }
    #region Create Student
    public ActionResult Create()
    {
        return View(new Student());        
    }
    [HttpPost]
    public ActionResult Create(Student student)
    {
        objContext.students.Add(student);
        objContext.SaveChanges();
        return RedirectToAction("Index");
    }
    #endregion
    #region Edit Student
    public ActionResult Edit(int ID)

    {
        Student student = objContext.students.Where(x => x.ID == ID).SingleOrDefault();
        return View(student);
    }
    [HttpPost]
    public ActionResult Edit(Student model)
    {
        Student student = objContext.students.Where(x => x.ID == model.ID).SingleOrDefault();
        if (student != null)

        {
            objContext.Entry(student).CurrentValues.SetValues(model);
            objContext.SaveChanges();
            return RedirectToAction("Index");


        }

        return View(model);

    }
    #endregion
    #region Delete Student

    public ActionResult Delete(int id)

    {
        Student student = objContext.students.Find(id);
        return View(student);

    }

    [HttpPost]
    public ActionResult Delete(int id, Student model)
    { var student = objContext.students.Where(x => x.ID == id).SingleOrDefault();
    if (student != null)
    {
        objContext.students.Remove(student);
        objContext.SaveChanges();


    }
    return RedirectToAction("Index");

    }

    #endregion

}

}

view on ActionResult Index() method @model


@model IEnumerable<CodeFirstApproach.Models.Student>

@{
  ViewBag.Title = "Index";
 }

 <h2>Index</h2>
 <p>
     @Html.ActionLink("create new ", "Create");
 </p>
  <table style="width:100%;">
<tr>
    <th style="width:20%;">
        @Html.DisplayNameFor(model=>model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model=>model.Email)
    </th>
    <th>
        @Html.DisplayNameFor(model=>model.Class)
    </th>
    <th>
        @Html.DisplayNameFor(model=>model.Address)
    </th>
    <th>
        @Html.DisplayNameFor(model=>model.Mobile)
    </th>


</tr>
  @foreach (var item in Model)
{ 
 <tr>
     <td>
         @Html.DisplayFor(modelItem => item.Name)
     </td>
     <td>
         @Html.DisplayFor(modelItem => item.Email)
     </td>
     <td>
         @Html.DisplayFor(modelItem => item.Class)
     </td>
     <td>
         @Html.DisplayFor(modelItem => item.Address)
     </td>
     <td>
         @Html.DisplayFor(modelItem => item.Mobile)
     </td>
     <td>
         @Html.ActionLink("Edit", "Edit", new { id= item.ID })|
         @Html.ActionLink("Details", "Details", new { id= item.ID })|
         @Html.ActionLink("Delete", "Delete", new { id= item.ID })|
     </td>
 </tr>
}

two Model class StudentContent.cs

namespace CodeFirstApproach.Models
{
public class StudentContent:DbContext
{
    public StudentContent()
        : base("name=DBConnectionString")
    { 

    }
    public DbSet<Student> students { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().HasKey(b => b.ID);
        modelBuilder.Entity<Student>().Property(b =>     b.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        base.OnModelCreating(modelBuilder);
    } 

  }
 }

And Student.cs

      namespace CodeFirstApproach.Models
{
public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Class { get; set; }
    public string Address { get; set; }
    public string Mobile { get; set; }

      }

   }

I am getting null reference exception in foreach row

I already tried If(Model != null ) for the foreach loop , butits giving me parser error

Please help .

dimanche 6 mars 2016

how to login with facebook using facebook csharp sdk in asp.net mvc?

i want to implement facebook login system in my webpage.but did not succeed.below i put my code that i write:

 private Uri RedirectUri
    {
        get
        {
            var uriBuilder = new UriBuilder(Request.Url);
            uriBuilder.Query = null;
            uriBuilder.Fragment = null;
            uriBuilder.Path = Url.Action("FacebookCallback");
            return uriBuilder.Uri;
        }
    }


    [AllowAnonymous]
    public ActionResult Facebook()
    {
        var fb = new FacebookClient();
        var loginUrl = fb.GetLoginUrl(new
        {
            client_id = "appid",
            client_secret = "appsecret",                
            redirect_uri = RedirectUri.AbsoluteUri,
            response_type = "code",
            scope = "email"
        });

        return Redirect(loginUrl.AbsoluteUri);
    }

    public ActionResult FacebookCallback(string code)
    {
        var fb = new FacebookClient();
        dynamic result = fb.Post("oauth/access_token", new
        {
            client_id = "appid",
            client_secret = "appsecret",
            redirect_uri = RedirectUri.AbsoluteUri,
            code = code
        });

        var accessToken = result.access_token;


        Session["AccessToken"] = accessToken;

        // update the facebook client with the access token so
        // we can make requests on behalf of the user
        fb.AccessToken = accessToken;

                  dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
        string email = me.email;
        string firstname = me.first_name;
        string middlename = me.middle_name;
        string lastname = me.last_name;


        FormsAuthentication.SetAuthCookie(email, false);
        return RedirectToAction("Index", "Home");
    }

but i got this error

(OAuthException - #1) Error validating client secret.

and i am using in this code client_id = my appid and client_secret = my appsecret key are used so please help me solved this problem.

Add extra data as part of url and not as parameter

So I've read about routes in MVC and configured according to what's mentioned in other posts.. So my intention is to generate url as below:

http://ift.tt/1U51tl1

with this intention I've configured my RoutesConfig.cs as below:

routes.MapRoute(
      name: "AdminMessage",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Admin", action = "Messages", id = UrlParameter.Optional }
);

Below is what my Controller looks like

[HttpGet]
public ActionResult Messages(string id)
{
    _model = new AdminViewModel();
    _userName = Convert.ToString(HttpContext.User.Identity.Name);
    ViewBag.Page = "Messages";
    _model = PrepareLayoutModel(_userName, "Messages");
    return View(_model);
}

And I use Url.Action to generate url as below:

<a href="@Url.Action("Messages", "Admin", new RouteValueDictionary(new {message.MessageID}))"></a>

But it always generates Url as http://domainname/controller/action?messageID=SDc@#123#2@, instead I want to generate it as http://domainname/controller/action/SDc@#123#2@. So what is the way I can get this done?

samedi 5 mars 2016

C# ASP.NET MVC @Url.Action does not exist in the current context

I know there can be some peculiarities in Visual Studio where it highlights @URL as not existing in the current context, but it still works. The problem I have however I think is different.

I an writing an application at the moment, I have completed a numerous admin screens all within there own area. The main area until now only had a ViewStart pointing to a _Layout which detected if you were logged in or not displayed a login page (which works) if you aren't and a series of hyper links if you are that take you to the admin pages - which all work.

In the _Layout the @Url is highlighted as does not exist in the current context - but works fine.

Now I have started writing the main area, so have added an Index.cshtml, this has a @model which is highlighted as does not exist in the current context, but I am able to access the data within without issue.

The problem is any anchor I add in the page and set the URL using @Url.Action doesn't work, they all say does not exist in the current context and when you view the source of the page the href= is missing as it the URL.

If I manually code the href= it does appear in the source and does work.

This is really driving me mad, and has rather stopped me in my tracks so any idea would be gratefully received.

Database First with Multiple Tables with Foreign Keys in a Single View

I have two tables department and teacher like this:

Department table (DeptID is the primary key)

DeptID | DeptName
 1         P
 2         C
 3         M

Teacher table (DeptID is a foreign key)

   DeptID | TeacherName
    1         ABC
    1         PQR
    2         XYZ

I have used database first approach to create a single model out of these two tables. I want to display both details in a single view like this:

TeacherName | DeptName
    ABC          P
    PQR          P
    XYZ          C

I tried to create controllers using scaffolding but it would provide views and CRUD operations for a single table in the model.

Is there any method using which I can map these two tables together in a single view ?

MVC3 - Return multiple Actions in Layout from layout controller

I have two actions in my shared layout, main menu and footer that return PartialViews -

@Html.Action("MainMenu", "Layout", new { area = "" })    
...    
@Html.Action("FooterMenu", "Layout", new { area = "" })

But I am getting the error -

"A single instance of controller 'Site.Controllers.LayoutController' cannot be used to handle multiple requests"

How do I get around this?

C# mvc3 deleting and reading table not updating new table in Entity Framework

I am working on mvc3 web application and using database with the help of entity framework.

First I added all the tables in EF and it were added correctly. Recently I made changes in one table and I wanted to update that table in EF.

So, I first deleted that table from EF and then tried to update EF using "Update model from database..." option.

I can see updated table under the Add tab. but when I click on Finish button, it not being added to EF.

I checked my web.config file. Database name and connection string is correct.

Thanks in advance.

vendredi 4 mars 2016

How to disable custom controller Action on header click of webGrid?

I have the following tab links which will change the data displayed in the webgrid as below,

following the cshtml file for the same,

 <div class="top-grid">
<div class="container">
    <div class="col-md-2">

        <p>
            <a href="#" id="EligiblePayLink">ELIGIBLE FOR EARLY PAY</a>
    </div>
    <div class="col-md-2">
        <h2>@Model.SupplierInitialPage.PendingInvoicesCount</h2>
        <p>
            <a href="#" id="PendingApprovalLink">PENDING APPROVAL</a></p>
    </div>
 </div>
<div class="clearfix">
</div>
</div>
 <div class="bottom-grid" id="InvoiceGridContents">

</div>

Below is the partial view with its controller class,

 WebGrid grid = new WebGrid(Model.EligiblePayInvoices, canPage: true, rowsPerPage: recCount);
        grid.Pager(WebGridPagerModes.All);

        @grid.GetHtml(

                 tableStyle: "table", // applying style on grid

        fillEmptyRows: true,
    //show empty row when there is only one record on page to it will display all empty rows there.       
        headerStyle: "header", //applying style.

        footerStyle: "grid-footer", //applying style.

        mode: WebGridPagerModes.All, //paging to grid 
        firstText: "<< First",
        previousText: "< Prev",
        nextText: "Next >",
        lastText: "Last >>",



        columns: new[]  // colums in grid
        {
            grid.Column(header:"DATE SUBMITTED",columnName: "DateSubmitted",style: "width-250px"), //the model fields to display
            grid.Column(header:"INVOICE #",columnName: "InvoiceNumber",style: "width-250px"),
            grid.Column(header:"INVOICE TITLE",columnName: "InvoiceTitle",style: "width-250px"),                
            grid.Column(header:"AMOUNT",columnName:"InvoiceAmount",style: "width-250px"),
            grid.Column(header:"PO#",columnName: "PONumber",style: "width-250px"),                
            grid.Column(header:"STATUS",columnName:"Status",format: item => Html.Raw(item.Status),style: "width-250px")
       })

And now the controller class,

   [HttpGet]
    public ActionResult ShowInvoiceGrid(int Id = 1)
    {
        var type = (PayInvoiceStatusType)Id;
        PayInvoiceViewModel _invoiceModel = objHelper.GetStreamPaySession(Session);
        if (_invoiceModel != null) 
            _invoiceModel = UpdatePayInvoiceViewModel(type);
        else
            _invoiceModel = CreateInitialPayInvoiceViewModel(type);

        return PartialView("_InvoiceGrid", _invoiceModel);
    }      

The problem is, when i click on the header of the webgrid, its triggering the custom controller action method and returning me only the grid partial view not the full page. Is there any idea?

jeudi 3 mars 2016

DropDownListFor Helper Makes Wrong Selection When Pre-Populating Null Values

I'm using MVC3 to populate an HTML form from a database. A number of the form elements are drop-down lists (selects). I'm using the "DropDownListFor" helper to pre-populate the lists and to perform data binding on POSTing of edited data (which works just fine).

I have a few nullable fields in the database where "NULL/Empty String" is a legitimate default value. So instead of "high", "medium" and "low" as 3 possible options, it uses "high", "medium" and "", where the empty string or null value is equivalent to "low". I've mirrored this behavior in the drop-down lists so that they provide corresponding text/value pairs.

The problem is with the model binding when it pre-populates the drop-down list and selects a default value to display in the DDL based on the value in the database. If the incoming database value is "high", it properly selects the "high" option. If the database value is "medium", it properly selects the "medium" option. BUT - if the database value is NULL/empty string, it selects the "medium" option and not the "low" option (or no "selected" at all, which is what I would have expected)! It's properly inserting the default optionLabel at the top of the list as per the DropDownListFor overload I'm using, but then it's promptly overwriting it by tagging 'selected="selected"' onto the "medium" option - where is that coming from?

Here is the code in the controller;

IcxPdcEditViewModel editViewModel = new IcxPdcEditViewModel()
{
    TwoPlusEmptyDDL = twoPlusEmptyList.TwoPlusEmptyList
};
return View(editViewModel);

where a helper sets up the DDL as follows;

public class PDCTwoPlusEmptyList
{
    public List<SelectListItem> TwoPlusEmptyList { get; set; }
    public PDCTwoPlusEmptyList()
    {
        this.TwoPlusEmptyList = new List<SelectListItem>()
        {
            new SelectListItem() { Text = "medium", Value = "medium" },
            new SelectListItem() { Text = "high", Value = "high" }
        };
    }
}

Here is the corresponding code in the View;

<td>Maintenance:</td>
<td><%= Html.DropDownListFor(model => model.Maintenance, Model.TwoPlusEmptyDDL, "low") %></td>

Here is the resulting HTML source code when the database value is NULL/empty string (confirmed);

<td><b>Maintenance</b>*:</td>
<td><select id="_Maintenance" name="Maintenance">
  <option value="">low</option>
  <option selected="selected" value="medium">medium</option>
  <option value="high">high</option>
</select></td>

One last thought, I am not using a ViewBag at all, and there are no conflicting names in my ViewData.

Any thoughts on what is causing this behavior?

Auto Mapping errors to individual properties

If I have an auto mapper such as TinyMapper or ExpressMapper configured to map DTOs to Models, and my DTO has notified me that, for example 'myDto.Email' has failed to update, is there a way to map that property back to the model (specifically in my case for ModelState.AddModelError purposes).

Here's a little pseudo code to hopefully clarify my need:

var mapper = SomeMapper.Register<MyModel, MyDto>();

var myDto = mapper.Map(myModel)
var errors = myDto.Update()
if(errors.Any())
{
  var error = errors.First();
  var property = memberConfiguration.GetMeTheModelPropertyFor(dto => dto.PropertyName= error.Property)

  ModelState.AddModelError(property.Name, error.Message);
}

So basically I'm asking which mapper can I achieve something like GetMeTheModelPropertyFor above and how?

Video Streaming for a IIS hosted MVC web application using HTML5 video

I was following article on http://ift.tt/1RJCnWA and wrote simple MVC application to stream large video files.

Here is my code with slight modifications to the code in that tutorial,

internal static void StreamVideo(string fullpath, HttpContextBase context)
    {
        long size, start, end, length, fp = 0;
        using (StreamReader reader = new StreamReader(fullpath))
        {

            size = reader.BaseStream.Length;
            start = 0;
            end = size - 1;
            length = size;
            // Now that we've gotten so far without errors we send the accept range header
            /* At the moment we only support single ranges.
             * Multiple ranges requires some more work to ensure it works correctly
             * and comply with the spesifications: http://ift.tt/1vK8VE4
             *
             * Multirange support annouces itself with:
             * header('Accept-Ranges: bytes');
             *
             * Multirange content must be sent with multipart/byteranges mediatype,
             * (mediatype = mimetype)
             * as well as a boundry header to indicate the various chunks of data.
             */
            context.Response.AddHeader("Accept-Ranges", "0-" + size);
            // header('Accept-Ranges: bytes');
            // multipart/byteranges
            // http://ift.tt/1vK8VE4

            if (!String.IsNullOrEmpty(context.Request.ServerVariables["HTTP_RANGE"]))
            {
                long anotherStart = start;
                long anotherEnd = end;
                string[] arr_split = context.Request.ServerVariables["HTTP_RANGE"].Split(new char[] { Convert.ToChar("=") });
                string range = arr_split[1];

                // Make sure the client hasn't sent us a multibyte range
                if (range.IndexOf(",") > -1)
                {
                    // (?) Shoud this be issued here, or should the first
                    // range be used? Or should the header be ignored and
                    // we output the whole content?
                    context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size);
                    throw new HttpException(416, "Requested Range Not Satisfiable");

                }

                // If the range starts with an '-' we start from the beginning
                // If not, we forward the file pointer
                // And make sure to get the end byte if spesified
                if (range.StartsWith("-"))
                {
                    // The n-number of the last bytes is requested
                    anotherStart = size - Convert.ToInt64(range.Substring(1));
                }
                else
                {
                    arr_split = range.Split(new char[] { Convert.ToChar("-") });
                    anotherStart = Convert.ToInt64(arr_split[0]);
                    long temp = 0;
                    anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : size;
                }
                /* Check the range and make sure it's treated according to the specs.
                 * http://ift.tt/oYi0Xv
                 */
                // End bytes can not be larger than $end.
                anotherEnd = (anotherEnd > end) ? end : anotherEnd;
                // Validate the requested range and return an error if it's not correct.
                if (anotherStart > anotherEnd || anotherStart > size - 1 || anotherEnd >= size)
                {
                    context.Response.ContentType = MimeMapping.GetMimeMapping(fullpath);
                    context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size);
                    throw new HttpException(416, "Requested Range Not Satisfiable");
                }
                start = anotherStart;
                end = anotherEnd;

                length = end - start + 1; // Calculate new content length
                fp = reader.BaseStream.Seek(start, SeekOrigin.Begin);
                context.Response.StatusCode = 206;
            }
        }
        // Notify the client the byte range we'll be outputting
        context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size);
        context.Response.AddHeader("Content-Length", length.ToString());
        // Start buffered download
        context.Response.WriteFile(fullpath, fp, length);
        context.Response.End();

    }

When I streaming large capacity(around 700MB) video in a network using above code the starting of video is very slow (around 1-2 minutes). In this stage I checked the network requests and it seems browser ask for video and waiting for a response from server. This is really annoying for the user.

Then once it started video is playing smoothly (It is a 720P resolution video and as my network connection is good video is playing very smoothly).

But when I do a seek with controls on html video player, then same issue happens and I have to wait another 1-2 minutes till response completed.

I am using IIS7 (MVC4). If I play the same video which located inside of IIS dir then I can play it without mentioned delay. Also if the video is located outside of IIS folder but if it within the same machine that hosted IIS then also no issues.

I am having this issue when I have video in a network location which is a different machine that IIS hosted.

So conclusion is, This is not because of user browser trying to load large video in to browser. It is something between video share machine vs IIS.

Any idea about resolving this?

Regards, -Lasith

How to run html in live websites

Some websites will give option to enter html in their websites like w3 and tutorialspoint in their tutorial examples so the user can change html and see the output . how can we achieve this in asp.net mvc

mercredi 2 mars 2016

Please Help Error : Inconsistent accessibility: property type 'System.Collections.Generic.IList is less accessible than property

  • // I made it public for the class

    namespace MVCEntityExample.Models { public class Country { public Country() { AvailableCountries = new List(); AvailableStates = new List(); } // made public for the properties as well

           [Display(Name = "Country")]
    
           public int CountryId { get; set; }
    
           public IList<SelectListItem> AvailableCountries { get; set; }
    
           [Display(Name = "State")]
    
           public int StateId { get; set; }
    
           public IList<SelectListItem> AvailableStates { get; set; }
    
    

    Getting Error as Error 1 Inconsistent accessibility: property type 'System.Collections.Generic.IList' is less accessible than property 'MVCEntityExample.Models.Country.AvailableCountries'

@model doesn't exist in my view with VS2015 but work fine with VS2012

I've a project created with Visual Studio 2012 and it work fine, but when i open it with Visual Studio 2015 Entreprise Edition, i don't why but in my all views @model, ViewBag & co, doesn't exist VS2015 say "The 'model' doesn't exist in the current context" BUT my project compil WELL and work.

print screen here, on the left side from VS2012 on the right side from VS2015, the same view in the same project

Did someone already had that problem ?

My project is an basic ASP.NET MVC3 Project With RazorViewEngine

ASPX Help Server Error in '/' Application

A old man gave me this code to which until recently could make some calculations and make a nice litte drawing. The calculations saved us a lot of time during our assignments at a nautical school. it used to look like this http://ift.tt/1UyAzm9 but with at functional calculator.

I have tried to delete the web config file to determine what the problem is caused by, and i found a problem with inherit. but the biggest problem is maybe me, im not really that familiar with ASPX.Net :/

Please take a look, and tell me how to get this going again. :) http://ift.tt/1VQrTpH

Compare two Dates in c#

Controller:

public JsonResult TestArray(string id)
{
    //warehouse_order warehouse_order = new warehouse_order();
    int[] finishedOrders = new int[8];
    int countErledigt;

    var stichtag = DateTime.Today;
    for (int i = 0; i < 8; i++)
    {
        stichtag = DateTime.Today.AddDays(-i);
        countErledigt = db.warehouse_order.Where(c => c.end_time == stichtag ).Count();
        finishedOrders[i] = countErledigt;
    }

    int[] test = finishedOrders;

    return Json(test, JsonRequestBehavior.AllowGet);
}

Model:

[DisplayName("Erledigt am")]
[DataType(DataType.Date)]
public Nullable<System.DateTimeOffset> end_time { get; set; }

I havn't been able to compare the two dates in the controller. any Idea how i could do that? Many Thanks

Mvc flash message as a partial view

I'm using a FlashHelper to show flash message to users and I need to show partial view istead of default flash message. How can I do that or that is possible or not.

I need a helper like that:

Flash.Success("_FlashMessagePartial",model)

Or Is there any library you suggest

mardi 1 mars 2016

remove visited alerts or notification from list [on hold]

I want to remove visited alerts/notification from the list. Also I want to keep track of all the alerts/notifications.

Please refer screenshot

How can I do this ?

Alerts are shown properly in the list. There is no issue. For removing visited alerts, I have created new table that stores all the alert status. Onclick of alert It will dump to new table with different status.

But I have no idea how to remove one of the alerts from the list.

Thanks in advance.

I'm implementing handsontable, where i need show the excel data in handsontable

I need to show the data in handsontable from excle sheet, But I got struck up in the middle, any one please help me here.

My controller code

public ActionResult Index()
{
    return View();
}
public ActionResult GetJsonData(FormCollection formCollection)   
{
    var usersList = new List<User>();
    if (Request != null)
    {
        HttpPostedFileBase file = Request.Files["UploadedFile"];
        if ((file != null) && (file.ContentLength > 0) &&      !string.IsNullOrEmpty(file.FileName))
        {
            string fileName = file.FileName;
            string fileContentType = file.ContentType;
            byte[] fileBytes = new byte[file.ContentLength];
            var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
            using (var package = new ExcelPackage(file.InputStream))
            {
                var currentSheet = package.Workbook.Worksheets;
                var workSheet = currentSheet.First();
                var noOfCol = workSheet.Dimension.End.Column;
                var noOfRow = workSheet.Dimension.End.Row;
                for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                {
                    var user = new User();
                    user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
                    user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
                    usersList.Add(user);
                }
            }
        }
    }       
    return View("GetJsonData",usersList);
}

Index view

<h2>Index</h2>
@using (Html.BeginForm("GetJsonData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit" id="btnsave" />
            </td>
        </tr>
    </table>
}  

<div id="example1" class="hot handsontable htColumnHeaders"></div>

<script type="text/javascript">
    $('#btnsave').click(function () {
        var url = '/Home/GetJsonData';
        $.get(url,
            null,
            function (data) {
                debugger;
                var container = document.getElementById('#example1');
                var hot = new Handsontable(container, {
                    data: data,
                    rowheader: true,
                    colheader: true
                });

            });
    });
</script>

GetJsonData view

<div id="example1" class="hot handsontable htColumnHeaders"></div>

<script type="text/javascript">
    $(document).ready(function () {
        var url = '/Home/GetJsonData';
        $.get(url,
            null,
            function (data) {
                  var container = document.getElementById('#example1');
                var hot = new Handsontable(container, {
                    data: data,
                    rowheader: true,
                    colheader: true
                });
                debugger;
            });
    });
</script>