jeudi 31 décembre 2015

404 when trying to access web api

I have an application I'm deploying to azure. It's a SPA app which uses REST API.

I placed the folder of the app in side the wwwroot folder.

when I try to access the API from my local machine i.e. my localhost:1979/api/auth/login I can do it but after I place the files in the www folder - I get a 404 when trying to access: http://ift.tt/1YUeX2j

I tried doing it on my machine on my local IIS and got the same error.

I'm sure it's a stupid thing like configuration but I can't figure it out.

Thanks for any help

form text area values with pagination

I just referred this article to add pagination for my asp.net mvc 5 project form view page. In this form page it has many text areas(like 15) so I limited one text area per one page.

Now this is working as I expected.

enter image description here

but once I insert date to first text area and then go to next text area , again then I click previous button , then those initially added values for first text area are disappearing ? what wrong with my solution ?

is this because, In my scenario I'm using form ??

this is controller method

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

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

        return View(model);
    }

this is view page

@model albaraka.Models.AddNewProduct

@{
    ViewBag.Title = "Brochure_Create";
    Layout = "~/Views/Shared/_bootstrapFileUploadLayout.cshtml";
}

<h4>Add New Product</h4>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()    
    <div class="form-horizontal">      
        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

        @for (int i = 0; i < Model.ListProductFields.Count; i++)
        {   

            <div class="form-group">
                @Html.LabelFor(x => x.ListProductFields[i].ProductFieldNameEn, Model.ListProductFields[i].ProductFieldNameEn, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">              
                        @Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN, new { @class = "form-control summernote", @row = 5 })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.ListProductFields[i].ProductFieldNameAr, Model.ListProductFields[i].ProductFieldNameAr, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                        @Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_AR, new { @class = "form-control summernote", @row = 5 })                 
                </div>
            </div>


                    <!-- pagination section-->
                    @if (Model.Pager.EndPage > 1)
                    {
                        <ul class="pagination">
                        @if (Model.Pager.CurrentPage > 1)
                        {
                                <li>
                                    <a href="~/Home/Add_Product">First</a>
                                </li>
                                <li>
                                    <a href="~/Home/Add_Product?page=@(Model.Pager.CurrentPage - 1)">Previous</a>
                                </li>
                            }

                        @for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
                        {
                                <li class="@(page == Model.Pager.CurrentPage ? "active" : "")">
                                    <a href="~/Home/Add_Product?page=@page">@page</a>
                                </li>
                            }

                        @if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
                        {
                                <li>
                                    <a href="~/Home/Add_Product?page=@(Model.Pager.CurrentPage + 1)">Next</a>
                                </li>
                                <li>

                                    <a href="~/Home/Add_Product?page=@(Model.Pager.TotalPages)">Last</a>
                                </li>
                            }
                        </ul>
                    }


        }



        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>


    </div>

}

this is relevant model classes

public class AddNewProduct
{
        public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }    
        public Pager Pager { get; set; }
}
public partial class AB_ProductTypeCategoryField
{
    public string ProductFieldNameEn { get; set; }
    public string ProductFieldNameAr { get; set; }

    public string Field_Value_EN { get; set; }
    public string Field_Value_AR { get; set; }
}

mercredi 30 décembre 2015

Not routing the static files in ASP.NET MVC 3

I'm trying to write a simple ASP.NET MVC 3 code in which all requests to URL http://ift.tt/1OlTldq will be handed by the corresponding controller but the rest of requests need to be treated as if they are static and looked by webserver on the hard disk.

Here's my code:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        "Calculator",
        "Calculator/{action}/{id}",
        new { controller = "Calculator", action = "Index", id = "" }
    );
}

But when I request http://ift.tt/1kuZbNH it prompts 404 Not found. The thing is that I don't want to code a pattern for the static content, instead I want ASP.NET to look for the static content if there was no matching route. And then if no static content was found on the hard disk, only then it should be saying 404 Not found. How can I do this?

mardi 29 décembre 2015

Displaying different forms in kendo window on click of different buttons

I have 3 buttons and on click of every button totally different content has to be loaded in kendo window, I am doing this in MVC. Can anyone help me out of this ?

Custom IUser implementation - Validate password

I have a problem using UserManager.CheckPassword(...) with a custom IUser implementation.

I am using .net Identity with Owin, creating my own implementations of IUser and IUserStore.

For the store, I only use the optional Email- and Password-Stores.

The IUser implementation is seen here, with the basic fields:

public class RegisteredUser : IUser<string>
{
    public RegisteredUser()
    {
        Id = Guid.NewGuid().ToString();
    }

    public string Id { get; }

    public string UserName { get; set; }

    public string PasswordHash { get; set; }

    public string Email { get; set; }

    public bool EmailConfirmed { get; set; }
}

The problem occurs when validating the user when logging in. I am unable to use the SignInManager.PasswordSignIn(...) as my store doesnt implement the LockoutStore.

Instead I use the UserManager.CheckPassword(...), but this throws an FormatException, saying (The input is not a valid Base-64 string...)

UserSignInManager manager = HttpContext.GetOwinContext().Get<UserSignInManager>();

RegisteredUser user = manager.UserManager.FindByEmail(model.Email);
if (user != null && manager.UserManager.CheckPassword(user, model.Password))
{
    manager.SignIn(user, model.RememberMe, model.RememberMe);
    return RedirectToAction("UserProfile");
}

Thinking about this, I also fail to understand how the CheckPassword() method is able to check the password of my custom implementation without knowing where to look.

What am I doing wrong?

load one item per page [ Pagination ]

I have a viewpage like below

enter image description here

this is the controller method for above view

public ActionResult Add_Product()
{       
    var model = new AddNewProduct
    {
        ListProductFields = db.AB_ProductTypeCategoryField.ToList()
    };

    return View(model);
}

this is model class for above view

public class AddNewProduct
{
    public string Product_ID { get; set; }
    public string ProductTypeID { get; set; }
    public string ProductCategoryID { get; set; }
    public string Subsidary_ID { get; set; }

    public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }
}
public partial class AB_ProductTypeCategoryField
{
    public string Field_Value_EN { get; set; }
    public string Field_Value_AR { get; set; }
}

this is viewpage

@model albaraka.Models.AddNewProduct

@using (Html.BeginForm()) 
{        

        @for (int i = 0; i < Model.ListProductFields.Count; i++)
        { 
          @Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN, new { @class = "form-control summernote", @row = 5 })

          @Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_AR, new { @class = "form-control summernote", @row = 5 })
        }

}

Now I want to add pagination for above view page and limit one ListProductFields per one page , for that I following this Tutorial

So I change my code to like this

    public ActionResult Add_Product(int? page)
    {

        var dummyItems = db.AB_ProductTypeCategoryField.Select(x => "Item " + x);
        var pager = new PaginationModel.Pager(dummyItems.Count(), page);


        var model = new AddNewProduct
        {
            Items = dummyItems.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
            Pager = pager
        };

        return View(model);

    }

But then I'm getting following Run-time Error

Values of type 'AB_ProductTypeCategoryField' can not be converted to string.

MVC page not loading - The resource cannot be found

I just created an empty MVC project and added a masterpage and 1 view(Index). I also created a Controller(HomeController). I also right clicked on Index.aspx view and set this as startup.

However and error is showing up when running the project - "Server Error in '/' Application. The resource cannot be found. Requested URL: /Views/Index.aspx"

HomeController

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

Index

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

<h2>Index</h2>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
    Test
</asp:Content>

MasterPage

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
<link href="../../Content/Site.css" rel="stylesheet" />
<title>Test</title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
  <body>
    <form id="form1" runat="server">
       <div class="page">
       <div id="header">
        </div>
   <div id="main">
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />

        <div id="footer">
        </div>
    </div>
        </div>
</form>
</body>
</html>

Global

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

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

        RegisterRoutes(RouteTable.Routes);
    }

Getting `null` Value In Action

Salaamun Alekum

I Am Getting null Value In Action

HR_TP_Supplier null Assignment1MedicineMasterPharmacy.Models.HR_TP_Supplier

Here Is CSHTML Code

