lundi 30 novembre 2015

Adding header text to a Pivot Grid on Export to Excel

I'm currently working on adding custom text to the very top of my Excel export from a Pivot Grid (DevExpress MVC). My customer has requested that I place a date time stamp at the top (header area). However, I am so far unsuccessful in figuring out how to tap into the export functionality. Below is my current code in the Controller.

public ActionResult ExportPivotGrid()
{
            Session["QPTReportsData"] = QPTReport.GetReportData(Helper.OfficeName);

            XlsxExportOptionsEx xopt = new XlsxExportOptionsEx();
            xopt.AllowHyperLinks = DefaultBoolean.True;
            xopt.ExportHyperlinks = true;
            xopt.TextExportMode = TextExportMode.Text;
            xopt.ExportType = DevExpress.Export.ExportType.WYSIWYG;

            return PivotGridExtension.ExportToXlsx(new PivotGridSettings()
            {
                Name = "ExportPivotGrid",
                BeforePerformDataSelect = (s, e) =>
                {
                    MVCxPivotGrid PivotGrid = s as MVCxPivotGrid;
                    string layout = (string)(Session["QPTCurrentPivGridLayout"]);
                    PivotGrid.LoadLayoutFromString(layout, DevExpress.Web.ASPxPivotGrid.PivotGridWebOptionsLayout.DefaultLayout);
                }
            }, Session["QPTReportsData"], true, xopt);

}

From what I can tell, there is no simple solution. Any help would be much appreciated.

Razor syntax binding attributes not working after migration from MVC 3 to MVC 5

After migration from MVC 3 to MVC 5 construction of setting attributes in html elements stopped to work.

<div attr="@model.Id">...</div> //output: <div>...</div>
<div class="@model.ClassName">...</div> //output: <div>...</div>

only custom attributes that are begining with data- are working

<div data-attr="@model.Id">...</div> //output: <div data-attr="7">...</div>

the workaround is to use @Html.Raw method

<div @Html.Raw(string.Format(@"class=""{0}""",model.ClassName))>...</div> //output: <div class="className">...</div>

Any ideas what happened and how to restore previous behavior?


Configuration

<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net451" />
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net451" />
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net451" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net451" />

dont call Action Post in mvc when use enctype

In my project I have View Like this :

@using (Html.BeginForm(MVC.Admin.Sys.ActionNames.Index, MVC.Admin.Sys.Name, FormMethod.Post, new { enctype = "multipart/form-data" }))
{...}

And My actions Are :

 [HttpGet]
    public virtual ActionResult Index()
    {...}
[HttpPost]
public virtual ActionResult Index(EditSysInfo sysInfoViewModel,HttpPostedFileBase file)
    {}

in View I have :

 <input type="file" name="file"/> ... submit button

but when Click On the submit button dont cann Post action , and redirect to httpget Action . yesterday its work fine . I dont know why doesnt run ? Today I just Install Microsoft.AspNet.Web.Optimization . when Change to this :

@using (Html.BeginForm())

Its work fine , but cant post file to action this way .

I try to getting file in Action Like This :

HttpPostedFileBase logo = Request.Files.Get("file");

Allways Count Request.Files is Zero.

thanks .

ireports generation with mvc-asp.net

I've been working on ireports recently, asp.net mvc 3.0

I've a view with a textbox 'empsrch'. I need to pass this value to ireports jrxml query. I dont know how to bind value in query without parameters.

All I want to know is how to bind value of a textbox from a mvc view to jrxml - query

my jrxml query is like this:

<![CDATA[select ROW_NUMBER() OVER(order by EDM_EMP.Updatedon desc)  AS [S.No],* from (
select module as ModuleName, PageName, field as FieldName,LTRIM(RTRIM(isnull(dbo.GetEmployeeID(R.empuid),' '))) as EmployeeID,
LTRIM(RTRIM(isnull(dbo.GetEmployeeName(R.empuid),' '))) as EmployeeName, oldvalue as OldValue, newvalue as NewValue, isnull(dbo.GetEmployeeId(U.EmpUID),' ') as UpdatedBy,
case edm_Employee.IsResigned
when 1
then 'Resigned'
when 0
then 'Live'
else ''

end as EmployeeStatus,
CONVERT(VARCHAR(19),R.updatedon) as UpdatedOn,
R.EmpUID as EmpUID ,D.Name as dgname

from Audit_Masters_Log R
left join Users U on U.UserUID=R.updatedby
left join edm_Employees as edm_Employee on edm_Employee.EmpUID=R.EmpUID
left join edm_um_Designation as D on D.DesignationID = edm_Employee.DesignationID
WHERE edm_Employee.FirstName like $P{Name} and EmployeeID like $P{EmployeeID} and R.UpdatedOn between $P{FromDate} and $P{ToDate} and D.Name in ($P!{Designations})) EDM_EMP]]>

need the textbox value for where condition to filter results?

samedi 28 novembre 2015

dont cache layout with DonutOutputCache

I use DonutOutputCache for caching data .

In my view I want dont cache Layout , for do this ,I use bloew code:

@{
@Html.Action(MVC.INDEX.ActionNames.GetLayout, MVC.controller.Name, true);
   var layoutname=TempData["layout"].ToString();
   this.Layout = layoutname;
      }

but this block dont run each time . how can I do it ?

My Layout set daynamicaly.

Please help me with Spring MVC 2

description of duties 1) View survey should form ( questions and stylish in ) 2) View poll rating should be done ( should ask questions and offer a choice made ​​in the 1st and stylish in ) 3) View the survey should show results. ( Questionnaires , voting rates distractors )

Hint: Entered questionnaires and at different times been given to you through a lisa transport and kept constantly updated with the current session .

Set selected item in selectlist

IEnumerable<Product> Get();

I get items and create collection of this objects

 public class Product
    {
        public int? ProductId { get; set; }
        public string ProductName { get; set; }
    }    

Name = new SelectList(Get(), "ProductId", "ProductName", model.Id)

 @Html.DropDownListFor(m => m.Id, Model.Name)

In Model

public int Id { get; set; }

public SelectList Name { get; set; }

Always on page selected item is first item

How I can set selected item by model.Id?

why error Method not found: 'Int32 PagedList.IPagedList.get_PageIndex() occurs

I am working on Paging in Mvc 3, but when i trying to run the page it gives me error

Method not found: 'Int32 PagedList.IPagedList.get_PageIndex()

Here is my code:

public class EmployeeController : Controller
{
    private myContext db = new myContext();

    public ViewResult Index(int? page)
    {
        int pageSize = 20;
        int pageNumber = (page ?? 1);
        return View(db.tbMovie.OrderByDescending(t=> t.Movie_ID).ToPagedList(pageNumber,pageSize));
    }
}

Here is View

@using PagedList.Mvc;
@using PagedList;
@model IPagedList<Cmedia.Models.Employee>

@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.EmployeeID)
    &nbsp;
    @Html.DisplayFor(modelItem => item.EmployeeName)
    <br>
}
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))

Everything looks fine, but i am still getting error.

vendredi 27 novembre 2015

Resposinve webdesign and positioning of elements

I have a small widgetbox on my webpage. This widgets box contains these elements:

<table class="absence-widget-table">
    <tr>
        <td class="absence-widget-left">
            <i class="fa fa-chevron-left" title="Next" aria-describedby="ui-tooltip-1"></i>
        </td>
        <td class="absence-widget-center" id="absence-date-container">
            @Html.Partial(MVC.ActivityWidget.Views.Partials.MyActivityAbsenceDateChanger, Model)
        </td>
        <td class="absence-widget-right">
            <i class="fa fa-chevron-right" title="Previous"></i>
        </td>
    </tr>
</table>

And these elements have these styles in my css file:

.center-absence-widget-left {
    position: relative;
    left: 604px;
    padding-top: 13px;
    padding-bottom: 10px;
    cursor: pointer;
}

.center-absence-widget-right {
    position: relative;
    left: 640px;
    padding-top: 13px;
    padding-bottom: 10px;
    cursor: pointer;
}

.center-absence-widget-center {
    position: relative;
    left: 620px;
    padding-top: 10px;
    padding-bottom: 10px;
    text-align: center;
    white-space: nowrap;
    width: 15%;
}

what i want to know is how do i add responsive design for these elements so when the page is not opened in a screen with less resolution, then the html elements responds to that and adjusts to it?

can anyone help with this ?

jeudi 26 novembre 2015

value of a variable reusing in JavaScript

I have following controllers

[HttpPost]
public JsonResult CreateDirectory(string product_ID , string type)
{
   .......

 return Json("OK");

}

[HttpPost]
public ContentResult UploadFiles(string folderid, string foldertype)
{
  .........
}

and using following script I'm trying to call and pass parameters to CreateDirectory controller method and UploadFiles controller method