<div class="form-group">
            @Html.LabelFor(model => model.HR_TP_Supplier, "Supplier", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @Html.ListBox("HR_TP_Supplier", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.HR_TP_Supplier, "", new { @class = "text-danger" })
            </div>
        </div>

Here Is C# Action Code

public ActionResult Create([Bind(Include = "MedicineID,Med_Name,Med_code,Generic_Name,Trade_Price,Retail_Price,Accounting_Unit,Nature,THERAPEUTIC_Group,Dosage,Description,Active,Enteredby,Enteredon,ClientID,HR_TP_Supplier")] PH_tmedicine_masterSubmit pH_tmedicine_master)
        {

This Is Entity Class

namespace Assignment1MedicineMasterPharmacy.Models
{
    using System;
    using System.Collections.Generic;

    public partial class PH_tmedicine_masterSubmit
    {
        public int MedicineID { get; set; }
        public string Med_Name { get; set; }
        public string Med_code { get; set; }
        public Nullable<int> Generic_Name { get; set; }
        public Nullable<int> Trade_Price { get; set; }
        public Nullable<int> Retail_Price { get; set; }
        public Nullable<int> Accounting_Unit { get; set; }
        public Nullable<int> Nature { get; set; }
        public Nullable<int> THERAPEUTIC_Group { get; set; }
        public string Dosage { get; set; }
        public string Description { get; set; }
        public string Active { get; set; }
        public string Enteredby { get; set; }
        public Nullable<System.DateTime> Enteredon { get; set; }
        public Nullable<int> ClientID { get; set; }
        public virtual HR_TP_Supplier HR_TP_Supplier { get; set; }
    }
}

Thank You

Render MVC view from ASP.NET

I have two separate projects one in MVC and another in ASP.NET. I have a function in MVC which render a view and convert it into a stream which is working absolutely fine.

I am using this function from ASP.NET using dll to render MVC view from ASP.NET. Problem is razorViewEngine.FindView always return null.

Any kind of help to render MVC view from ASP.NET will save my time as well as save me from rework.

public static Stream RenderView<T>(string controllerName, string viewName, T model, Dictionary<string, object> viewData = null)
    {
        var context = HttpContext.Current;
        var contextBase = new HttpContextWrapper(context);
        var routeData = new RouteData();
        routeData.Values.Add("controller", controllerName);
        var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController());
        var razorViewEngine = new RazorViewEngine();
        var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false);
        var writer = new StringWriter();
        var vdd = new ViewDataDictionary<T>(model);

        if (viewData != null)
        {
            foreach (var d in viewData)
                vdd.Add(d.Key, d.Value);
        }

        var viewContext = new ViewContext(controllerContext, razorViewResult.View, vdd, new TempDataDictionary(), writer);
        razorViewResult.View.Render(viewContext, writer);
        byte[] byteArray = Encoding.UTF8.GetBytes(writer.ToString());
        return new MemoryStream(byteArray);
    }
    class EmptyController : ControllerBase
    {
        protected override void ExecuteCore() { }
    }

lundi 28 décembre 2015

Free HTML to PDF tool [on hold]

I have had i license for EO.PDF and my license does not work with Windows 10. So it needs to be renewed. Since EO.PDF is very expensive i am looking for some good alternatives. I have used HtmlRenderer.PdfSharp to generate my pdf file, and this works fine. But this creates a "weird" looking pdf file and it does not look very good. I have been looking on ways to style this pdf but i cant seem to find any way to so. So i was wondering if there is any good alternatives that either does not cost a lot or is free.

current tool link

btw. i am using mvc3. Thanks

MVC3 FileContentResult returns corrupt pdf

I have an issue where pdfs are being corrupted when viewing. I can assure all of you that the source (test.pdf) pdf is not corrupt. Non pdf files will display correctly.

Running the following code displays the pdf with black blocks where the text should be.

public ActionResult ShowDoc()
        {
            return File(@"c:\temp\test.pdf", "application/pdf");
        }

Corrupt Display

With IE I get this message:

enter image description here

Please help.

How to write unit test for HttpContext.Current.Request.Headers

Below is an Example.