<script type="text/javascript">

    var productid = "sample";

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

        $.ajax({
            url: '@Url.Action("CreateDirectory", "Home")',
            data: { product_ID: $('#Product_ID').val(), type: "type1" },
            type: "POST",
            dataType: "json",            
            error: function (response) {
                alert(response.responseText);
            },
            success: function (response) {
                if (response === 'OK')
                {
                    productid = $('#Product_ID').val();
                    alert(productid)
                }
                else
                    alert("errro");
            }
        });
    });  

  $("#idd").fileinput({
        type: 'POST',
        cache: false,
        uploadUrl: '@Url.Action("UploadFiles", "Home")',
        enctype: 'multipart/form-data',
        overwriteInitial: true,
        uploadExtraData: { folderid : productid , foldertype : "type1" },            

    });   

</script> 

Issue:

I'm assigning new value for var productid in click JavaScript event of above script.

like this productid = $('#Product_ID').val();

then I try to reuse that newly assigned value for productid reuse/reassign in fileinput JavaScript event

like this folderid : productid

but I cannot see newly assigned value for folderid , when Its calling to UploadFiles method I can see folderid is value is sample

Keyboard shortcut for MVC application

How can we use Keyboard shortcut for MVC application?. My requirement is when I press Ctrl+U , I want to load my home page and when I press Ctrl+T, nedd to open another page. How it is possible in client side. Please help.

Regards Sreyas MN

How to proceed with the given example?

In order to get a nice intro to asp.net mvc i started working on w3schools example. this example is super easy to understand and follow. I did exactly as shown in the below tutorials. [http://ift.tt/1Otmpye]

All steps prior to controller addition work fine But when i try adding a controller i get the below error:


Microsoft Visual Studio

Unable to retrieve metadata for 'MvcApplication1.Models.MovieDB'. Unable to cast object of type 'System.Data.Entity.Core.Objects.ObjectContext' to type 'System.Data.Objects.ObjectContext'.

I have looked for the similar error online and came across solutions that were created by using lower versions of entity framework. In my project i have installed entity framework 6 using nuget packages.

Guide me where I am wrong. I don't have any previous entity framework knowledge nor do I understand which suits which version of mvc.

As the example guides I created a asp.net mvc 3 web application using razor and html 5.

Please guide me where I am wrong or how to solve this?

MapSignalR is missing with vs 2010

I have added signal R as below install-package Microsoft.AspNet.SignalR -Version 1.1.3 . to my project in vs 2010 .net version 4.0.....MapsignalR() method is not found in the owin startup class.public void Configuration(IAppBuilder app) { app.MapSignalR(); } this is the owin startup class This gives a message Owin.Iappbuilder doesnt contain a definition of MapSignalR. I am beginner in Signar .Any help will be appreciated to resolve the same. I have tried updating and reinstalling owin and signal R . But no luck

mercredi 25 novembre 2015

session management in distributed asp.net applications

I have 2 webapplications one in webforms and another in mvc3. We have the requirement of clubing both and provide an interface for the functionalties in a dashboard.

2 task's are identified
1. SSO
2. Session management

If somehow SSO is possible how problem 2 can be sorted.
Now i will have 3 applications one for showing login and dashboard and the above said 2 applications.

  1. How to perform session timeout across application
    Say if 3 apps have same session timeout and after login in app1 and if i moved to app2, since am active app1 must not timeout

  2. How to communicate applications using session (if possible)

Any help will be appreciated. How should i design such a distributed system

C# MVC RouteBase routing too many redirects

I have this custom routing system where i will get the paths, controllers, views and areas from my DB and set them according to the requested path.

My problem right now is that when i try to access one page it gives me the too many redirects response.

What happens in this area is:

  • User access page and fill a form;
  • Form is posted using AJAX and then a redirect is made from jquery;
  • User makes an appointment or generate a voucher;

If the user tries to return to the previous page by typing it on the browser( i don't have any button to that link ) he gets the too many redirects problem.

Since the code is kind of big i'm going to post it here: http://ift.tt/1Tf7nxO

I only left out my DB logic.

What could be doing this ? I only could see the problem in this area but i don't know for sure it isn't happening in other areas.

use jquery string in form GET mehtod

i am trying to replace characters using jquery and i want to pass it into a form action get method. Right now i an getting the value of a text field and sending it to the get method. I want to check and replace the a character in the string and then pass it afterwards.. How do i do that?

my code:

    <li>
        <form action="Citizen/CitizenSearch" method="get">
            <input class="cpr-search" type="text" name="cpr" />
            <input class="cpr-search" name="submit" type="hidden" value="Søg" />
        </form>
    </li>
<script type="text/javascript">
    $('#Søg').keypress(function (e) {
        var cpr = $('#cpr').val();
        if (cpr.indexOf("-") >= 0) {
            cpr = cpr.replace("-", "");
        }
        if (e.which == 13) {
            $(this).blur();
            $('#submit').focus().click();
        }
    });
</script>

i am very new to mvc and web development.. can anyone help ?

mardi 24 novembre 2015

NoClassDefFoundError on ASP.net MVC3

Iam newbie to java, I have this applet embedded inside the view but i am getting the error

NoClassDefFoundError

/Content/HelloApplet (wrong: name:HelloApplet)

and this is the code inserted the view

**<object type="application/x-java-applet" width="400" height="400">
  <param name="archive"  value="@Url.Content("~/Content/HelloApplet.jar")" />
  <param name="code"       value="@Url.Content("~/Content/HelloApplet.class")"  />
  <param name="HelloApplet" value="true" />
</object>**

any help?

Return to redirect, then call JS function

Displaying a Jquery DataTable on screen. Row is selected, new Trial date is selected for that row. Button pressed and necessary row is updated in the controller POST. if (Request.HttpMethod == "POST")All works fine.

I then use a return RedirectToAction("Users", "AziMapOrgs"); to recall the function to update the datatable 'AllOrgsDataTable' which I thought was going to update the jquery dataTable in the view. But it turns out I ALSO need to call function setupPage() in the view to redraw the dataTable.

//controller
 public ActionResult Users(string selectedCheckBoxes, string newDate)
        {
            Models.AziMapOrgsModel orgModel = new Models.AziMapOrgsModel();

            //When Extend Trial button is pressed will be a post back so update users to new Trail End Date
            if (Request.HttpMethod == "POST")
            {
                if (selectedCheckBoxes != "" && newDate != "")
                {
                    orgModel.UpdateUserTrial(selectedCheckBoxes, newDate);
                    return RedirectToAction("Users", "AziMapOrgs");
                }
                //after new exiry date set run through code again to update table with new dates
            }

            //Display all users in dataTable and set ID to 'IDColumn' in jquery dataTable
            ViewModels.AziMapOrgsVM orgViewModel = new ViewModels.AziMapOrgsVM();
            orgViewModel.AllOrgsDataTable = orgModel.GetOrganisations();
            orgViewModel.IDColumn = "ID";

            return View(orgViewModel);
        }

//Users View
    function SetupPage() {
    //draw dataTable
    var table = $('#OrgTable').DataTable();
    if (table.length > 0) {
        table.DataTable({
            "bSort": false,
            "sScrollX": true,
            "bLengthChange": false,
            "scrollY": "75%",
            "scrollCollapse": true,
            "paging": false,
            "oLanguage": {
                "sZeroRecords": "No such record exists"
            },
            "columnDefs": [
            { type: "OrgFreeTrialEnd", targets: 0 }
            ]
        });
    }
    table.draw();

open browser.ShowSaveAsDialog() in Client side

How to Write browser.ShowSaveAsDialog() in client side?. I have an asp.net mvc application which need to open the dialog box in Webbrowsercompleted event.

Regards Sreyas MN

value of a Model property send as a parameters to controller method in bootstrap-fileinput

I'm using the Bootstrap File Input plugin and I'm trying to get the product_ID Model property value from following form and send as a parameters to controller method.

this is the form

@model project_name.Models.relavantmodel

@using (Html.BeginForm())
{
   @Html.EditorFor(model => model.Product_ID)

   <input id="idd" type="file" class="file">

   // form sumbit button
   <input type = "submit" value="Create" /> 

}

I have following controller

    [HttpPost]
    public ContentResult UploadFiles(string product_ID, string type)
    {
      .........
    }

Also I refer this question also

I'm trying to use following script for call upload method and send parameters


Approach 1 :

$("#idd").fileinput({
    type: 'POST',   
    uploadUrl: '/Home/UploadFiles', // server upload action
    uploadExtraData: { 'product_ID': document.getElementById('#Product_ID').value, 'type': "marketing_materials_EN" },

});


Approach 2 :

$("#idd").fileinput({
    type: 'POST',        
    uploadUrl: '@Url.Action("UploadFiles", "Home")',
    uploadExtraData: { product_ID: $('#Product_ID').val(), 'type': "marketing_materials_EN" },


Approach 3 :

 $("#idd").fileinput({
        type: 'POST',        
        uploadUrl: '@Url.Action("UploadFiles", "Home" ,new {product_ID = @Model.Product_ID , type = "marketing_materials_EN" })',

But none above approach I cannot get the product_ID that I'm inserting, .But I can send type

Once put I debug point at controller method I can see type value is getting

enter image description here

and product_ID getting NULL

enter image description here

How can I get the product_ID here

lundi 23 novembre 2015

send value to controller using html.actionlink

I am passing value from html.actionlink to the controller. But the problem is in controller, value is not being fetched. I don't know what is the problem.

Here is my code :

View :

    @Html.ActionLink("Copy", "Copy", "Item", new { id = item.Item_code}, null)

Contoller :

       public ActionResult Copy(int id)
       {
                 // Logic here
                 return View();
       }

Thank you !

sending value of model property as an ajax parameter

I have following form in my view-page

@using (Html.BeginForm())
{
   @Html.EditorFor(model => model.Product_ID)

}

<input id="idd" type="file" class="file">

I want to send above inserted Product_ID as ajax object route value before click the submit button of this form.for that I created it like this product_ID = Model.Product_ID but this product_ID getting null.

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

    $.ajax({
        url: '@Url.Action("CreateDirectory", "Home",new { product_ID = Model.Product_ID })',
        type: "POST",

controller

    [HttpPost]
    public JsonResult CreateDirectory(string product_ID)
    {
      ...........
    }

EDIT

using alert inside above script I try to show that Product_ID

alert('@Model.Product_ID');

same results not showing value

Pass a List to View In MVC

I am passing a list values to my View. But I am getting an error of "The model item passed into the dictionary is of type 'System.Collections.Generic.List". Here is my controller action:

public ActionResult Index()
    {
        Test t = new Test();
        List<Customer> myList= t.GetData();
        return View(myList);
    }

Here is the view:

@model List<AsyncActions.Models.Test>
@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>
<table border="1" cellpadding="4">
    @foreach (var row in Model)
    {
    <tr>
        @*<td>@row."CustomerID"</td>
        <td>@row."CustomerCode"</td>*@
    </tr>
}

here is my model:

namespace AsyncActions.Models
{
public class Test
{
    public List<Customer> GetData()
    {
        try
        {
            Customer c = new Customer();
            List<Customer> cst = new List<Customer>();
            for (int i = 0; i < 10; i++)
            {                    
                c.CustomerID = i;
                c.CustomerCode = "CST"+i;
                cst.Add(c);
            }
            return cst;
        }
        catch (Exception)
        {
            throw new NotImplementedException();
        }

    }
}
public class Customer
{
    public int CustomerID { get; set; }
    public string CustomerCode { get; set; }
}
}

I have already tried removing List<> from view. When I do that, I am getting an error as "foreach statement cannot operate on variables of type 'AsyncActions.Models.Test' because 'AsyncActions.Models.Test' does not contain a public definition for 'GetEnumerator". I have tried so many things. I checked this link , but that didn't solved my issue. I am unable to find out what I have missed. Any help is much appreciated.

MVC: Should we have any if else OR other logical statement in View?

THIS IS MY MODEL:

public class Employee
{
    public string EmployeeName { get; set; }
    public string Address { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int Salary { get; set; }
}

THIS IS MY VIEW:

<div>
    Employee Detail<br />
    Employee Name : @Model.emp.EmployeeName<br />
    Address : @Model.emp.Address <br />
    Age : @Model.Age
    <span style="color:@Model.SalaryColor">Salary : @Model.emp.Salary</span>
     @if (Model.Salary > 20000)
     {
         <div1>..</div1>
     }
     else
     {
        <div2>..</div2>
     }
</div>

With this if/else, i am inserting business logic in the UI Layer/ View of MVC. But i am clueless how can this be avoided?

I know that this would make UI tightly bound with Business logic which is not good. Any way i can avoid this?

dimanche 22 novembre 2015

Resource File not recognised by Intellisence

I have three resource files in a Resource folder which are Account, Home and Novel. When coding the only resource file I can find with:

Resources.

Is the Home file. I have all three set to public and as far as I can see there's no difference between the three.

Home Designer File:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Resources.Home {
    using System;


    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Home {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Home() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TheNovelMachine.Resource.Home", typeof(Home).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to &lt;h1&gt;Your &lt;span&gt;Story&lt;/span&gt; Starts &lt;span&gt;Here&lt;/span&gt;...&lt;/h1&gt;.
        /// </summary>
        public static string Heading {
            get {
                return ResourceManager.GetString("Heading", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec blandit purus varius est ornare vehicula. Sed eget hendrerit justo, nec pulvinar quam. Etiam eget tellus nunc. Nullam fermentum nunc enim, at placerat eros convallis eget. Aenean sed elit non nisl tempor molestie. Fusce porta est ut sem faucibus tincidunt. Ut facilisis dapibus lacus, sed mattis justo accumsan et.&lt;/p&gt;
        ///
        ///    &lt;p&gt;Sed ut lobortis sapien. Morbi sit amet nulla non leo pharetra aliquam. Cras vel laoreet orci, ac imperdiet quam. Pell [rest of string was truncated]&quot;;.
        /// </summary>
        public static string Intro {
            get {
                return ResourceManager.GetString("Intro", resourceCulture);
            }
        }
    }
}

Novel Designer File:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TheNovelMachine.Resource {
    using System;


    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Novel {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Novel() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TheNovelMachine.Resource.Novel", typeof(Novel).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to We want to know what it&apos;s all about!.
        /// </summary>
        public static string AbstractRequired {
            get {
                return ResourceManager.GetString("AbstractRequired", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Action and Adventure.
        /// </summary>
        public static string GenreAction {
            get {
                return ResourceManager.GetString("GenreAction", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Children&apos;s.
        /// </summary>
        public static string GenreChildren {
            get {
                return ResourceManager.GetString("GenreChildren", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Drama.
        /// </summary>
        public static string GenreDrama {
            get {
                return ResourceManager.GetString("GenreDrama", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Fantasy.
        /// </summary>
        public static string GenreFantasy {
            get {
                return ResourceManager.GetString("GenreFantasy", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Historical.
        /// </summary>
        public static string GenreHistory {
            get {
                return ResourceManager.GetString("GenreHistory", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Horror.
        /// </summary>
        public static string GenreHorror {
            get {
                return ResourceManager.GetString("GenreHorror", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Mystery.
        /// </summary>
        public static string GenreMystery {
            get {
                return ResourceManager.GetString("GenreMystery", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Choose a Genre, so your novel knows where to live!.
        /// </summary>
        public static string GenreRequired {
            get {
                return ResourceManager.GetString("GenreRequired", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Romance.
        /// </summary>
        public static string GenreRomance {
            get {
                return ResourceManager.GetString("GenreRomance", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Satire.
        /// </summary>
        public static string GenreSatire {
            get {
                return ResourceManager.GetString("GenreSatire", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Sci-Fi.
        /// </summary>
        public static string GenreScifi {
            get {
                return ResourceManager.GetString("GenreScifi", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Your novel needs a name!.
        /// </summary>
        public static string TitleRequired {
            get {
                return ResourceManager.GetString("TitleRequired", resourceCulture);
            }
        }
    }
}

How to generate "1. Do the homework" from "@Model.Number. @Model.Task" in razor?

I need to generate a string which looks like variable, dot, space, another variable.

The @Model.Number. @Model.Task or @(Model.Number). @(Model.Task) or @{Model.Number}. @{Model.Task} doesn't seem to compile.

The @Model.Number<text>. </text>@Model.Task works, but it generates a trashy <text> tag in the resulting html.

If I place all of these on a separate line:

@Model.Number
. 
@Model.Task

then the result will render with an extra space between the number and the dot.

The @Model.Number@:. @Model.Task doesn't compile either.

samedi 21 novembre 2015

Unable to Update User status after logged out in asp.net using single R

http://ift.tt/1aPclzd

I have used above links code and modify this code and add some line in above linked project as below lines.

In chat.aspx....

  chat.client.onUserDisconnected = function (id, userName) { $.connection.hub.start(); }


In Chat.cs...

public override Task OnDisconnected()
        {
            var newUsers = OnlineUser.userObj.FirstOrDefault(item => 
                item.connectionId  == Context.ConnectionId);
            if (newUsers != null)
            {
                var id = newUsers.connectionId;
                OnlineUser.RemoveOnlineUser(id, newUsers.userName,        newUsers.userId);
            }

            //return Clients.All.joined(Context.ConnectionId, newUsers);
            return Clients.Caller.OnlineStatus(Context.ConnectionId, newUsers); 
        }


After added abobe line in project then user status update but it is not update on any user page who are online. Please help me to resolve this issues.

vendredi 20 novembre 2015

Asp.Net MVC data annotation custom attribute is not working

I need implement a cusotm attribute then using asp.net data annotation to validate a class. Unfortunately, the attribute class is not called at run time. Please help me out. Many thanks.

enter image description here

display current user data in MVC

In MVC i want to authenticate users,they must not be able to see other user data when logged on. Users must be able to CRUD their own data only. I have created two model:

public class User
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public List<Product> Products { get; set; }
}


public class Product
{
    public int productId { get; set; }
    public string productName { get; set; }
    public double productPrice { get; set; }

    public User Users { get; set; }
}

And i have product controller, where i want to authenticate users from CRUD other users data.

onhashchange event doesn't detect changes between "/Home/Index" and "/" - ASP.NET MVC3

I'm working in a ASP.NET MVC3 web app, and my problem is the following: I want to detect URL changes using:

window.onhashchange = function (event) { 
    //some stuff...
};

and it works perfectly... But, it works perfectly while in the url always appears:

'localhost:[port]/Home/Index'

or in some cases, url changes to:

'localhost:[port]/Home/Index#'

When the user changes the url (for example, he deletes '/Home/Index'), the pages is reloaded (the url is 'localhost:[port]/') but when user presses back button and back again to '/Home/Index' onhashchange event doesn't detect this change. Why? '/Home/Index' and '/' is the same?

How to save Web page complate in MVC (Webpage,complete(*.htm;,html))

How can we programatically save complete web page in MVC?

I mean I want to save page as " Webpage,complete(*.htm;,*html)" style. I used the WebClient but it save only the HTML page. I awnt both page as well as images etc.. like saving webpage CTRL + s as Complete webpage. Please share if anyone knows

Regards Sreyas MN

HTML JavaScript form.submit variables

I've got a simple form that takes a selection of checkboxes and a date range. Upon clicking a button, this gets sent to my MVC controller via three variables - all strings; my issue is that one of the variables always comes back null whereas the other two work correctly.

Var 1 and 2 as such:

$("[name=start]").val(moment().subtract('month', 1).startOf('month').format('DD/MM/YYYY'));

$("[name=end]").val(moment().subtract('month', 1).endOf('month').format('DD/MM/YYYY'));

var 3 =

$("[name=trust]").val((dataList));

dataList is a string of names, seperated by "," e.g. "Craig,Ben,Tom,Harry" - ideally I wanted this to be a list but I couldn't figure out a way to pass it to the controller so I'm using this workaround.

When the code reaches the controller, var 1 and 2 arrive correctly; but var 3 is always null despite dataList always being populated with the correct data.

I can see it's because the properties of HTML variable 'trust' has .val() which contains the correct data, but when passing it to the controller it must pass the object. My confusion is that var 1 and 2 are written in exactly the same way, so I don't understand how it passes the correct property whereas var 3 passes the object.

<form action='@Url.Content("~/Report/GenSLM/")' method='post' name='slmForm'>
    <input type="hidden" name="trust" value="" />
    <input type="hidden" name="start" value="" />
    <input type="hidden" name="end" value="" />
</form>

Here is a screenshot of what I'm talking about: enter image description here As you can see in the JS watch, var start is an object which has .val() = "01/10/2015", var trust again is an object which has .val() = "data1,data2,data3". When passing them to the controller, start and end are received correctly from .val() but trusts arrives as the object - not .val().

Can anyone explain whats going wrong or where I have gone wrong? If any further details are needed please do let me know.

Custom ModelValidatorProvider - get access to containertype property

I have the following class (simplified for question)

MyPageData.cs
{
    string PageName {get;set;}
    List<Field> Fields {get;set;}
}

Which contains a collection of another class (fields for the user to enter).

Field.cs
{
     string Id {get;set;}
     object Value {get;set;}
}

And this is bound to the view in a manner like below

Data.cshtml
{
   @model MyPageData

   @using(Html.BeginForm())
   {
     @foreach(var field in fieldsData)
     {
          var index = MyPage.Fields.IndexOf(field);
          @Html.TextBoxFor(t => t.MyPage.Fields[index].Value);
     }
   }
}

Some of the field values require validation. Having read around a bit, I was hoping to do this with a Custom ModelValidatorProvider, but this only seems to provide me with details of the property that I am trying to bind, and the page object model as a whole (example code below)

public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
      protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
        {
            if(metadata.PropertyName == "Value" && metadata.ContainerType == typeof(Field))
{
    var id = **Some magic to work out the id of the Field that this value property is set for;**
    once we have the id then we can work out what validators to apply 
}            

            return base.GetValidators(metadata, context, attributes);
        }
}

So the problem that I am having is working out which field this 'Value' property is being set for. The container type shows as Field.cs, but I can't seem to get any values for this - I can get the container values, but this returns the MyPageData.cs with all of the fields, so I can only then match it by value.

Any ideas anyone?

Extract text from a list of Html elemnts using jquery

I have an issue when trying to get the text out of a list of elements in jquery.

I have a list of elements in a varible.. What i want is to extract the text from each elements and insert it into a list of strings with comma seperation.

my code:

var names = $('input.select:checked').closest('tr').find('.citizen-name');
for (var i = 0; i < names.length; i++) {
                ???;
            }

how can i do this?

thanks for the help!

jeudi 19 novembre 2015

Why does Url.RouteUrl Requires Optional Parameter and Ignores RouteName?

Here is my route configuration. Given 2 Routes that take in different parameters, Test1Route works perfectly fine as I'd expect.

        routes.MapRoute(
            name: "Test1Route",
            url: "{controller}/{action}/{optionalParam}",
            defaults: new { controller = "Test1Controller", action = "Index", optionalParam = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Test2Route",
            url: "{controller}/{action}/{param1}/{optionalParam}",
            defaults: new { controller = "Test2Controller", action = "Index", param1 = 10, optionalParam= UrlParameter.Optional }
        ); 

But Test2Route, when added like this, completely fails using RouteUrl:

@Url.RouteUrl("Test2Route", new {action = "SomeAction", param1 = 5})

The url it makes may be: http://site/Test1Controller/ but no parameters show up so this is invalid. Debugging I may get an exception like:

A public action method '5' was not found on controller Test1Controller

Why would it be using Test1Controller when I specifically name it "Test2Route"? If I omit the name and use something incorrect - it throws an exception saying that the named route can't be found. That makes sense. But yet when specified correctly, its ignoring the name!

Lets say I go ahead and explicitly name the controller:

@Url.RouteUrl("Test2Route", new {controller = "Test2Controller", action = "SomeAction", param1 = 5})

The url becomes http://site/Test2Controller/ with no parameters. Same exception about action method not found but with Test2Controller.

Now, lets say I explicitly name optionalParam which I expect not to have to do.

@Url.RouteUrl("Test2Route", new {controller = "Test2Controller", action = "SomeAction", param1 = 5, optionalParam = 6})

The result is correct and works!

http://site/Test2Controller/5/6

  • What could be causing the Routes to default over to Test1Route despite the Test2Route being specified explicitly in the RouteUrl call?
  • Why do I need to explicitly use controller and optionalParam in the parameters? This SO demonstrates that it was necessary for someone else, but no workaround or why.

Note that upon researching, I've found some SOs that mention SomeAction didn't have [HttpGet] or [HttpPost] or both or shouldn't have either specified. I've tried all combinations regarding those flags and they seem irrelevant to the parameter issue I'm experiencing.

Also note that the routing works if I'm not using RouteUrl. Typing out http://site/Test2Controller/500/ or http://site/Test2Controller/500/600 works fine too.

Ajax BeginForm works randomly on my customers computers

I have a simple Ajax.BeginForm in my MVC3 solution. Site is working just fine for me and 95% of my users, but from time to time I get complains from some users that Submit button is not working. No action is made when thous users click submit on my page. As I wrote it works for big majority of users.

Users that this is not working for have tried multiple browsers and OS. I even got info from users browser console and there is no errors.

Anyone have an idea of what the issue can be?

Thank you!

TypeError: validator is undefined in jquery.validate.js

I have following form.

enter image description here

once I click that Go to Next Section Button I can direct to next section in this form.

Here the whole code for this view and this the Layout file for that view page

But now Once I click I'm not getting any response and I cannot goto next page I'm getting following error.But this error occur in Firefox only , once I change debugging to Chrome this is working.

TypeError: validator is undefined file_path/jquery.validate.js

this is that error view

Error view 1

enter image description here

Error view 2

enter image description here

Bugzilla debugger pointed out following section ([if (validator.settings.rules)]) of jquery.validate.js file has the error

staticRules: function( element ) {
    var rules = {};
    var validator = $.data(element.form, "validator");
    if ( validator.settings.rules ) {
        rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
    }
    return rules;
},

mercredi 18 novembre 2015

Issue in Redirecting on Action Filter onActionExecuting

I have an issue in redirecting to the external URL Requirement I want to redirect to an external URL whenever the session is expired .... I have a separate class in which I override the definition of onActionExecuting Action Here is my Code ...

public class SessionExpireAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       // var redirectUrl = "http://www.google.com";
        var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();

        if (isAjaxRequest)
        {
            filterContext.Result = new RedirectResult("http://www.google.com");
            return;
        }
        base.OnActionExecuting(filterContext);

    }
}

I Have try almost all the solution that I could find on Stack Over Flow but my problem is not still solved.

Is there is any issue related to pipeline execution of controller filters if so kindly guide me ...

Thanks in advance.

i want to add an id after localhost portnumber using rules in web.config

this is my code

<rule name="adding Id after PortNumber" patternSyntax="Wildcard" stopProcessing="true">
        <match  url="(.*)" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="{HTTP_HOST}/12312312" negate="true"/>
        </conditions>
        <action type="Redirect" url="{HTTP_HOST}/{R:1}"/>
      </rule>

but when i run this i am getting the url path as 'http://localhost:49363/' but i want 'http://localhost:49363/12312312'

how to redirect to other page if mvcRouting failes

this is my RouteConfig.cs and i am using isValidAppId class to match the appid which comes in url to the 'modelApplicationId' which i have stored in web.config

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
namespace SCS.Web
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
           "ApplicationRoute",
           "{appId}/{controller}/{action}/{id}",
           new { controller = "Account", action = "SignIn", id = UrlParameter.Optional },
           new {

               isValidAppId = new isValidAppId() 

           }
       );
    }



}


public class isValidAppId : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var isValid = false;
        if (values["appId"] != null && WebConfigurationManager.AppSettings["ModelApplicationId"] != null)
        {
            if (values["appId"].ToString() == WebConfigurationManager.AppSettings["ModelApplicationId"].ToString())
                return isValid = true;
        }

        // return true if this is a valid AppId
        return isValid;
    }
}

}

if the isValidAppId returns false i want to redirect to other Error.cshtml page.

Format image in generating excel form in asp.net

I would like to ask if is it possible to format image in excel when generating it from the HTML Page? I tried to do it but still it has been rendered with its actual size. In showing the excel form, I am just using the table tag. Anyone who can help me with this. Thanks.

mardi 17 novembre 2015

how to prevent set default value if property has already value in edit view and model in mvc

I am working on edit view, i want set the default value for Create_Time and Last_Update

here is model

public class TVSerialEpisode
{
    private DateTime _CurrentTime = DateTime.Now;
    [Key]
    public Int64 Video_ID { get; set; }
    public string Episode_Name { get; set; }
    public string Description { get; set; }
    public bool Is_Active { get; set; }
    public DateTime Create_Time
    {
        get { return _CurrentTime; }
        set { _CurrentTime = value; }
    }
    public DateTime Last_Update
    {
        get { return _CurrentTime; }
        set { _CurrentTime = value; }
    }
}

here is controller

 public ActionResult EditEpisode(TVSerialEpisode tvepisode)
    {
        if (ModelState.IsValid)
        {
            tvContext.Entry(tvepisode).State = EntityState.Modified;                
            tvContext.SaveChanges();
            return RedirectToAction("ListAllEpisode"});
        }
        return View(tvepisode);
    }

i am not sending Create_Time and Last_Update value from view. And it is working fine with create view. But the problem is that when i am trying to edit view and save it then it also set the default value for Create_Time and Last_Update , but i want only Last_Update should be update, not Create_Time

How to pass variables to custom ActionFilterAttribute

What are my options for passing variables into my MyCustomAttribute class?

Currently the class is defined as:

public class MyCustomAttribute : ActionFilterAttribute
{
    public string MyIDParam { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var myID = filterContext.ActionParameters[MyIDParam] as Int32?;
        ..... logic ....
    }
}

Now in my controller I have this:

[MyCustomAttribute(MyIDParam = "id")]
public ActionResult Report(int id)
{
    Guid userId = GetUserInfo();

    ... logic ...
}

In this case I would like to be able to pass "id" and "userId" to MyCustomAttribute class.

Is this possible? Doesn't the MyCustomAttribute get executed before the contents of the Report method?

How to bind dropdown list from action method in MVC 3 inside create view

I want to populate a dropdownlist on create view with form also. Here is my code

@model CM.Models.TVSerialEpisode

@{
   ViewBag.Title = "AddEpisode";
}
@Html.Action("ListAllSeason","TvSerial") //here i want to call this action method so i could bind all tv serial

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>TVSerialEpisode</legend>



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

         @Html.DropDownList("Serial_ID", new List<SelectListItem>
        {
           new SelectListItem { Text = "Backstrom", Value="16" },
           new SelectListItem{Text="10 Things I hate about You", Value="15"},
           new SelectListItem { Text = "Castle", Value="14" }
      }, "Select Serial")
         @Html.ValidationMessageFor(model => model.Serial_ID)
    </div>

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

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

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

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

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

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

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

here is the model class

namespace CM.Models
{

[Table("tbltvserial")]
public class TVSerial
{
    [Key]
    public Int64 Serial_ID { get; set; }
    public string Serial_Name { get; set; }
    public string Season_Name { get; set; }
    public int Season_No { get; set; }
    public int? Release_Year { get; set; }       
}
public class TVSerial_VM
{       
    public Int64 Serial_ID { get; set; }
    public string Serial_Name { get; set; }       
    public int Season_No { get; set; }            
}


[Table("tblserialepisode")]
public class TVSerialEpisode
{
    [Key]
    public Int64 Video_ID { get; set; }        
    public Int64 Serial_ID { get; set; }
    public int Episode_No { get; set; }
    public string Episode_Name { get; set; }       
    public string File_Url_480p { get; set; }
    public string File_Url_720p { get; set; }
    public string Description { get; set; }
    public bool Is_Active { get; set; }
    public DateTime Uploaded_Time { get; set; }     
}

public class TvSerialContext : DbContext
{
    public DbSet<TVSerialEpisode> TvSerialEpisodes { get; set; }
    public DbSet<TVSerial> TvSerials { get; set; }  
}
}

here are controller class

public class TvSerialController : Controller
{

    public List<TVSerial_VM> ListAllSeason()
    {
        try
        {
            TvSerialContext tvContext = new TvSerialContext();
            List<TVSerial_VM> tv = tvContext.TvSerials
                .Select(t => new TVSerial_VM
                {
                    Serial_Name = t.Serial_Name,
                    Season_No=t.Season_No,
                    Serial_ID=t.Serial_ID
                }).OrderBy(t=> t.Season_Name).
                  ToList();
            return (tv);
        }
        catch (Exception ex)
        {
            return null;
        }

    }
}

public class TvSerialEpisodeController : Controller
{

    TvSerialContext tvContext = new TvSerialContext();
    public ActionResult AddEpisode()
    {
        return View();
    }


    [HttpPost]
    public ActionResult AddEpisode(TVSerialEpisode tvEpisode)
    {
        if (ModelState.IsValid)
        {
            tvContext.TvSerialEpisodes.Add(tvEpisode);
            tvContext.SaveChanges();
            return RedirectToAction("AddEpisode");
        }

        return View(tvEpisode);
    }
}

I don't know how to bind the tvserial list inside above view page. basically i want to choose the serial id from dropdown list, is this posible to call a action method inside the create view.

lundi 16 novembre 2015

OKTA authentication for ASP.NET MVC app

I have to develop an ASP.NET MVC website. For authentication, we have decided to use OKTA as the authentication provider. We do not want to use Okta API, but we would like to use SAML implementation. Are there any articles/guidelines available on this? I also would like to know how can we extend this to a WCF service. All of these will be hosted in Azure.

MVC HttpPostedFileBase always null with ajax options

i've encountered some issue where i cannot get the file from the form with ajaxOptions. Below are the code..

@using (Ajax.BeginForm(null, null, new AjaxOptions { OnBegin = "blockUI", OnSuccess = "handleFormSuccess", OnFailure = "onAjaxFailure" }, new { enctype = "multipart/form-data" }))
{
<div class="col-md-4">
                            <div class="form-group">
                                @Html.LabelFor(model => model.MediaName, new { @class = "control-label" })
                                <span class="text-danger" aria-required="true"> * </span>
                                @Html.TextBoxFor(model => model.MediaName, new { @class = "form-control", @placeholder = LocalizationViewModel.Media.MediaName })
                                <span class="text-danger">@Html.ValidationMessageFor(model => model.MediaName)</span>
                            </div>
                        </div>
<div class="row col-md-12">
                        <div id="imageContent" class="form-group">
                            @Html.Label(@LocalizationViewModel.Media.Image, new { @class = "control-label" })
                            <div class="col-md-12">
                                @Html.TextBoxFor(model => model.MediaFile, new { type = "file" })
                            </div>
                        </div>
                    </div>
    }

if i change to this, it's working file.

@using (Html.BeginForm("CreateMedia", "Media", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
<div class="col-md-4">
                            <div class="form-group">
                                @Html.LabelFor(model => model.MediaName, new { @class = "control-label" })
                                <span class="text-danger" aria-required="true"> * </span>
                                @Html.TextBoxFor(model => model.MediaName, new { @class = "form-control", @placeholder = LocalizationViewModel.Media.MediaName })
                                <span class="text-danger">@Html.ValidationMessageFor(model => model.MediaName)</span>
                            </div>
                        </div>
        <div id="imageContent" class="form-group">
                            @Html.Label(@LocalizationViewModel.Media.Image, new { @class = "control-label" })
                            <div class="col-md-12">
                                @Html.TextBoxFor(model => model.MediaFile, new { type = "file" })
                            </div>
                        </div>
                    </div>
}

below are my controller and view model.

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> CreateMedia(CreateMediaViewModel viewModel)
        { // some code here
}


public class CreateMediaViewModel
    {
[Display(ResourceType = typeof(Media), Name = "MediaName")]
        [Required(ErrorMessageResourceType = typeof(Message), ErrorMessageResourceName = "MessageFieldRequired")]
        public string MediaName { get; set; }

        [Display(ResourceType = typeof(Media), Name = "Image")]
        public HttpPostedFileBase MediaFile { get; set; }
    }

Have anyone have the idea to make it works? :( i been stuck here for some times...thanks..

inserting muliple lines to a database table using LINQ query

I'm try to insert all the ith values to table called AB_Product_vs_Field but its only insert last i values only

this is that LINQ query

            for (int i = 0; i < product.ListProductFields.Count; i++)
            {
                insertproductvalue.Product_ID = product.Product_ID;
                insertproductvalue.Field_ID = product.ListProductFields[i].ProductFieldID;
                insertproductvalue.Field_Value_EN = product.ListProductFields[i].Field_Value_EN;

            };

            db.AB_Product_vs_Field.Add(insertproductvalue);
            db.SaveChanges();

How to insert all of those rows one by one

samedi 14 novembre 2015

how to write value of javascript in text file in mvc5

I need to write a Javascript's value in text file in my mvc5 project. Is it possible to do so?I tried the code below but didn't succeed. its not considering the "OpenTextFile" and ActiveXObject as a function. do i need to add some references for using these?

var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();

jeudi 12 novembre 2015

ASP.NET current Session object - inject log logic

In the app I am working on we are using an InProc ASP.NET SessionState object.

I'd like to find a way to log a message whenever some code reads or writes into the Session object.

I am aware of the Item[] index, and I suppose I should inject the code somehow.. or maybe inherit the HttpSessionState class?

Options, ideas, experience...?

Asp.net MVC Razor errors cause bad characters

i use Asp.net MVC Razor.Page works in local.But at the server page does not work.It show bad characters.What cause that error?What should i do?it works in local.And there is many page.All pages works well at the server.Just that page does not work.I looked razor code every tags is trueenter image description here

change css of div from variable

Is it possible to add style to a div using a JS variable: g_heightOfKildareImage for e.g. in c# would look like:

<div id="ButtonsDiv" class="storyBoardButtons" style="bottom:" + g_heightOfKildareImage + "" />

Perform action when user click in browser's back button

I'm working on a web application (ASP.NET MVC3), and I have this problem: I want to redirect to "Home/Index" when user clicks the browser's back button. Is there any way to perform this (with Javascript or wathever)?

formatting of text in p tag not formatting?

Evening all...User enters data into a record which is stored in the DB. If I copy the text from this record into note pad it is displayed formatted correctly...

    Drive along the coastline and drink in the sights exploring the newly-designated Wild Atlantic Way where secrets lie hidden in remote peninsulas. And on the mountain roads, the sweet aroma of turf smoke will greet you as you make your way around.

The county can justifiably make many claims: the highest sea cliffs and the largest sand dunes in Europe, the biggest waves in Ireland. With no fewer than 13 unspoilt golden strands, it proudly boasts the largest number of Blue Flag beaches of any county in Ireland.

Where, the visitor may ask, is the essence of Donegal? There is not one particular spot since it is to be found everywhere: from the burstingly fresh local seafood, at the summit of Errigal mountain, in the Killybegs fishing boats bringing home the catch, in the ruins of a medieval castle, on a ferry ride to Tory Island, on top of an ancient hillfort, or in the reminiscent <br/> call of the corncrake or shrill whistle of the oystercatcher.

However when displaying on screen in the browser I put the text inside a <p> tag but it displays on screen as...

Drive along the coastline and drink in<br /> the sights exploring the newly-designated Wild Atlantic Way where secrets lie hidden in remote peninsulas. And on the mountain roads, the sweet aroma of turf smoke will greet you as you make your way around. The county can justifiably make many claims: the highest sea cliffs and the largest sand dunes in Europe, the biggest waves in Ireland. With no fewer than 13 unspoilt golden strands, it proudly boasts the largest number of Blue Flag beaches of any county in Ireland.Where, the visitor may ask, is the essence of Donegal? There is not one particular spot since it is to be found everywhere: from the burstingly fresh local seafood, at the summit of Errigal mountain, in the Killybegs fishing boats bringing home the catch, in the ruins of a medieval castle, on a ferry ride to Tory Island, on top of an ancient hillfort, or in the reminiscent <br/> call of the corncrake or shrill whistle of the oystercatcher.

As you can see no formatting, line spaces after paragraphs etc...does anyone know why? thanks

code that renders the html....

//mvc dataTable being displayed
     <p>@row["Description"]</p>

mercredi 11 novembre 2015

How to redirect to specific error page in MVC FileDownloadResult

I enable my users to download files, some times the files are archived or do not exist at the location, I currently display a 404, I created a specific error page for this specific scenario but I am unable to display it because I have to return something in the FileDownload Result and I am unable to do a response redirect. Also I tried to return content with javascript but that is also not compatible with FileDownloadResult type. How do I route the user to the intended error page which I have will render from its own controller/action?

   public DownloadFileResult Download(string file)
        {
            try
            {
                string loadLististFileName = file;

                // get the displayed filename, extract the file name
                string fileNamePath = loadLististFileName;
                string fileName = Path.GetFileName(fileNamePath);
                string dirName = Path.GetDirectoryName(fileNamePath);

                string dirPath = dirName.Replace("\\", ",");

                string[] dir = dirPath.Split(',');
                int dirlength = dir.Length;
                string year = dir[dirlength - 3];
                string month = dir[dirlength - 2];
                string day = dir[dirlength - 1];

                var fileData = IOHelper.GetFileData(fileName, dirName);

                fileName = IOHelper.GetPrimaryFileName(file);

                return new DownloadFileResult(fileName, fileData);
            }
            catch (FileNotFoundException)
            {

                //return Content("<script language='javascript' type='text/javascript'>alert('Image not found!');</script>");            

                Response.Redirect("Exception/FileIndex");
            }

        }

How to call Javascript from Razor View

How can I call a Javascript method from a razor view?

At first I tried

@if (TempData["myMessage"] != null)
{ 
    @:displayMessage();
}

and when the page rendered I literally saw "@:displayMessage(); on my HTML page.

So then I tried.

@if (TempData["myMessage"] != null)
{ 
    <script type="text/javascript">displayMessage();</script>
}

Which works if displayMessage function exists on that html page. However in my case displayMessage exists in a seperate javascript file. (Which gets included on this web page)

ViewModel validation for a List and display the error message

i need to do a validation by ensuring the list must have atleast one item is selected. I populate the checkbox with my list, below is the code

@for (var i = 0; i < Model.ProductList.Count(); i++)
{
    var product = Model.ProductList[i];
    @Html.HiddenFor(model => model.ProductList[i].ProductId)
    @Html.CheckBoxFor(model => model.ProductList[i].Selected)
    @Html.LabelFor(model => model.ProductList[i].ProductName, product.ProductName, new { style="margin-right:10px" })
}
<span class="text-danger">@Html.ValidationMessageFor(model => model.ProductList)</span>

Here is my custom validation rule

public class MustHaveOneProductSelected : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var products = value as List<MediaContentTypeProductItem>;
        int selected_count = products.Where(x => x.Selected).Count();
        if (selected_count <= 0)
            return false;
        else
            return true;
    }
}

Apply validation in a list

[MustHaveOneProductSelected(ErrorMessage = "Please select atleast one product.")]
public List<MediaContentTypeProductItem> ProductList { get; set; }

The MustHaveOneProductSelected is validate correctly by returning true and false. Just it wont display the error message. Am i missed out anything?

MVC 3 Area Registration 302 Error

I have a 2 area which names called with "Admin" and "Services". My project structure as below image 1

I want to redirect all root url to Admin area. I changed my area registration files to resolve this problem as below code block.

//Root 
//Old Value
routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
//New Value
routes.MapRoute(
                "Default", // Route name
                "trash/{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );

Now for redirecting the root url to Admin area I've updated AdminAreaRegistration.cs class as below.

//Admin
//Old Value
context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                 new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

//New Value
context.MapRoute(
                "Admin_default",
                "{controller}/{action}/{id}",
                 new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

After this update when i want to browse my web site it was ok I can see my admin area views. But I have a lot of AJAX call on Admin Area Views and when those ajax calls try to call Services Area controller it could not access to the Services Controller, I've monitored on network plugin to see what is my error I get a HTTP 302 error and then its redirect to 404 Not Found page.

I hope my explanation is understable.

Thank you in advance.

Project Structure

mardi 10 novembre 2015

How to combine a list model to another model in ASP.NET MVC

I have two models:

public class Model1
    {
        public int? Id { get; set; }    
        public string Name{ get; set; }
        private IList<Model2> _model2; 
    } 

  public class Model2
        {
           public string Name2{ get; set; }
        }

JSON data for ajax call:

[
  {
    "Id": 1,
    "Name": "Foo",
    "Name2": "Foo2"
  },
  {
    "Id": 2,
    "Name": "Foo3",
    "Name2": "Foo4"
  }
]

Controller action:

public ActionResult Save(List<Model1> models)
        {
        }

In this way I do not get Name2 in controller action. Are there any way to get Name2 in controller?

I know it can be solved by creating another model. e.g

public class Model3
        {
            public int? Id { get; set; }    
            public string Name{ get; set; }
            private Model2 _model2; 
        } 

But I don't want to create new model class. thanks....

Handling 404 error in MVC5

I am trying to redirect user to an controller action while there is any 404 found. Like missing Controller or missing action or bad URL. I am using below approach :

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />
</httpErrors>

But the issues is my action(pageNotFound) is called every time I request a URL. Even if the URL is valid.This may kill performance during production deployment. Any suggestion or another approach

Saving viewmodel object value

i am creating a date forward/backward funktion in MVC. I am very new at this and i want to ask how do i set a new value to an MVC object.

this is my code: i am sending a link with parameters to define a date and get data

    var getAbsenceList = function (location, userId, absenceDate, modifier) {
    $.get('ActivityWidget/MyActivityAbsenceListData/?location=' + location + '&userId=' + userId + '&modifier=' + modifier + '&absenceDate=' + absenceDate, function (response) {
        $('#absence-data').html(response.UserList);
        $('#absence-date-container').html(response.AbsenceDateData)
    });

my absenceDate is set i a partial view here:

@model MyActivityAbsenceViewModel
@string.Format("{0:dddd}", Model.AbsenceDate).UppercaseFirst() d. @string.Format("{0:d}", Model.AbsenceDate)
@Html.HiddenFor(m => m.AbsenceDate)

And this is my HTML code:

<table class="absence-widget-table">
    <tr>
        <td class="absence-widget-left">
            <i class="fa fa-chevron-left" title="Next" aria-describedby="ui-tooltip-1"></i>
        </td>
        <td class="absence-widget-center" id="absence-date-container">
            @Html.Partial(MVC.ActivityWidget.Views.Partials.MyActivityAbsenceDateChanger, Model)
        </td>
        <td class="absence-widget-right">
            <i class="fa fa-chevron-right" title="Previous"></i>
        </td>
    </tr>
</table>

when i press the next or previous button absenceDate is always todays date. It doesnt change the value when one of the buttons are presssed.

cna anyone help?

thanks.

lundi 9 novembre 2015

'X-Frame-Options' to 'SAMEORIGIN' google maps MVC

I want to display the Google maps with the following code using iframe

<script type="text/javascript" src="http://ift.tt/zEj3Kb">
<noscript>
    <div style="display: inline;">
      <img height="1" width="1" style="border-style: none;" alt="" src="http://ift.tt/1GSMgQC''/?label='';guid=ON&amp;script=0" />
    </div>
</noscript>
    <div class="mapContainer" style="width: 251px; height: 202px;">
       <iframe id="iGmap" width="251" height="202" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="@Html.Raw(Model.CurrentBranch.GoogleMapURLWithZoomSet)">
       </iframe>
    </div>

Where

src='http://ift.tt/1HCuf3L''&amp;ll='',''&amp;spn='',''&amp;output=embed&amp;z=4'

The above code I am using in cshtml page But giving the error like Refused to display 'http://ift.tt/1GSMh6Q…&ll=,&spn=,&output=embed&z=6' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

save image to http server

Get an image from a http server. Resize the image to a thumnail and save back to the same folder as a different name "thumb" + imgName. This all works apart from saving to the server again. I tried saving to local and it works so the server is the problem

    Image fullsizeImage = Image.FromStream(new MemoryStream(new WebClient().DownloadData(ResolveUrl(ConfigurationManager.AppSettings["ImagesFolder"] + exportedFileName))));
    Image thumbImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
 thumbImage.Save(Server.MapPath(ResolveUrl(ConfigurationManager.AppSettings["ImagesFolder"] + "thumb_" + exportedFileName)));

This wont allow me to thumbImage.Save() back to the external server http it flags as 'http:/localhost:61318/Uploads/thumb_6086Jellyfish.jpg' is not a valid virtual path.

So I need to pass it to a memory stream first?? I tried

string destinationFileName = ResolveUrl(ConfigurationManager.AppSettings["ImagesFolder"] + "thumb_" + exportedFileName);
 System.IO.FileStream fs = System.IO.File.Open(destinationFileName, FileMode.Create);
thumbImage.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
 fs.Close();
 //BUT THIS FLAGGED AS - uri formats are not supported

So Do I need to creat the memory first? then save the image to that path...any ideas? thanks

dimanche 8 novembre 2015

xsd substitution or xlt transformation

How Do I Change this XSD using substitution to get the following outcome?


I have a XML that is being returned from my asp.net api from a Saas providor. The service comes from asp.net mvc however, I can only use asp classic, and i'm pretty limited in what i can do. I can send TSQL queries to the sql server 2005... Other than that theres not much that can be done. So my only option for what i need (well my best current option) is this. The data returns from my asp classic page service.asp. service.asp returns the structured xml based off an XSD file that is in the same folder as my script to get the data. I'll show you what it currently returns, what the current xsd is, and what it should return, and the modifications I tried making to the XSD. Hopefully that's the info someone will need to help me as this isn't exactly my strong suite. Thanks!

Current XML Response

Currently the data returns like this:

<xmldata>
    <group>
        <groupid>1</groupid>
        <parentid>2</parentid>
        <item>133</item>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    </group>
    <group>
        <groupid>2</groupid>
        <parentid>2</parentid>
        <item>134</item>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    </group>
    <group>
        <groupid>2</groupid>
        <parentid>2</parentid>
        <item>313</item>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    </group>
    <group>
        <groupid>3</groupid>
        <parentid>2</parentid>
        <item>46</item>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    </group>
</xmldata>

Current XSD File

My current XSD File is structured as follows:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="xmldata" xmlns="" xmlns:xs="http://ift.tt/tphNwY" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
  <xs:element name="xmldata" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="groups">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="groupid" name="groupid" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="ParentID" msprop:SqlDbType="Int" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="groupproductlink">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="groupproductlink" name="ID" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="groupID" msprop:SqlDbType="Int" minOccurs="0" />
              <xs:element name="ProductCode" msprop:SqlDbType="Int" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Products">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="Products" name="AutoDropShip" msprop:maxLength="1" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" msprop:SQLFrom="FROM vm.Products p INNER JOIN vm.Products_Descriptions pd ON p.ProductCode = pd.ProductCode INNER JOIN vm.PE pe ON p.ProductCode = pe.ProductCode INNER JOIN vm.Products_Memos pm ON p.ProductCode = pm.ProductCode" minOccurs="0" />
              <xs:element name="productid" msprop:maxLength="30" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" minOccurs="1" />
              <xs:element name="ProductCode" msprop:SQLTableAlias="p" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="ProductName" msprop:maxLength="255" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>


What the XML Should Be

The XML Needs to be returned in the following way (please note the attribute becoming the element)

<groups>
    **<1> //<---Element=groupID**
        <item>133</item>
        <parentid>2</parentid>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    **</1> //<---Element=groupID
    <2> //<---Element=groupID**
        <item>134</item>
        <parentid>2</parentid>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    **</2> //<---Element=groupID
    <2> //<---Element=groupID**
        <item>313</item>
        <parentid>2</parentid>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>e="1">
    **</2> //<---Element=groupID
    <3> //<---Element=groupID**
        <item>46</item>
        <parentid>2</parentid>
        <ProductCode>blahblah</ProductCode>
        <ProductName>blahblah</ProductName>
    **</3> //<---Element=groupID**
</groups>


The XSD I attempted to use and didn't get any response

I tried transforming the XSD that I listed above to the following:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="groups" xmlns="" xmlns:xs="http://ift.tt/tphNwY" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
  **<xs:element name="groups" *msdata:IsDataSet="true"* msdata:UseCurrentLocale="true">**
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="groupid" *msdata:IsDataSet="true"* msdata:UseCurrentLocale="true" msprop:TableNameXsd="groupid" msprop:SqlDbType="Int" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="groupid" name="groupid" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="ParentID" msprop:SqlDbType="Int" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="groupproductlink">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="groupproductlink" name="ID" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="groupID" msprop:SqlDbType="Int" minOccurs="0" />
              <xs:element name="ProductCode" msprop:SqlDbType="Int" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Products">
          <xs:complexType>
            <xs:sequence>
              <xs:element msprop:TableNameXsd="Products" name="AutoDropShip" msprop:maxLength="1" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" msprop:SQLFrom="FROM vm.Products p INNER JOIN vm.Products_Descriptions pd ON p.ProductCode = pd.ProductCode INNER JOIN vm.PE pe ON p.ProductCode = pe.ProductCode INNER JOIN vm.Products_Memos pm ON p.ProductCode = pm.ProductCode" minOccurs="0" />
              <xs:element name="productid" msprop:maxLength="30" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" minOccurs="1" />
              <xs:element name="ProductCode" msprop:SQLTableAlias="p" msprop:SqlDbType="Int" msprop:IsIdentity="true" minOccurs="0" />
              <xs:element name="ProductName" msprop:maxLength="255" msprop:SQLTableAlias="p" msprop:SqlDbType="VarChar" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>


However, It doesn't work currently. I think maybe I need to use a substitution group, however unfortunately it's been years since I did this and I can't remember what exactly I need to do. I truly hope someone here has some better ideas!

Thanks for your assistance. If you have any questions let me know and I'll do my best to answer them!

samedi 7 novembre 2015

how to add fiddler request body parameters in ajax call

Please check my ajax code and image of fiddler. If I use fiddler , I am getting output.But in ajax call,giving error like bad req.

   $.ajax({
                type: "POST",
                url: "http://localhost:54544/token",
                contentType: "application/form-url-encoded",
                data: JSON.stringify({
                    grant_type: "password",
                    Username: "user",
                    Password: "user"
                }),
                
                success: function (data) {
                    alert("succ");
                    alert(data);
                },
                error: function (xhr, status, p3, p4) {

                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    alert(err);
                }
            });

fiddler req img output in fiddler img

vendredi 6 novembre 2015

Insert & Update in Asp.Net MVC3

I can't create and update the information by this way: Using Initializer, and Combing two models classes to get the Index View,I have two tables EmployeeInformation & DesignationHierarchy as: CREATE TABLE [dbo].[DesignationHierarchy]( [Id] [numeric](18, 0) IDENTITY(1,1) NOT NULL, [EmployeeId] [numeric](18, 0) NULL, [LineManagerId][numeric](18, 0) NULL ) & CREATE TABLE [dbo].[EmployeeInformation]( [Id] [numeric](18, 0) IDENTITY(1,1) NOT NULL, [Name] [nvarchar](255) NULL ) and ModelClasses as: ` public class DesignationHierarchy { public decimal Id { get; set; } public decimal EmployeeId { get; set; } public decimal LineManagerId { get; set; }

}`

`public class EmployeeInformation { public decimal Id { get; set; } public string Name { get; set; }

}`

and public class EmployeeInformationHierarchy { public EmployeeInformation EmployeeInformation { get; set; } public DesignationHierarchy DesignationHierarchy { get; set; } } and the methods to Create: ` public ActionResult Create() {

        ViewBag.EmployeeName = new SelectList(db.EmployeeInformation.ToList(),"Id","Name");

        return View();
    } 
   [HttpPost]
    public ActionResult Create(DesignationHierarchy designationHierarchy)
    {
        if (ModelState.IsValid)
        {
            db.DesignationHierarchy.Add(designationHierarchy);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }
        return View(designationHierarchy);
    }`

and edit: public ActionResult Edit(decimal id) { DesignationHierarchy designationHierarchy = db.DesignationHierarchy.Find(id); ViewBag.EmployeeName = new SelectList(db.EmployeeInformation.ToList(), "Id", "Name",designationHierarchy); return View(designationHierarchy); } [HttpPost] public ActionResult Edit(DesignationHierarchy designationHierarchy) { if (ModelState.IsValid) { db.Entry(designationHierarchy).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(designationHierarchy); } and for index: ` public ViewResult Index() {

        var designationHierarchy = from d in db.EmployeeInformation


                                   join r in db.DesignationHierarchy on d.Id equals r.LineManagerId


                                   select new EmployeeInformationHierarchy { EmployeeInformation = d, DesignationHierarchy = r };

        return View(designationHierarchy);
    }`

and Views: ` @Html.HiddenFor(model => model.Id) @Html.LabelFor(model => model.EmployeeId,"Name") @Html.DropDownListFor(m => m.EmployeeId, (SelectList)ViewBag.EmployeeName, "--Select Name--") @Html.ValidationMessageFor(model => model.EmployeeId)

    <div class="editor-label left_align">
        @Html.LabelFor(model => model.LineManagerId,"Line Manager")
    </div>
    <div class="editor-field left_right_padding">
   @Html.DropDownListFor(m => m.LineManagerId, (SelectList)ViewBag.EmployeeName, "--Select Name--")
        @Html.ValidationMessageFor(model => model.LineManagerId)
    </div>`

and view for index: <td> @Html.DisplayFor(modelItem => item.EmployeeInformation.Name) </td> <td> @Html.DisplayFor(modelItem => item.EmployeeInformation.Name) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.DesignationHierarchy.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.DesignationHierarchy.Id }) </td>

jeudi 5 novembre 2015

Getting issue when implementing angular grid in mvc

I have one MVC project where previously i used kendo controller all the things are fine there.

Now when i added angularjs ui grid in my new and used kendo datepicker so angular js was not working because of i added those angular.js script in _layout.cshtml page just after kendo.all.min.js. but did not find angularjs worked. so i removed the script from there and added those script in newly created view so angular grid is working now but the new issue i got that is Jquery function not defined for kendo datepicker. i know this issue becasue jquery.min.js it is used now in two places first in layout.cshtml and second in new view. if i remove this jquery.min.js script from new view gettting issue like angularjs injecterr. if i am using this view my kendo datepicker is not working.

If anyone who have idea to set all the angularjs script in _layout.cshtml only then it would be good.

Need help.

retrieve table data using reflection

So i have a database in npgsql. And I want to get the data of one tables, for example I have a table named "User" and I want to get all the "Name" and "Age". How do I do that using reflection. I'm new to this reflection thing. Thanks in advance.

CheckboxList MVC EditorFor Template PostBack

I inherited some incomplete code. The developer was using an editorfor template for creating his checkboxlist. The problem is that it does not bind back to the model so that I can get the data back to the server side. Anyone have an example on how to use an editorfortemplate for a checkboxlist and send data back bound to the model? Below is the editortemplate content.

EDITOR TEMPLATE called ServiceTypeViewModel.cshtml

     @model List<ViewModels.ServiceTypeViewModel>
<table>

@{int k = 0; int columns = 2;}

@for (int i = 0; i < (Model.Count / columns + (Model.Count % columns == 0 ? 0 : 1)); i++)
{
    <tr>
    @for(int j = 0; j<columns; j++){
        <td>
            @if (k<Model.Count) { 
                <input name="ProvidedServices[@(k)].Name" id="ProvidedServices__@(k)__Name" type="hidden" value="@Model[k].Name">       
                <input name="ProvidedServices[@(k)].Selected" class="CB" id="ProvidedServices__@(k)__Selected" type="checkbox" value="true">
                <input name="ProvidedServices[@(k)].Selected" type="hidden" value="false">
                <input name="ProvidedServices[@(k)].ServiceTypeClass" id="ProvidedServices__@(k)__ServiceTypeClass" type="hidden" value="@Model[k].ServiceTypeClass">       
                <input name="ProvidedServices[@(k)].ServiceType" id="ProvidedServices__@(k)__ServiceType" type="hidden" value="@Model[k].ServiceType">       
                @Html.DisplayFor(m=>Model[k].Name)
                k++;
            }
        </td>
    }
    </tr>
}
</table>

MODEL BELOW

  public class ServiceTypeViewModel
    {
        public string ServiceTypeClass { get; set; }
        public string ServiceType { get; set; }
        public bool Selected { get; set; }
        public string Name { get { return ServiceTypeClass + " " + ServiceType; } }
    }
}

EditorFor Template Definition in main Model.

[UIHint("ServiceTypeViewModel")]
public List<ServiceTypeViewModel> ProvidedServices { get; set; }

Index.cshtml

    @Html.LabelFor(x => x.ProvidedServices)
    @Html.EditorFor(x => x.ProvidedServices)