public class MyController : Controller
{
    [Route("~/api/mycontroller")]
    [HttpGet]
    public int ID()
    {
        try
        {
            return somecontroller.getID(ID);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Above it the controller that is fetching the ID from the below controller. Below is the controller that it is inherited.

public class Controller : ApiController
{
    public int ID
    {
        get
        {
            return int.Parse(HttpContext.Current.Request.Headers["ID"]);
        }
    }
}

How do i write unit test case for the following.???

Min.js not found on ISS 7 working perfectly on localhost VS2010

JavaScript not found when i try to upload it on IIS 7 but working on local host

 <script src="../../assets/js/ace.min.js" type="text/javascript"></script>
    <script src="../../assets/js/ace-elements.min.js" type="text/javascript"></script>

Tried direct link as well not working

dimanche 27 décembre 2015

How to pass textbox value to controller in mvc4

How to pass the value on this textbox to controler.

In Index.cshtml file

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <form>
        <input type="text" id="test" name="test" />
        <input type="submit" value="Click" />
    </form>
</body>

In MyHomeControler file

public ActionResult Index(string test)
{
     string val = test;
     return View();
}

What should I do the color of web config file and razor syntax have been gone?

enter image description here The given Image is here Please open it

samedi 26 décembre 2015

Escaping special characters in json

I built Data table in mvc this data table in rendering page i send to it 100 rows after that you can get data by AJAX (see more) in rendering i send data in json string

Code in httpget action

    viewmodelobj.str= (new System.Text.StringBuilder(Newtonsoft.Json.JsonConvert.SerializeObject(viewmodelobj.datalist)).Replace("\\r", "<br/>").Replace("\\t", "").Replace("\\\"", "&quot;").Replace("'", "&#39;").Replace("\\\\", "&#92;").Replace("\\n", "<br/>")).ToString();

and i need to escape special characters because if i send it without escaping those characters data will not displayed

Code in view

var jsobj= JSON.parse(workqueueLoadedData);
        $('#datatableId').DataTable().rows.add(jsobj).draw();

But when i make see more and get data by ajax i didn't have to escape special characters although i use almost the same code Send data by ajax

var jsonResult = Json(new
        {
            data = lisOfWorkQueue
        }, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;

        return jsonResult;

So do you know why it's working right in ajax without escaping special characters unlike get action ? and is there another way to send json from controller to view in rendering step without escaping special characters , thanks in advance

vendredi 25 décembre 2015

In python how do I access an ASP webpage using Requests

I have an ASP website that I'm trying to access thru Python Requests. I can get a 200 status code when access the root server directory, but when I try and access .ASP website I'm getting a 404 error. Ive tried POST as well, same result

When I access http://hostname/Scripts/Home.asp thru the webbrowser, it works fine

>>> import requests
>>> r = requests.post(url="http://hostname")
>>> r.statuscode
200
>>>

But when I try:

>>> import requests
>>> r = requests.post(url="http://hostname/Scripts/Home.asp")
>>> r.status_code
404
>>>

jeudi 24 décembre 2015

Html.ValidationSummary and Ajax.BeginForm Best Practices

When some of the validation errors are client side and the others are server side, the client side errors goes into the @Html.ValidationSummary placeholder in the main view while the server side ones goes into the @Html.ValidationSummary which located on the action partial view.

If i'm not specifying @Html.ValidationSummary as part of the form action partial view, no server side errors shown at all.

how can i merge all the errors (client and server side) into one div located outside of the UpdateTargetId element?

@using (Ajax.BeginForm("PartialViewAction", "MyController", new AjaxOptions { UpdateTargetId = "AjaxResult"}))
{
        <div class="ValidationSummary">
            @Html.ValidationSummary()
        </div>

           <div class="ChartCriteriaSideBox">      
                <div>
                    <ul class="none">
                        <li>
                            @Html.RadioButtonFor(m => m.datesRange.PeriodTypeId, (int)DatesRange.PeriodType.RecentMonth, new { @checked = "checked" }) Recent Month
                        </li>
                        <li>
                            @Html.RadioButtonFor(m => m.datesRange.PeriodTypeId, (int)DatesRange.PeriodType.RecentYear) Recent Year
                        </li>
                        <li>
                            @Html.RadioButtonFor(m => m.datesRange.PeriodTypeId, (int)DatesRange.PeriodType.BetweenDates) Range
                        </li>
                    </ul>
                </div>
    </div>
      <input type="submit" />
    }

Create col1, col2, col3 using MVC where (1,2,3 are dynamically generated)

  • 1> .cs page
public partial class TBL_FG_MENUS
{
     public string ColName1{ get; set; }
     public string ColName2{ get; set; }....ntimes

     public string ColValue1{ get; set; }
     public string ColValue2{ get; set; }....ntimes
}

Question:

  1. I need to loop inside view using this model

    2> .cshtml page (view)

 @{
     int i=1;
     foreach(var item in Model)
     {
         <p>@item.ColName+i<p><br/>
         i++;
     }

     i=1;
     foreach(var item in Model)
     {
         <p>@item.ColValue+i<p><br/>
         i++;
     }

 }

Here I want ColName1, ColValue1 n times inside the loop

mercredi 23 décembre 2015

how to handle page in MVC? page object showing null value how can I use this statement in MVC4?

I have two interfaces in my asp.net(C#) application(IAppNavigation,IViewDimensions) , I am converting the asp.net application into asp.net MVC4(razor).

The below code is in some class file

       Page Page = null;
            if (Page == null)
            {
                Page = HttpContext.Current.Handler as Page;
            }

  IViewDimensions dims = ((IAppNavigation)Page).GetCurrentDimensions();

How to handle page in MVC? page object showing null value how can I use this statement in MVC4?

Please find the below the listed two interfaces.

public interface IAppNavigation
    {
       IViewDimensions GetCurrentDimensions();  
    }

public interface IViewDimensions
    {
        DimensionDetail this[string dimensionName]
        {
            get;
        }

        DimensionDetail[] Dimensions
        {
            get;
        }

        IViewDimensions Clone();

        void SetDimension( string dimensionName, string memberName );

        List<int> GetGeoIds(string geo);
    }

c# create Rss-Feed with the data out of the Database MVC

I want to create automaticlly the Rss-Feed with a controller in a MVC application. I have to use the data out of the database. The Table i need is Movie. Here is the code that i use at the moment:

public ContentResult GenerateRssFeed()
{
   string xmlString = "<div>Test</div>";
   CineStarEntities entities = new CineStarEntities();
   foreach (Movie movie in entities.Movie.Where(m => m.MovieID !=null).ToList()
   {
   }
   return Content(xmlString);`   
}

How can i write the foreach-Loop that i can outprint my data?

Why has Html.DisplayTextFor stopped showing the text as HTML?

I have an ASP.NET MVC3 web page which used to nicely display a C# string of HTML nicely. My server code programmatically loads the string with HTML tags for a nice table. The following cshtml has been showing this nice table as a nice table for years:

<h3>Nice Table:</h3>
@Html.DisplayTextFor( model => model.sNiceTable )

But today we notice browsers (Firefox & IE) are instead displaying it as a pile of text showing the HTML tag text:

<table><tr><th>...

rather than rendering it visually as a table, the way it did for years until now. The "Nice Table" header still displays properly.

Looking at the text in Firefox's developer Inspector shows HTML that looks like it should render as HTML, but (after showing the <h3> tag in color) it too has those tags from my string in black, even though when I paste the same string into an HTML file and load it, it shows the nice table. That is, Inspector shows the code as if it should work, but my string is in black for some reason that doesn't show in its code view.

Trying to use "view source" in Firefox or IE seems to be unusable for this, because the view part doesn't even show up there for some reason.

I see there are various other methods such as Display() and DisplayFor(), but they seem to do the same thing.

I haven't really touched this page since it last worked. The only thing I suspect that changed was applying some MS updates that had some other annoying side-effects on my projects.

What can I do to get this text to render again, rather than spew the HTML tags in the string as text?

Edit: model.sNiceTable is a C# string data member of the viewmodel, where the interface is:

public interface IMemberStatsViewModel
{
    string sNiceTable { get; set; }
    // other properties...
}

Its value gets assembled in my code which is called in the view model's constructor:

public MemberStatsViewModel()
    : base(new DataLayer.DataLayer(), ClientInterfaceTypeEnum.Web)
{
    InitializeMe();
}

InitializeMe() calls a data layer function which returns the C# string and assigns it to sNiceTable. The string is built based on stuff I look up in the data layer.

mardi 22 décembre 2015

Passing data from Controller to model in MVC 3

is there a way to pass data from controller to model?

the scenario of my project is that, it has two tables in database, and in View there are two text boxes , the data of one text box is save to one table while data of another table is save to another table , i want to show the data of both tables in another single View . for that reason i want to send both textbox values from controller to model then want to show the data from that model to the view. can someone please help how can i implement it ?

Website under load throws StructureMap Exception Code: 202

The website works with a few users but when the website is under load (From VS Load Test) the following exception is thrown:

StructureMap Exception Code: 202 No Default Instance defined for PluginFamily MyProject.IRepository

  • StructureMap version 2.6.2
  • ASP.Net MVC 3

StructureMap config

ObjectFactory.Initialize(x =>
        {
            x.Scan(
                    scanner =>
                    {
                        scanner.AssembliesFromApplicationBaseDirectory(p => p.FullName.StartsWith("MyProject"));

                        // add registry types
                        scanner.LookForRegistries();
                    });
            x.AddRegistry<ServiceRegistry>();
            x.AddRegistry<DataRegistry>();
            x.AddRegistry<LogicRegistry>();
        });

DataRegistry

For(typeof(IRepository<>)).Use(typeof(EntityRepository<>));

Exception is thrown here:

 var controller = ObjectFactory.GetInstance(controllerType) as Controller;

Debug

ObjectFactory.WhatDoIHave() shows the following

IRepository (IRepository)
Scoped as: Transient

3bd2b6ef-80e9-4b98-9c04-f59c44fc6d8b Configured Instance of MyProject.EntityRepository, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

IRepository (IRepository)
3bd2b6ef-80e9-4b98-9c04-f59c44fc6d8b Configured Instance of MyProject.EntityRepository[[MyProject.Person, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Scoped as: Transient

3bd2b6ef-80e9-4b98-9c04-f59c44fc6d8b Configured Instance of MyProject.EntityRepository[[MyProject.Person, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

lundi 21 décembre 2015

keep sidemenu expand every reload

i facing some situation on sidemenu want to make the , but anyway the webpage refresh all the time after i click on the sidemenu. i need to make the sidemenu stay on active after click, any solution about this?

try some javascript from internet still remain the same. here is my code:

<div id="sidebar" class="sidebar responsive"   >
               <ul  class="nav nav-list" >
                    <li class="#"  >
                        <a  href="#"  class="dropdown-toggle">
                          <span class="menu-text" >
                           <ul class="submenu" >
                           <li class="active" >   //set it active will remain active all the time
                                <span class="menu-text"  >

above is example from my code, Thank you.

405 error from an IFrame

I have a main application and in one of the views I load an IFrame.
The IFrame is another controller/view that will make up this IFRAME
In the IFrame view I am trying to make an AJAX POST back to it's controller.
However I am getting a 405 error message on the post.

Is it possible to make a post back to the IFRAME controller?

Example: JavaScript from IFRAME:

function myFuction() {
    var model = {
        rId: 1,
        tId: 2,
        mType: 1
    };
    $.ajax({
        type: 'POST',
        url: 'Main/Report/GetData',
        contentType: 'application/json',
        data: JSON.stringify(model)
    }).success(callback);    
};

In the controller for the IFRAME:

[HttpPost]
public JsonResult GetMapDataT(int reportId, int targetId, int mapType)
{
    var userId = GetUserGuid();
    var data = MappingService.GetMapData(userId, reportId, targetId, mapType);
    return Json(data);
}

Nhibernate on Asp.net mvc strange state related errors on iis8 server 2012 and structuremap

We are getting a couple different strange errors out of nhibernate in our asp.net MVC 3 application. But only in the productions(field) environment, and only on our highest load application, and it only started after we upgraded from server 2003 to server 2012, and pointed to a new copy of our sybase DB at our new main data center, and released new code. (Of course we did all 3 on the same weekend, and so have no idea which caused it.)

The problems are happening all over, including in code we haven't touched in forever. We haven' changed the underlying nhibernate wrapper code. We also use fluent if that helps any.

Because of a design decision above my level we are only updating inserting and deleting with nhibernate, selects we do by hand... but all our erros are essentially "we(nh) wrote to the Db and things were out of synch)".

we basically fetch data manually, populate an EO, make our changes to the EO and tell nhibernate to handle updating it for us.

Here is one example error.

23 Nov 2015 07:02:10,925 [6] [Error] OnActionExecuting : ProgrammerInfo Unexpected row count: -1; expected: 1; Details=NHibernate.StaleStateException: Unexpected row count: -1; expected: 1 at NHibernate.AdoNet.Expectations.BasicExpectation.VerifyOutcomeNonBatched(Int32 rowCount, IDbCommand statement) at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation) at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session) at NHibernate.Action.EntityUpdateAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at NHibernate.Engine.ActionQueue.ExecuteActions() at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) at NHibernate.Impl.SessionImpl.Flush() at NHibernate.Transaction.AdoTransaction.Commit() at JCDCHelper.NhAccess.BusinessObjects.NHSession.Commit() at CIS3G.BLL.BusinessObjects.CTTCredentialsBLL.SaveCredentials(CTTCredentialsVM record) at CIS3G.Controllers.TrainingStudentBasedController.SaveCredentials(CTTCredentialsVM criteria)

We also get stale state errors. we are using Structure map and are running out session wrapper in hybrid mode, to implement the session per request pattern. My firs thought was multithreadede access to session corrupting the state.. but the session per request pattern is suppoed to prevent this yes?

x.ForRequestedType() .AddInstances(z => z .OfConcreteType() .WithName("JCDC_HasTrans") .SetProperty(y => y.DBNameAndHasTran = "JCDC_HasTrans") ) .AddInstances(z => z .OfConcreteType() .WithName("JCDC_HasNoTrans") .SetProperty(y => y.DBNameAndHasTran = "JCDC_HasNoTrans") ) .AddInstances(z => z .OfConcreteType() .WithName("SPAMIS_HasTrans") .SetProperty(y => y.DBNameAndHasTran = "SPAMIS_HasTrans") ) .AddInstances(z => z .OfConcreteType() .WithName("SPAMIS_HasNoTrans") .SetProperty(y => y.DBNameAndHasTran = "SPAMIS_HasNoTrans") ) .CacheBy(InstanceScope.Hybrid);

The fact that it's load dependence leaned me towards a racing condition on multiple thread corrupting the state. Bu the more I've read the move I'm beginning to feel this is a "you are not using nhibernate right" problem

What else can be causing this

I know the -1,-1 error can be caused by double deleting an object, but that's thread related right?

The Nhibernate articles say to look at the generated sql and it'll explain the error, but i pull it out and de-parameterize it and the sql works fine.

This issue is hitting our customers pretty hard, Any guidance or help is appreciated, especially posts/links that will help be understand what can cause the nhibernate to throw the -1,1 and stale state exceptions, when threading is supposedly "handled".

what is the effect of a lock on a static object in a web applicaiton on iis 8

we are having some issues with nhibernate in an MVC asp.net web app, One of our first theories was that since session is not thread safe, that might be causing our issue.

we are using structure map, and our session wrapper is instantiated as a "hybrid" which is supposed to solve threading issues by having 1 session per request.

to test this theory, we put a static object lockObject in our session wrapper, and then put locks around any call that modifies (but not retrieves) anything on the session object.

But I'm uncertain as the effect this will have under high load. What we want is no non synchronous access to a give instance of session, will it instead synchronize across all instances, even if memory is not shared?

Is there a better way to achieve our goals?

Thanks

How to map javascript object to mvc model?

I've a js object like bellow:

$scope.docPropIdentityModel = {
        Owner: {OwnerID:"", OwnerName: ""},
        };

I want to send this object to my mvc controller through ajax call. Let say the controller is like:

controller(test_class model)
{
}

and the model is like:

test_class
{
  public string Owner{get;set;};
}    

I'm getting null in my controller. How can I map the js object value to my model?

dimanche 20 décembre 2015

How to make upload on Load Balancing server?

I am using asp.net mvc 4.0 application. this application is running on live server with Load balancing. this is pointed by multiple server on one common shared path. so now I want to make release on this application. means want to upload one dll from local to live. previously I did directly copy paste without making any iis stop. at that time after upload site is responding very slow,after upload on first time I got very slow response , then after also 3/4 attempt site responding very slow.

so, I want to know Is there any specific step to do upload ?

mvc application shows 500 internal server

I have developed one mvc 4 application and hosted on server and its working fine.but now i want to host this application on another plesk server 12.0.18 , but application shows following error 500 internal server error.there is a problem with the resource you are looking for,and it can not be displayed. I have set custom error mode 'off' but still same error is occurring. I have two connection strings. If i specify connection string of another server then application is working fine and if i specify connection string of plesk database then error occurs again. So its about connection string.so i think entity framework not connecting to plesk database so is it about permission or what?

But i can connect with that database from web application they have provided by using my little admin for sql server.but not with connection string from application.

Make select box change values when another value is selected from another select box

I want my select box change depending wich option i choose in the first select, and i want to hide the values that are not from that option

My html here:

<select id="localidad">
            @foreach (ja_era.Models.Localidades localidad in ViewBag.localidades)
            {
                <option value="@localidad.Id">@localidad.Zona</option>
            }
        </select>
        <select name="Localidad" id="barrio">
            @foreach (ja_era.Models.Barrios barrio in ViewBag.barrios)
            {
                <option class="@barrio.Localidad" value="@barrio.Id">@barrio.Barrio</option>
            }
        </select>

The Localidad select has 4 options and bring the countries, then i have the second select that bring the cities all in one select box. Wichones are well defined in my database.

enter image description here

enter image description here

You can see here that "Barrios" has the column localidad where i insert the localidad id

I have tried some js code but cant figure it out how to make it work.

$(document).ready(function() {
       $('#localidad').change(function () {

});
})

Use linq OrderBy to order a list by an ID

I have a list of users that i want to order by an ID. So now the list is ordered by a users fullname like this:

OrderBy(m => m.FullName).ToList();

what i want to do is order this list so a specific id is set to be at the start index.

so the pseudo code would be:

Var passedId = 2123

OrderBy(m=>m.ID); <--- And then set passedId to be in the start index of the list

is this possible ?

thanks.

samedi 19 décembre 2015

WebApi2 Attribute Routing doesn't work unless controller classes are named in a specific manner

I was debugging an issue with attribute routing giving 404s for known-good routes. Well, known-good to me, but they weren't being picked up by the framework. I was grouping my controllers/models into logical units, e.g.:

Auth
    Models
        Model1
        Model2
    Controller

So my "AuthController" is named MyApi.Auth.Controller instead of, for instance, MyApi.Auth.AuthController.

My routes were not being picked up until I renamed my controller, adding anything before it, e.g. zzController. This makes me think there's a bug in attribute routing, or am I missing something?

vendredi 18 décembre 2015

ASP.NET MVC 3 and .NET Framework 4.5

need to run ASP.NET MVC 3 on Framework 4.5. VS 2010 doesn't give this option, but if I open it with VS 2015 it allows to change Framework to up to 4.6. We can't upgrade our application to a newer MVC (4 or 5) version, so the only option is to update a project framework and recompile it. Is there any well-known issues running MVC 3 on 4.5?

Can not Change input text value with jQuery in ASP.NET MVC?

I have a Bootstrap modal that shows the images of Gallery, when you click on it. I want change input value by clicking on each image and put their Url on input text for submit . But it doesn't work and value of input text doesn't change . Why?

    @model IEnumerable<tourism.Models.Gallery>

    <input type="text" name="imgUrl" id="index-img" style="width: 100%;" value="url" />

 <div class="container">
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info btn-lg" id="myBtn">Choose Image</button>

    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog modal-lg">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Gallery</h4>
                </div>
                <div class="modal-body">

                    <div class="row">

                        @foreach (var item in Model)
                        {
                            <div class="col-lg-2 col-sm-3 col-xs-4">
                                <a href="#" onclick="(function () {    ('input[name=imgUrl]').val()=@Html.DisplayFor(modelItem => item.Url); })()" class="close" data-dismiss="modal"><img src="@Html.DisplayFor(modelItem => item.Url)" class="thumbnail img-responsive" alt="@Html.DisplayFor(modelItem => item.Alt)"></a>
                            </div>
                        }

                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>

</div>

jQuery code for passing Url from model to input text(from above code) :

<a href="#" onclick="(function () {    ('input[name=imgUrl]').val()=@Html.DisplayFor(modelItem => item.Url); })()" class="close" data-dismiss="modal"><img src="@Html.DisplayFor(modelItem => item.Url)" class="thumbnail img-responsive" alt="@Html.DisplayFor(modelItem => item.Alt)"></a>

How to call IFrame from web page in MVC

How can I call an IFrame from a view?

In my current view I have this HTML.

<table>
    <tr>
        <td style="vertical-align: top;">
            <div style="border:dashed;" id="mapContainer">
                <iframe src="MyIframe" name="myTest"></iframe>
            </div>
        </td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>

The MyIframe is a cshtml file that exists in the same location as the above view resides in.

When I run the application I get a 404 - Not found.
What is the proper way to load an IFrame in an existing view?

jeudi 17 décembre 2015

Run javascript after element is added to body

I have an element that does not appear on the page unless some function is activated. I want to remove this after it appears on the page.

how do i run my javascript code when and only when this element is added ?

I am new at this and would appreciate some help. Thanks.

ps. element is generated by jquery and only has classname.

Action method parameter set to value of submit button

This is some legacy ASP.NET MVC3 code I've been asked to look at. It has an action method with two string parameters in addition to the model.

public ActionResult RequestUsername(StaffModel model, string request = null, string clear = null)

The form that calls this has two submit buttons:

<input type="submit" class="button" title="Request username" value="Request Username" name="request" />
<input type="submit" class="button" title="Clear form" value="Clear" name="clear" />

If I click the first one, the method parameter called 'request' is set (to "request"). If I click the second button, the method parameter called 'clear' is set (to "clear"). I can't see any custom code that would do this, so I think it must be something in the framework.

My question is: what is doing the mapping between the name attribute of the button being clicked, and the action parameter?

Thanks

Add bootstrap pagination dynamic

I'm looking for a way so that for each 10th post, it add a pagination, so that it's sperating my pages, dynamic. BUt not sur what i should do?.

This is my foreach code:

@foreach (var Thread in Model.Threads)
    {
        <div class="col-sm-12">
            @Html.ActionLink(Thread.Title, "Post", "Threads", new { @id = Thread.Id }, new { @class = "CategoryTitles" })
            <br /><br /><p style="margin-left: 25px;">By: @Thread.ApplicationUser.UserName</p><hr />
        </div>
    }

But don't know what to do from now

Form Post action stalls the page

I have created a form with filters and a gridstate. I use this form as a post action. When i submit this form via my javascript. The bage stalls/is in load state after the file is downloaded.

i download a list of users from. This userlist has a filter where u can press search. This search button is disabled for some reason when i download the file?

see image: http://ift.tt/1JdBoIs

(Søg means search)

my code: http://ift.tt/229BDA0

I have tried setting the target for my form to be target="_blank" but that doesnt help. It still diables the button. What is the cause of this ??

mercredi 16 décembre 2015

generate a list of URL links for files in folder [javascript]

I want to generate list for each file in folder.For example if I have following files in specific folder

  • sample_picture1.jpg
  • sample_picture2.jpg

I want to generate URL links as follows


Currently I created it as like this.

json method to find files in a folder

    public JsonResult filesinfolder()
    {
        string salesFTPPath = "folder_path";

        DirectoryInfo salesFTPDirectory = new DirectoryInfo(salesFTPPath);

        IEnumerable<string> files = salesFTPDirectory.GetFiles()
          .Where(f => f.Extension == ".xls" || f.Extension == ".xml" || f.Extension == ".jps" || f.Extension == ".jpg" || f.Extension == ".jpeg" || f.Extension == ".png")
          .OrderBy(f => f.Name)
          .Select(f => f.Name);

        return Json(files, JsonRequestBehavior.AllowGet);
    }

script to get files

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: '@Url.Action("filesinfolder", "Home")',
        dataType: "json",
        success: function (data) { onSuccess(data); },
        error: function (xhr, status, err) {}
    });
});

var onSuccess = function (data) {

};

So I want to take the result to onSuccess as list of URLs (for files in a folder).

Return a list of all Active Directory groups a user belongs to in string[ ]

I need to return all Active Directory groups a user belongs to but in string[ ], so I can use the result in Generic Principal.

I am not sure if to cast results? Please help!

string[] roles = new string[] {  
helper.GetActiveDirectoryGroups(User.Identity.Name) };

GenericPrincipal principal = new GenericPrincipal(identity,roles);

 public string[] GetActiveDirectoryGroups(string userName)
    {
          //code here

    }

How to use reference link inside img tag in mvc3

I have a img tag on view page. it works fine if img src path reference to same website, but if pass http path inside src from other website it does not display image.

mardi 15 décembre 2015

MVC Data Form Entry with DataGrid (CRUD)

I am tasked to change our Silverlight(SL) application to MCV since the development lifecycle of SL has already been stopped. I am new to MVC but I can find a good tutorial how to do a simple CRUD with MVC. Basically, the requirements are

1.) in the UI, there should be two pane, left and right.

2.) In left pane, a grid/data grid view of list of "Student" entity and on the

3.) right side is a data form which displays the Student's details.

4.) The details in right pane, the data form, will change as you select an item in left pane, the data grid.

5.) The data form should be able to do the CRUD functionality.

I am very desperate to find a tutorial but I can't find one that fits my needs. I will be very thankful to those who can help me with this by giving some links or video tutorial. Hope to read comments that could help.

lundi 14 décembre 2015

C# Missing conditional formats with EPPlus

When writing a excel file from a template, using a web page in mvc3, the conditional format get messed up. Checking the xml files of the sheet, I go from this:

<conditionalFormatting sqref="T6:U18">
<cfRule type="colorScale" priority="2">
<colorScale>
<cfvo type="percentile" val="0"/>
<cfvo type="percentile" val="50"/>
<cfvo type="percentile" val="100"/>
<color rgb="FF63BE7B"/>
<color rgb="FFFFEB84"/>
<color rgb="FFF8696B"/>
</colorScale>
</cfRule>
</conditionalFormatting>

To this:

<conditionalFormatting sqref="T6:U18">
<cfRule type="colorScale" priority="2">
<colorScale>
<cfvo type="min" />
<cfvo type="percent" val="50" />
<cfvo type="max" />
<color rgb="fff8696b" />
<color rgb="ffffeb84" />
<color rgb="ff63be7b" />
</colorScale>
</cfRule>
</conditionalFormatting>

A code snip:

[HttpPost]
public ActionResult Export(DataModel model)
{ 
    using (ExcelPackage xlsPackage = new ExcelPackage(new FileInfo(Server.MapPath("~/Content/Data/TEMPLATE.xlsx")), true))
    {
        ExcelWorksheet wsSheet = xlsPackage.Workbook.Worksheets["TOTAL"];

       //Data fill

        MemoryStream stream = new MemoryStream();
        xlsPackage.SaveAs(stream);
        stream.Position = 0;

        return File(stream, "application/vnd.ms-excel", "Data.xlsx");
    }
}

date format giving error in server in local working fine in MVC

I have a functionality which upload an excel sheet to database. One of the validation is checking then date format given in excel sheet is dd/MM/yyyy

for that i do a regular expression check as below

if (!checkRegex(member["DOB"].ToString().Trim()))
{
  ModelState.AddModelError("DOBFORMAT", "Date of Birth is not in dd/MM/YYYY for record " + count + ". Please check");
System.IO.File.Delete(pathToExcelFile);
return View();
}

and regulare expression checking function is

      public bool checkRegex(string inputstring, string type)
                {
            DateTime date;
           string format;

        Regex regex = new Regex(@"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)
    (?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))
    (?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3
    (?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|
    (?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$");
 try
{
 date = Convert.ToDateTime(inputstring);
 format = "dd/MM/yyyy";
 string check = date.ToString(format);
 if (regex.IsMatch(check))
     return true;
else
 return false;
}

when I am uploading an excel sheet with "27/08/1983" from server it is giving error that date format is wrong for the record.

I tried the same with localhost and done debugging. It passed the regular expression and uploaded successfully.

Date format in server and localhost is "dd/MM/yyyy"

Also other excel sheets are uploading successfully.

Please show some light on this issue

dimanche 13 décembre 2015

Prevent Race Condition in ASP.NET Resource Class

As we know the static resource class share among multiple threads in asp.net,We have a CMS application uses resources for localizing strings but when the application is under load,Resource culture sometimes loads with invalid culture,for example in Views wee see that Thread.CurrentThread.CurrentUICulture is en-US but Resource.Culture is it-IT,It's about 3 month that we're working hard on this problem,in the last we had to set "Resource.Culture" in Application_AcquireRequestState and also Set it in OnResultExecuting but this is not the correct way and we see that resources in Layouts yet will be invalid sometimes under load.This is our code to set culture in Application_AcquireRequestState

var cultureInfo = new CultureInfo(lang);
var culture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
culture.DateTimeFormat.AMDesignator = "AM";
culture.DateTimeFormat.PMDesignator = "PM";
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Monitor.Enter(Lockobj);
try
{
    Resources.App_GlobalResources.Resource.Culture = culture;
}
finally
{
    Monitor.Exit(Lockobj);
}

these are some threads that others had problem like this
ASP.Net MVC resource files are sometimes incorrectly loaded by the ResouceManager

http://ift.tt/1NNJAoi

Special thanks to Any one can help around this

vendredi 11 décembre 2015

Save Non English data using EntityFramework on MYSQl Database using MVC

I am using EntityFramwework approach in an MVC3 app to save & retrieve data I am playing with non English data in app

I try to save a new record to db as

  internal bool AddDept(DEPTModel model)
    {
        try
        {
          deptmaster db_itm=  new deptmaster { MalayalamName = model.MalayalamName, Name = model.Name };
          dbcontext.deptmasters.AddObject(db_itm);
            dbcontext.SaveChanges();
            return true;
        }
        catch
        {
            return false;
        }
    }

While putting break point and inspect model properties i can see my properties in nonEnglish language ("Malayalam") But after the completion of database insert query when i check db i can see only ????? inside table.

How can i make sure the same data from view is inserted to table

My column structre is

 ALTER TABLE deptmaster MODIFY MalayalamName VARCHAR(250) CHARACTER SET UTF8;

So if i manually edit table column using MySQL front its saving nonEnglish text

How to popup alert when TextBoxFor's input does not exist in database?

NPG_Chemical_Measurement_Methods is a ICollection type. In my Chemical.cshtml, I have:

<div id="nioshs">
    @Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>

and in the EditorTemplate view:

<div class="method" style="display:inline-block;">
<p>
    @Html.RemoveLink("x", "div.method", "input.mark-for-delete")
    @Html.HiddenFor(x => x.DeleteMethod, new { @class = "mark-for-delete" })
    @Html.TextBoxFor(x => x.Measurement_Method)
    @Html.Hidden("Measurement_Type", "NIOSH")
    &nbsp;&nbsp;&nbsp;
</p>
</div>

I want to have something like when I give input for "@Html.TextBoxFor(x => x.Measurement_Method)", then click on other place of the current page, an alert will popup says "Not exist in Database" if record cannot be found in "Measurement_Method" table.

How to bind modal data inside sidebar in _layout.cshtml in mvc3 EF5

I want to display modal data inside right sidebar in _layout.cshtml page, so the data will be display on every view. Here i create a PartialView for that data which i have placed inside rightsidebar in _layout. It works ok on index page, but when i redirect to another page, it gives me error. enter image description here

_layout.cshtml

    <div class="col-md-9 contentbar">
        @RenderBody()
    </div>
    <div class="col-md-3" style="padding-top: 20px;">

        <ul style="font-weight: bold; list-style-type: none; padding: 0px;">
            <li style="font-weight: bold;">Tv Serial Latest                   
                        @{Html.RenderPartial("ListAllTvt");}
            </li>
        </ul>
    </div>
</div> 

PartialView (ListAllTvt.cshtml)

@model  IEnumerable<Cmedia.Models.TVSerialModel>
<ul style="padding: 0; font-weight: normal; list-style-type: none;">
      @foreach (var item in Model)
      {
        <li>@Html.ActionLink(@item.Serial_Name, "ListAllEpisode", "TvSerialEpisode",new { id = item.Serial_ID}, null) </li>
      }
 </ul>

TvSerialContoller.cs

public class TvSerialController : Controller
{
    public ViewResult Index()
    {
       List<TVSerialModel> tv = tvContext.dbTvSerials.ToList();
       return View(tv);
    }

    public ActionResult Detail(Int32 id)
    {
       TVSerialModel tvserial = tvContext.dbTvSerials.Find(id);
        return View(tvserial);
    }

    public ActionResult ListAllTvSeri()
    {
       List<TVSerialModel> tv = tvContext.dbTvSerials.ToList();
       return View(tv);
    }
}

i guess when the index view called it set the model value by default because index and partialview using same model, but when i redirect to another page it flush the model data and then i get the error. I don't know how to fix this.

Using web form aspx and mvc partial view

As per the question, I have an mvc project which has file with .aspx extension with separate code behind. I would like to include the aspx file as mvc partial by calling @Html.Partial("AspxFileName"). But I am not sure whether this could be achieve. If it could, how to achieve it?

jeudi 10 décembre 2015

Mocking Web API call in MVC

i have mvc application which call the WEB API using the restsharp . i am writing the test cases for the MVC application. test case execution fails in the debug mode when it hit to the Web API below is the MVC code

  public JsonResult GetCustomerInforGrid(string ddlItem, string Searchtext)
        {

            CustomerInfoModel customerinfor = new CustomerInfoModel();
            List<CustomerInfoModel> listcustomerinfor = new List<CustomerInfoModel>();
            var restClient = new RestClient(ConfigurationManager.AppSettings["SWBWebApiBaseUri"]);
            var request = new RestRequest("api/CustomerInfo/GetCustomerInfo/{ddlItem}/{Searchtext}", Method.GET);
            request.AddParameter("ddlItem", ddlItem, ParameterType.UrlSegment);
            request.AddParameter("Searchtext", Searchtext, ParameterType.UrlSegment);
            var varexceptionlist = restClient.Execute<List<CustomerInfoModel>>(request);

            foreach (var item in varexceptionlist.Data)
            {

                listcustomerinfor.Add(item);
            }


            return Json(listcustomerinfor, JsonRequestBehavior.AllowGet);

        }

below is the code written in the MS test i am trying to mock it but not sure how to do. kindly provide the help/suggestion how to test the MVC controller

 [TestMethod]
        public void SearchCustomer()
        {
            String GCIN = "GC007637306A";
            CustomerInfoModel CIM = new CustomerInfoModel();

            CustomerInfoController controller = new CustomerInfoController();
            //HomeController controller = new HomeController();
            //Mock Request.Url.AbsoluteUri 
            HttpRequest httpRequest = new HttpRequest("", "http://mySomething", "");
            StringWriter stringWriter = new StringWriter();
            HttpResponse httpResponse = new HttpResponse(stringWriter);
            HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
            controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);


            CIM.CustomerName = "XXX XXXXX 549224361A";

            CustomerInfoController CI = new CustomerInfoController();
            controller.GetCustomerInforGrid("GCIN", GCIN);

            Assert.Equals(CIM, CI);

        }

PDFTron displays blurry pages when connectivity is slow

My PDFTron web Application(website) displays blurry pages when connectivity is slow on android phones in any browser(like chrome). So there is any way/idea to overcome this issue, please suggest.

How can I display a matrix table in asp.net mvc3 with not set many to many?

my question is very similar to this one

I have three tables which are in a many to many relationship. I have to build a matrix that will give the possibility to set the between table. In contrast with the other question, I don't have the Sales values yet, but I need to build the same grid format.

I'm not sure about how to write the LINQ query and the one in the other article did not work for my purpose.

Thank you for your help,

ASP.NET MVC 3 Razor DateTime.Parse don't work

I'm trying to do a cast with dates but it's throws me an exception .

The code is:

This Works ->

var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");

This Doesn't Work ->

var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");

The model is Ok and values are dates in string format

The error is:

Server Error in '/' Application. String was not recognized as a valid DateTime. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:

Line 13:    var Ubicacion = Model != null ? Model.Ubicacion : null;
Line 14:    var FechaInicio = Model != null ? DateTime.Parse(Model.FechaInicio).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");
Line 15:    var FechaFin = Model != null ? DateTime.Parse(Model.FechaFin).Date.ToString("dd/MM/yyyy") : DateTime.Parse("").Date.ToString("dd/MM/yyyy");

wrong redirect page in Application_AcquireRequestState event in MVC

When i redirect from login action to another action in another controller i use this code

RedirectToAction("Index", "dashboard")

in glbal.asax i use this event Application_AcquireRequestState this event is called in each redirect in the system but when i redirect to dashboard from login page the url that i got in Application_AcquireRequestState function is url of login page not dashboard url although i redirect right by this code

RedirectToAction("Index", "dashboard")

and sometimes i got this issue and sometimes not get it and i didn't get it local but i get it always in deployment in the internet

mercredi 9 décembre 2015

Video (.mp4) not getting downloaded in MVC

In my view i have a link to download a .mp4 like below

<a href="@Href("~/Content/mm/Manual_Video.mp4")" target="_blank"> Download Video </a>

and i stored the Manual_Video.mp4 in Content folder but when I click on the link I am getting below error

404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

Any idea?

Use LINQ to load users in MemberShip in MVC3 with C#

Hello wanted to know how I could use LINQ to list the data of users who did in this code:

@inherits System.Web.Mvc.WebViewPage<MembershipUserCollection>

@{
    ViewBag.Title = "Index";
}

  <h2>Table</h2>
  <table style="width: 100%;">
  <tr>
  <th>Nom
  </th>
  </tr>

    @foreach (MembershipUser user in Membership.GetAllUsers())
    {
  <tr>
    <td>
            @user.UserName

    </td>
    <td>
            @user.CreationDate
    </td>
    <td>
            @user.LastActivityDate
    </td>

</tr>
}

</table>

I do not understand is how to use LINQ to directly load data from users in membership, I mean charging all users and list these data in a comfortable foreach

As I can accomplish this?

Execute code before reaching the controller's code

My intention it's to create a MasterController that decides what configurations will use depending on the URL parameters.

  1. My first idea was to create a MasterController. All requests to the server would be redirected to this controller and then, this MasterController would decide wich controller to use, and redirect to it. The problem would be that this would make too many requests.

  2. My second idea was to call a function in the beginning of each controller that redirects to the correct controller if necessary. The problem would be the same: it would increase the number of requests.

Concrete example: Imagine that I have the followings URLs:

http:\\myapp.com\?showController1=true

http:\\myapp.com\abcd?showController1=true

When the server receives the request, I want the final result be the same: show Controller1, independently of the request being to homeController or abcdController.

To make this work, before witch controller is reached, I need to decide which controller will be called dependedind on the url parameters. But I want to minimize the number of requests made between the server and the browser.

It is possible to implement this without making extra requests?

Dashboard using Angulerjs and signalr

I have to develop dashboard for the train scheduling system. This system mainly contain two separate systems MVC web portal and windows service. Windows service used to update schedule status. As a example when train starts windows service update schedule status from pending to start.
My requirement is build dashboard with ASP.Net MVC to display schedules according to it status.
I want to display start schedules in green color and stop ones in red color when status changed. I want to do this without any server post backs and page reloads. I know this can be done using Angulerjs, Signalr and ASP.Net or using SQL dependency objects.

How can I develop this kind of dashboard ? any one has any examples or demos ... ?

mardi 8 décembre 2015

ASP.net MVC3 with forms authentication and LDAP authentication

I have asp.net mvc3 application with forms authentication. But the our client request AD authentication as well. But the mvc3 app is hosted outside the clients network. What are the possible solutions for this.

  1. Get permission to access the clients network from remote server.
  2. Get an API to access the active directory data from webserver.

If we choose opt one how could we access active directory for authentication from outside the client network. I anybody have any idea or better options please let me know. Thanks in advance.

How to read a specific field in ADO.NET Entity Data Model Object on Postback event

I have a dropdownlist that is populated from a database as:

Controller

PayrollDb pdb = new PayrollDb ();
var addBranchGui = new branch();
addBranchGui.BranchTypes = new SelectList(pdb.branchtypes,"Id", "Type");


View

<p>Branch Type:@Html.DropDownListFor(x => x.BranchType, Model.BranchTypes, "Choose an option")</p>

This codes correctly populates the dropdownload list. Problem arises when user selects an option in the dropdownlist and submits the form and I catch the input data on [HttpPost action method and insert it into a database table, it is the "Id" field that gets inserted when I want the "Type" field to be inserted.

I can understand that on Postback event, browsers is reading "Id" field. Can someone please guide me how I can command the browser to give me the "Type" field so I can insert that into database.

Access Current Area Name in Session Start - MVC 4.0

We have multiple areas in our MVC 4.0 application and I am looking for a way to get the current Area name when the session is started.

How to use @page CSS in ASP.NET MVC View

How to use the @page css in a Asp.net MVC View (.cshtml). Because when I tried, It shows an error message

the 'page' does not exist in the current context

And the below mentioned is the stylesheet I used in the view

<style type="text/css" media="print">
            @page port {size: portrait;}
            @page land {size: portrait;}
            @page {
                 size: 85.60mm 53.98mm;
                 margin-top: 8.65mm;
                 margin-bottom: 5.33mm;
                 margin-left: 4.0mm;
                 margin-right: 4.0mm;
                }
        </style>

How to call button click event after controller postevent?

How to call button click event after controller postevent?

here is my view where i have a text box to enter notification messafe and on button click it should save data to database and should send the notification to clients using the code in the script section . Here it calls the http post event but the code in the jquery also firing but the notification is not sending . notifications.server.sendNotifications(); is not firing .

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <div class="publishContainer">
            @Html.TextAreaFor(model => model.Text, new { @placeholder = "Whats in your mind !!" })</div>
        <p>
            <input id="button1" type="submit" value="button" />
        </p>
    }
    @section Scripts {
        <script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
        <script src="~/Scripts/jquery.signalR-1.1.4.js" type="text/javascript"></script>
        <script src="~/signalr/hubs"></script>
        <script type="text/javascript">
            $(function () {
                var notifications = $.connection.notificationHub;
                debugger;
                // Start the connection.
                $.connection.hub.start().done(function () {
                    $("#button1").click(function () {
                        notifications.server.sendNotifications();

                    }).fail(function (e) {
                        alert(e);
                    });
                });
            });
        </script>
    }

    and the controller Post event 

     [HttpPost]
            public ActionResult Notification(Notification notification)
            {
                if (ModelState.IsValid)
                {
                    db.Notifications.Add(notification);
                    db.SaveChanges();

                    //var hub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                    //hub.Clients.All.sendNotifications();

                    //NotificationHub obj = new NotificationHub();
                    //obj.SendNotifications();

                }

                return View(notification);
            }

This will call the http Post event but it is not firing the jquery event where i have the signal r hub methos.

Security Exception in Web.Config On Server

When I am using

<trust level="Full"/>

in Web.Config it gives error:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: This configuration section cannot be used at this path. This happens when the site administrator has locked access to this section using from an inherited configuration file.

But When I skip trust level, it gives error

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: That assembly does not allow partially trusted callers.

I had also added [assembly: AllowPartiallyTrustedCallers] in AssemblyInfo.cs, but it could not help.

Any Help will be great.

lundi 7 décembre 2015

partial view in a layout - unable to replace span text

I am working on setting up notification in the layout. I use partial view to display the notification below is my layout:

    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <link href="/Content/ABC.css" rel="stylesheet" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
                <div class="content-wrapper">
                    <div class="float-left">
                        <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
                    </div>
                 @Html.Partial("_Notification") //this is partail view
                        <div class="float-right">

and the partial view is as below.

 <div id="notification">
     @*   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>*@
            <strong>
             <span style="padding-right:3px; padding-top: 3px; display:block;">
                <img src="../../Images/notification.jpg" />
        </span> : </strong>
    </div>
@section Scripts {
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery.signalR-1.1.4.js" type="text/javascript"></script>
    <script src="~/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
        var proxy = $.connection.notificationHub;
        var Count = 0;
        alert(1);
        proxy.client.receiveNotification = function (data) {
            for (var i = 0; i < data.length; i++) {
                var element = data[i];
                if (element.IsRead) {
                    Count = Count + 1;
                }

                $("#notification span").text("Unread messages");
            }
        };
        $.connection.hub.start();
    });


</script>
}

i am unable to replace the span text with the below code .i am using signal r hub class to send the notification. from my admin notification screen i am saving a text and in layout i am getting the count of the unread mesasges and will be dispalying there. Here once i hit save in the notification screen the count is not displaying in the layout

updating multiple records at once in linq

I want to update few records in a table at once.

So I have table like below

enter image description here

these are relevant model classes

AB_Product_vs_Field model class

public partial class AB_Product_vs_Field
{
    public string Product_ID { get; set; }
    public string Field_ID { get; set; }
    public string Field_Value_EN { get; set; }
    public string Field_Value_AR { get; set; }
}

ProductEdit model class

public class ProductEdit
{
    public string Product_ID { get; set; }
    public string ProductTypeID { get; set; }
    public string ProductCategoryID { get; set; }
    public string Subsidary_ID { get; set; }
    public string Field_ID { get; set; }
    public string ProductFieldNameEn { get; set; }
    public string ProductFieldNameAr { get; set; }
    public string ApprovalStatus { get; set; }
    public string Status { get; set; }
    public IList<AB_Product_vs_Field> ListProductFields { get; set; }
    public IList<AB_ProductTypeCategoryField> ListProductLables { get; set; }
}

Once I submit details I want to update all the relevant rows AB_Product_vs_Field table.

Eg: lets say I update Product_ID = 10 records , its should be update all the rows relavant to Product_ID = 10

So I created my linq query like this

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Product_Edit(ProductEdit product)
    {
        AB_Product_vs_Field insertproductvalue = new AB_Product_vs_Field();      
        var user = db.AspNetUsers.Find(User.Identity.GetUserId());


        if (ModelState.IsValid)
        {

            var listInsertproductvalue = new List<AB_Product_vs_Field>(); 

            for (int i = 0; i < product.ListProductFields.Count; i++)
            {
                listInsertproductvalue.Add(new AB_Product_vs_Field
                {
                    Product_ID = product.Product_ID,
                    Field_ID = product.ListProductFields[i].Field_ID,
                    Field_Value_EN = product.ListProductFields[i].Field_Value_EN,
                    Field_Value_AR = product.ListProductFields[i].Field_Value_AR
                }); 

            };

            db.Entry(listInsertproductvalue).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

but here I'm getting following error in db.Entry(listInsertproductvalue).State = System.Data.Entity.EntityState.Modified; line

The entity type List`1 is not part of the model for the current context.

Translate database values dynamically in globalization instead creating new translation tables

My requirement is to implement globalization in an existing ASP.NET MVC project. Using resx. file is good for static values. How can we translate database values. Should we need to create separate translate table for each base tables. Don't we have any other way, because we have nearly 100 base tables.

dimanche 6 décembre 2015

CKEditor not working in IE11

This is the code i've implemented so far

<div class="CommentBox" style="display: none;">
   <div class="editor-field">
     @Html.TextAreaFor(model => model.ObjComment.Description, new { @id = "txtComment", @class = "clsCKEditor" })
   </div>
</div>

And the JQuery code is as follows:

 $("#btnComment").click(function () {        
        var editor = CKEDITOR.instances[txtComment];
        if (CKEDITOR) {
            if (CKEDITOR.instances.txtComment) {
                CKEDITOR.instances.txtComment.destroy();
            }
        }
        $("#txtComment").val('');
        CKEDITOR.replace('txtComment', { uiColor: '#D8D8D8' });

        CKEDITOR.config.htmlEncodeOutput = true;
        $(".CommentBox").show("slow");           
    });

Here, txtComment is an id of the textarea which i'm using as an Editor. On click of the button, the editor will be generated and the div containing this editor will show up.

This is working perfectly as expected in Chrome and Firefox. However,its giving error in IE11 at this line:

var editor = CKEDITOR.instances[txtComment];**'txtComment' is undefined**

Ami missing something? Would you please help me resolve this. Thanks in advance.

PDFTron displays blurry pages when connectivity is slow

My PDFTron Application displays blurry pages when connectivity is slow on android phones. So there is any way/idea to overcome this issue, please suggest.

I'm having trouble loading Modal and able to popup i am newbie in mvc

here it my code where i called from

 <div class="form-group form-inline">
      @Html.LabelFor(model => model.Supplier_ContactId, new { @class = "control-label col-md-2" })
      <div class="col-md-10">
      @Html.EditorFor(model => model.Supplier_Contact.Supp_Email, new { htmlAttributes = new { @class = "form-control" } })
      <a class="btn btn-default" data-toggle="modal" href="@Url.Action("ModelEdit", "SupplierContact", new { id = @Model.ID })"><span class="glyphicon glyphicon-edit"></span>&nbsp;Edit</a>
      @Html.ValidationMessageFor(model => model.Supplier_ContactId, "", new { @class = "text-danger" })
      </div>
</div>

here its my modal view

@model OnLineShoppingCart.Models.Supplier_Contact
@{
    ViewBag.Title = "Edit";
    Layout = null;
}

<div class="modal fade" id="editModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
            </div>

            <div class="modal-body">
                <div>
                    <hr />
                    <div class="form-group">
                        @Html.LabelFor(model => model.Supplier.Company_Name, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DisplayFor(model => model.Supplier.Company_Name, new { htmlAttributes = new { @class = "form-control" } })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Supp_Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Supp_Phone, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Supp_Phone, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Supp_Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Supp_Mobile, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Supp_Mobile, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Supp_Fax, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Supp_Fax, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Supp_Fax, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Supp_Email, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Supp_Email, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Supp_Email, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Supp_Web, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Supp_Web, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Supp_Web, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    @*<div class="form-group">
                            <div class="col-md-offset-2 col-md-10">
                                <input type="submit" value="Save" class="btn btn-success" />
                                @Html.ActionLink("To List", "Index", null, new { controller = "SupplierAddress", id = Model.Id }, new { @class = "btn btn-success " })
                            </div>
                        </div>*@

                </div>
            </div>

            <div class="modal-footer">
                @using (Html.BeginForm("Edit", "Cantact", FormMethod.Post, new { data_bind = "submit: editSupplier" }))
                {
                    @Html.AntiForgeryToken()
                    <div class="form-actions no-color text-center" data-bind="visible: !sending()">

                        <input type="submit" value="Save" class="btn btn-danger" />
                        <button type="button" class="btn btn-default"
                                data-dismiss="modal">
                            Close
                        </button>

                    </div>
                }
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->`enter code here`
@*</div>*@

The issue is when I this line of code Layout = null; I get a blank screen but if I don't I get a normal screen but not a modal window please help me I am new to MVC

Wcf Service partially work only for small files - error:"no endpoint listening -incorrect address/soap action

hye , I wrote a video service that perform video process, when sanding a small video file (380kb) - server accept and perform video process as expected, when sanding a larger video file (20MB) - getting error "no endpoint listening this is often caused by an incorrect address or soap action" or -"404 not found". I added: requestLimits maxAllowedContentLength="400999999" in client side And added httpRuntime targetFramework="4.5" maxRequestLength="5999999"
On service side, still don’t work, help please, Thanks

part of client side - app.config binding name="MessageUserNameSecurity" receiveTimeout="00:10:00" sendTimeout="00:03:00" maxBufferPoolSize="400999999" maxReceivedMessageSize="5999999" readerQuotas maxStringContentLength="400999999" maxArrayLength="400999999" security mode="Message" message clientCredentialType="UserName" security binding

vendredi 4 décembre 2015

Set dynamic name for exported file from crystal viewer c#

Now I need to set name for downloaded file from crystal viewer c#, I've tried this code after search but it is not working

protected void Page_Init(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ReportDocument doc = (ReportDocument)Session["ReportView"];
        doc.SummaryInfo.ReportTitle = ((ReportDocument)Session["ReportView"]).SummaryInfo.ReportTitle;//"MyVeryOwnExportFile";
        CrystalReportViewer1.ReportSource = doc;
        CrystalReportViewer1.BestFitPage = false;
    }
    else
    {
        ReportDocument doc = (ReportDocument)Session["ReportView"];
        doc.SummaryInfo.ReportTitle = "MyVeryOwnExportFile";
        CrystalReportViewer1.ReportSource = doc;
    }
}

And when I tried this code to set dynamic name for exported file by this way it's working but affects on viewer and next page become not work after this change

CrystalReportViewer1.ID="downloaded file name";

after this line I can download file with dynamic names but next page option in view become not working.

edit multiple rows in a table using linq asp.net mvc

I have table like below

enter image description here

Once I pass Product_ID as "01" I want to expand all relevant rows into editor view and once I submit those save those values into this table.

So I create my get method like this

    [HttpGet]
    public ActionResult Product_Edit(string Product_ID)
    {
        Product_ID = "01";

        var product_fields = (from productstatistics in db.AB_Product_vs_Field
                              where productstatistics.Product_ID == Product_ID
                              select new AB_Product_vs_Field
                             {
                                Product_ID = productstatistics.Product_ID,
                                Field_ID = productstatistics.Field_ID,
                                Field_Value_EN = productstatistics.Field_Value_EN,
                                Field_Value_AR = productstatistics.Field_Value_AR
                             }).ToList();

        if (product_fields == null)
        {
            return HttpNotFound();
        }


        return View(product_fields);

    }

but here I'm getting following exception message

The entity or complex type 'project_name.table_name' cannot be constructed in a LINQ to Entities query.

jeudi 3 décembre 2015

select values from three dropdown option list and insert in one cell one value dd/mm/yyyy in asp.net mvc

I faced problem in designing and inserting Date values in dd/MM/yyyy format using jquery datetime picker, so i need to select value from three dropdown option select and insert in one field/cell in mssql database using Razor view in asp.net mvc3.

mercredi 2 décembre 2015

Ignoring null values when using Regex Validator in Data Annotation

I'm having an issue with a nullable field with a Regex Format for a Phone Field

Im using ASP.net MVC 3

Here is my Regex Format Validator in my Data Annotation

[Display(Name = "Phone")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid Phone Number")]
public string Phone { get; set; }

My question is, is there a workaround to ignore the field when the value is null and hide the Error Message to it? Thanks

How do I fix msbuild to prevent 'Could not find a part of the path bin\roslyn\csc.exe'?

I'm trying to correct an issue with building an MVC project in Visual Studio 2015 with a Release configuration. My app is giving me the YSOD:

Could not find a part of the path [...]\bin\roslyn\csc.exe

I can see why it's happening, but I'm having trouble determining the appropriate course of action. The aforementioned roslyn folder is being placed in a sibling folder to my web project folder instead of inside the project's bin directory with the rest of the output, moving the Roslyn folder into the bin directory fixes the issue. In addition to this, it appears as though copies of the csc.exe and other associated executables are being dumped directly into the bin directory directly instead of in the Roslyn directory.

Having checked the answer to Could not find a part of the path ... bin\roslyn\csc.exe, it alludes to the VS2015 template being incorrect and the suggestion is a postbuild event to work around this, but that doesn't seem right to me.

Is there a way to make msbuild put Roslyn in the right place the first time instead of having to complete 2 operations?

Send object in window.refresh kendo grid mvc

in javascript I want to send object in refresh for kendowindow

var object = {
            Number: "dfs",
            Id : 1,
            SelectedId:"dsf"
        }

var window = $("#Window").data("kendoWindow");
        window.refresh({
            url: url,
        data: {
            item: object
        }
    });

Model:

public class Weight
{
   public string Number { get; set; }
   public int Id { get; set; }
   public string SelectedId { get; set; }
}

parameteres are null

public ActionResult Update(Weight item)
{
}

how i can send object to server correctly?

how to save two file from two different html file upload in same function using angularjs and MVC3

here is my all code i am trying to upload small image and large image separate but angularjs not let me allow to do this, it only taking one file but not taking other one. plz anyone help with this. thanks in advance.

<div ng-app="eventModule" >
<div ng-controller="eventController">
<div>
<span >Thumbnail Image</span>
<input type="file" id="fileToUpload" onchange="angular.element(this).scope().selectThumbnail(this.files)"  accept="image/*"  />
</div>
<div>
<span >Large Image</span>
<input type="file" onchange="angular.element(this).scope().selectLargeImage(this.files)" class="LargeImageSubCategory" />
</div>
</div>
<span  data-ng-click="SaveFile()">Submit</span>
</div>

<script>
    var eventModule = angular.module('eventModule', []);
    eventModule.controller('eventController', function ($scope,ArticleService, $http, $sce) {
        $scope.selectThumbnail = function (file) {
            $scope.SelectedThumbnail = file[0];
        }

        $scope.selectLargeImage = function (file) {
            $scope.SelectedLargeImage = file[0];
        }

        $scope.SaveFile = function () {
            $scope.IsFormSubmitted = true;
            $scope.Message = "";
            ArticleService.UploadFile($scope.SelectedThumbnail, $scope.SelectedLargeImage).then(function (d) {
                alert(d.Message);
                ClearForm();
            }, function (e) {
                alert(e);
            });
         };
    });
    eventModule.service("ArticleService", function ($http, $q) {
        this.UploadFile = function (Thumbnail, LargeImage, TitleHeading, Topic, SmallDesc, LargeDesc) {
            var formData = new FormData();
            formData.append("Thumbnail", Thumbnail);
            formData.append("LargeImage", LargeImage);
            // here when i am trying to send two files so controller is not called
            //and function is breaking and alert is comming "File Upload Failed"
            formData.append("TitleHeading", TitleHeading);
            formData.append("Topic", Topic);
            var defer = $q.defer();
            $http.post("/Articles/SaveFiles", formData,
            {
               withCredentials: true,
               headers: { 'Content-Type': undefined },
               transformRequest: angular.identity
            }).success(function (d) {
               defer.resolve(d);
            }).error(function () {
               defer.reject("File Upload Failed!");
            });
            return defer.promise;
         }
    });
</script>

//And My ArticlesController.cs code is

[HttpPost]
public JsonResult SaveFiles(string TitleHeading, string Topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (Request.Files != null)
{
var file = Request.Files[0];
actualFileName = file.FileName;
fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
int size = file.ContentLength;
try
{
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}

mardi 1 décembre 2015

Async file upload in MVC using kendoUpload

I am using file uploader with MVC.

Following is my code :

<div class="demo-section k-content">
<input name="files" id="files" type="file" />
</div>


<script>
$(document).ready(function () {
            var data = JSON.stringify({
            'ReportID': '@(Model.ReportID)',
        });

    $("#files").kendoUpload({
        async: {
            saveUrl: '@Url.Action("save", "UserPage")',

            //removeUrl: "remove",
            autoUpload: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: data,
        }//,
    });
});

on ActionResult I am using following code :

string fileName = Path.GetFileName(files.FileName);
fileName = model.ReportID + "s" + Guid.NewGuid() + extension;

Everything is working fine except the value of model.ReportID its returning NULL every time.

I am missing something here?