mardi 25 avril 2017

Configure structure map to scan for all implementations as opposed to convention?

Currently have my structuremap set-up configured to scan for implementations via convention.

So for any dependency on IMyRepo, MyRepo will be looked for.

But how can I resolve IMyRepo to any implementation that doesn't follow that naming convention?

i.e. TotallyDifferentRepoImp : IMyRepo

Sorry - I should clarify, I want this to be automatically registered - i..e I don't want to have to specify each implementation. I want to configure a convention here.

lundi 24 avril 2017

Understanding Properties

As by definition of properties in C# , these are the extension of fields and can be get set. So can we set the properties of an object of a class as well?

class c1{
     public C2 obj {get;set;}
}

dimanche 23 avril 2017

Creating SMS Gateway using asp.net MVC

I m trying to implement my own SMS gateway using asp.net MVC. Please suggest any solution how to start with it.

Thanks in Advance!!

Post form always returning null

I have an application in asp .net mvc 4 as follows:

1.ProductsController.cs

namespace MvcApplication2.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/

        [HttpGet]
        public ActionResult Products()
        {
            List<Product> prList = new List<Product>();
            Product p1 = new Product();
            p1.ProductName = "J & J";
            p1.Price = 40;
            p1.Ratings = 5;
            prList.Add(p1);
            Product p2 =  new Product();
            p2.ProductName = "Himalaya";
            p2.Price = 20;
            p2.Ratings = 2;
            prList.Add(p2);
            return View(prList);

        }

        [HttpPost]
        public ActionResult Products(FormCollection prList,List<MvcApplication2.Models.Product> fg) 
        {
            return View(prList);
        }

    }
}

2. ProductList.cs

namespace MvcApplication2.Models
{


    public class Product
    {
        public string ProductName { get; set; }
        public int Price { get; set; }
        public int Ratings { get; set; }
    }

}

3. Products.cshtml

@{
    Layout = null;

}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Products</title>
    @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")

    <script src="~/Scripts/jquery-3.2.1.min.js"></script>
</head>
@model IEnumerable<MvcApplication2.Models.Product>
@using (@Html.BeginForm("Products", "Products", FormMethod.Post))
{
<body>
    <div style="width:100%;height:100%;position: relative ">
        <div style="width:100%;top:0px;height:40px;position:relative;background-color:purple">
            <input type="submit" value="Sort price" style="float : right;width:30px;" id="SearchId" />
            @Html.TextBox("Search Box", null, new { @style = "float:right;width:80px "});
            <input type="submit" value="submit" />  
        </div>
        <div id="tableDiv">
            <table id="tableId">
                <tr>
                    <th>Name</th>
                    <th>Price in Rs.</th>
                    <th>Ratings</th>
                </tr>
@foreach (var drawing in Model)
{

                <tr>
                    <td>@drawing.ProductName</td>
                    <td>@drawing.Price</td>
                    <td>@drawing.Ratings</td>
                </tr>

}
            </table>
        </div>
    </div>
</body>
}
</html>

Whenever I navigate to http://localhost:5858/Products/Products and click and on submit , the contol comes to [HttpPost] in Products methods, but the model is always empty .

What is it that I am missing here?I am expecting the same model to be returned when the page was loaded , why is it that the model is becoming empty?

jeudi 20 avril 2017

Why does this one DropDownListFor work, and this other one doesnt?

I am trying to learn mvc, and after much struggle I finally got a DropDownListFor to work as intented. Here is the working Dropdownlistfor.

Working ViewModel

public partial class get_preKschedule_Result
    {
        public string start_time { get; set; }
        public Nullable<short> lunch_minutes { get; set; }
        public string dismiss_time { get; set; }
        public Nullable<short> headct { get; set; }
        public byte format { get; set; }
        public Nullable<byte> days_per_week { get; set; }
        public string description { get; set; }
    }

format is the type of preK program the school is enrolled in. The values are stored 1-10 in the database so the DropDownListFor will need all values and text. Here is the View.

Working View

@model  DirectoryMVC.Models.get_preKschedule_Result

@{
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem { Text = "Head Start", Value = "6" });
    listItems.Add(new SelectListItem { Text = "Four Year Old At Risk", Value = "7" });
    listItems.Add(new SelectListItem { Text = "Integrated Special Ed", Value = "8" });
    listItems.Add(new SelectListItem { Text = "Reverse Mainstream Special Ed", Value = "9" });
    listItems.Add(new SelectListItem { Text = "All Other District Special Ed", Value = "10" });

}
<div class="col-md-2">
    @Html.DropDownListFor(m => m.format, new SelectList(listItems, "Value", "Text", listItems.Where(x => x.Value == Model.format.ToString())))
    @*listItems*@
</div>

I don't know if there is an easier way, but this is the way I finally got it to work. So when I do this exact same process for this next ViewModel it didn't work! Edit The administrator dropdown for title is not selecting any value, or setting any text. I will also list everything I tried. I am 100 percent sure that the data returned is correct I have verified in the watch that the models property title evaluates to true when I compare it to SelectListItems value.

Non-Working ViewModel

public partial class get_administrators_Result
{
    public int admin_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string title { get; set; }
    public string email { get; set; }
}

Non-Working View

@model  DirectoryMVC.Models.get_administrators_Result

@{ 
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem { Text = "Mr.", Value = "Mr." });
    listItems.Add(new SelectListItem { Text = "Ms.", Value = "Ms." });
    listItems.Add(new SelectListItem { Text = "Dr.", Value = "Dr." });
    listItems.Add(new SelectListItem { Text = "Miss", Value = "Miss" });
    listItems.Add(new SelectListItem { Text = "Mrs.", Value = "Mrs." });
    listItems.Add(new SelectListItem { Text = "Rev.", Value = "Rev." });
}

<div class="col-md-1"> @Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", listItems.Where(x=>x.Value == Model.title)))
</div>

I have even tried

@Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", Model.title))
@Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", (object)Model.title))

and every other combination I can think of with the lambda (m=> m, ...

mardi 18 avril 2017

how to pass model to partialview in umbraco?

I want to pass a object as model to a partial view in umbraco. there is two function @Html.Partial() and @Html.Partial() which have 4 override method listed below :

@Html.Partial(string partialName)
@Html.Partial(string partialName, Object object)
@Html.Partial(string partialName, Object object, ViewDataDictionary dic)
@Html.Partial(string partialName, ViewDataDictionary dic)

and :

@Html.RenderPartial(string partialName)
@Html.RenderPartial(string partialName, Object object)
@Html.RenderPartial(string partialName, Object object, ViewDataDictionary dic)
@Html.RenderPartial(string partialName, ViewDataDictionary dic)

I try to use @Html.RenderPartial(string partialName, Object object) and @Html.Partial(string partialName, Object object) but i an getting this Exception:

Cannot bind source type <>f__AnonymousType0`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to model type Umbraco.Web.Models.RenderModel.

I search a lot in google to an example of using these methods but i cannot find any thing. so there are two question:

  1. What is different between Partial and RenderPartial method?
  2. How can I pass data to partialview from page razor?

How to remove the "" part from mvc

An mvc application I'm supposed to maintain doesn't work on FF.I have a site, which shows a pdf inside an <iframe>. When I try run it on FF, it shows me the Corrupted Content Error inside the iframe. The page you are trying to view cannot be shown because an error in the data transmission was detected . After googling a bit it seems it is due to having to many headers inside, so I checked in IE (it works properly on IE), and yeah, this was the frame content:

<object width="100%" height="100%" classid="clsid:......">
    <PARAM NAME="ExtentX" VALUE="25135">
    .... many other PARAM NAMEs>
</object>
<html style="display: none;">
  <head></head>
  <body></body>
</html>

So it appears to solve my problem I have to delete the <head> elements inside the fame. According to my googling it seems the problem is somewhere with the Response.appendHeader functions, but everything seems okay to me. My controller code:

Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "#toolbar=1&amp;view=FitV");
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.

Someone suggested adding those lines before those lines, but it didn't help:

Response.ClearHeaders();
Response.ClearContent();
Response.Clear();

lundi 17 avril 2017

The name 'Url' does not exist in the current context in Areas Folder

I've WebAPI project. I've created Areas for admin panel. I've attached screenshot below for project structure.
enter image description here

In web.config of Areas->Views folder, I've mentioned:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization" />
        <add namespace="CallApp" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

In Web.Config of root folder, I've mentioned:

<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

But I am getting The name 'Url' does not exist in the current context error in _Layout.cshtml page of Areas Admin.
enter image description here

jeudi 13 avril 2017

Custom Remote Valdaition Without MVC Reference In DataModel class

[CustomRemote("Error Message", Action = "ActionName", Controller = "User", AdditionalFields = ".UserId,.RoleId")] public string UserName { get; set; }

mercredi 12 avril 2017

Regex Visual Studio One Specific Character

I am trying to validate a text box in Visual Studio to be either the character M or F. I have a few other validations with regex set in a similar fashion which are all working correctly. However, with this one, it still allows me to use ANY letter in the text box. What is wrong with this code?

public static bool IsGender(string gender)
{
    bool validGender = true;
    string _genderRegEx = @"^\:|m|M|f|F|$";
    if ((!Regex.Match(gender, _genderRegEx).Success))
    {
        MessageBox.Show("Gender must be either M or F.");
        validGender = false;
    }
    return validGender;
}

How to mask Password in MVC ViewRazor

I need to mask Password in View in MVC Project, where i have list of users.

I have this code in View, where i see the password at the moment.

 @Html.DisplayFor(modelItem => item.Password)

How to Mask password in View?

mvc images in_Layout.cshtml missing in some of my views

In my _Layout.cshtml, I have the main section for the views as shown below:

@RenderBody()

It properly set background image for create views.For Example CADCreate.cshtml But misses the backrground image for edit and delete views. For example CADEdit.cshtml and CADDelete.cshtml.

Note :

  • All views mentioned above, except Layout.cshtml, are in the same folder.

  • The images folder is under my project folder.

Thanks in advance

MVC Routing with Period in parameter name

I am trying to implement a remote validation using entity framework in an MVC application. I need help trying to define the action signature and the appropriate route config. I have the following class in my model:

 public class FiscalReports
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long id { get; set; }
    public Int64 Counter { get; set; }
    public short FiscalYear { get; set; }
   [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM dd, yyyy}")]
   [DisplayFormat(DataFormatString = "${0:N0}")]
    [Remote("ValidateSalary", "FiscalReports", AdditionalFields ="Counter, FiscalYear")]
    public int? Salaries { get; set; }

}

I have a viewmodel which is used for a view that contains several of the above objects.

 public class FiscalReportVM
{
    public FiscalReports CurrentFR { get; set; }
    public FiscalReports ReportedToDate { get; set; }
    public FiscalReports BudgetToDate { get; set; }
}

The Validation action is in the FiscalReports controller is as follows:

  public JsonResult ValidateSalary(int Salaries, short FiscalYear, int Counter)
    {
        return ValidateFiscalField(Salaries, FiscalYear, Counter, "Salaries");
    }

In the view I am using the HTML helper

@Html.EditorFor(model=>model.CurrentFR.Salaries)

This generates the field and validation correctly. Generated HTML is below

input data-val="true" data-val-number="The field Salaries must be a number." data-val-remote="'Salaries'; is invalid." data-val-remote-additionalfields="*.Salaries,*.Counter,*.FiscalYear" data-val-remote-url="/FiscalReports/ValidateSalary" name="CurrentFR.Salaries" type="number" value="" />

The validation request is firing properly and in fiddler I see the following request:

http://localhost:50409/FiscalReports/ValidateSalary?CurrentFR.Salaries=27000&CurrentFR.Counter=4773&CurrentFR.FiscalYear=2

My problem is that I have trouble defining a route and action with the variables in dotted notation. The action definition does not accept dotted parameters (Can't do ValidateSalary(int CurrentFR.Salaries,....). I need help trying to define the action signature and the appropriate route config.

mardi 11 avril 2017

Store current date and time in database using MVC

I have a requirement where I need to store the current system time in the database. here I need to provide 2 logins for User and Admin. Here User will login into the application and will click the In button. Then button action will trigger and will load the current system date and time and it will be saved in the database as well. same like Out button too. Below are the code works which I did,

This is my Model,
public class Employee
    {
        public DateTime In { get { return DateTime.Now; } }
        public DateTime Out { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

This is My controller,
public ActionResult Login(Employee ED)
        {
            if (ModelState.IsValid)
            {
                var Admin = DE.tblEmployees.Where(m => m.Email.Equals(ED.Email) && m.Password.Equals(ED.Password)).Select(a => new { a.Role, a.Name, a.Email }).ToList();
                if (Admin != null)
                {
                    var role = Admin[0].Role;
                    ViewBag.Email = Admin[0].Email;

                    if (role == "Admin")
                        return RedirectToAction("AdminView", "Home");
                    else
                        return RedirectToAction("UserView", "Home");
                }
            }
            return View();
        }

This is My View,
        <button type="button">In</button>
        <button type="button">Out</button>

when you click In button then automatically current system date and time will save automatically.
How to achieve that functionality, how to write the code for this..
Any help would be grateful.

Failed to load pdf document in Mvc Using ITextSharp

Hi this is my Controller code for generate PDf

using System.Web;
using System.Web.Mvc;
using B2B.Common.Models;
using B2B.Common;
using System.Web.Security;
using B2B.BAL;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Text;

namespace B2B.UI.Areas.Agency.Controllers
{
    [Authorize(Roles = RolesType.Agent)]
    public class MyBookingController : Controller
    {

        #region Hotels Booking
        public ActionResult HotelsBooking()
        {


            StringBuilder pdfBody = new StringBuilder();
            pdfBody.Append("<div class='col-sm-10 dashboard_right_cont pt-2 pb-2' style='margin-bottom:-60px;'>");
            pdfBody.Append("<div id='bookingDetails'  class='registration_cont'>                               ");
            pdfBody.Append("<h4 class='text_blue'><strong>Booking Details</strong> </h4>                       ");
            pdfBody.Append("<hr class='hr_blue'>                                                               ");
            pdfBody.Append("<div class='row'>                                                                  ");
            pdfBody.Append("<div class='col-sm-3'>                                                             ");
            pdfBody.Append("<div class='alert alert-success'>                                                  ");
            pdfBody.Append("<p class='mb-1'>Booking reference number:</p>                                      ");
            pdfBody.Append("<h5><strong>@Html.DisplayFor(model => model.BookingRefNo)</strong></h5>            ");
            pdfBody.Append("<hr class='mt-1 mb-1'>                                                             ");
            pdfBody.Append(" <p class='mb-1'>Booking status:</p>                                               ");
            pdfBody.Append(" <h5><strong>@Html.DisplayFor(model => model.Status)</strong></h5>                 ");
            pdfBody.Append("</div>                                                                             ");
            pdfBody.Append("<div class='alert alert-info'>                                                     ");
            pdfBody.Append("<h6><strong><i class='fa fa-user'></i> Leading Passenger</strong></h6>             ");
            pdfBody.Append("<p class='mb-1'>Passenger name:</p>                                                ");
            pdfBody.Append("<h6><strong>@Html.DisplayFor(model => model.LeadingPassengerName)</strong></h6>    ");
            pdfBody.Append(" <hr class='mt-1 mb-1'>                                                            ");
            pdfBody.Append(" <p class='mb-1'>Nationality:</p>                                                  ");
            pdfBody.Append(" <h6><strong>India</strong></h6>                                                   ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                           ");
            pdfBody.Append("  <p class='mb-1'>Country of residence:</p>                                        ");
            pdfBody.Append("  <h6><strong>India</strong></h6>                                                  ");
            pdfBody.Append("</div>                                                                             ");
            pdfBody.Append("<hr>                                                                               ");
            pdfBody.Append("</div>");



            pdfBody.Append(" </div>                                                                                                                                                                                  ");
            pdfBody.Append(" </div>                                                                                                                                                                                  ");
            pdfBody.Append(" <div class='col-sm-12'>                                                                                                                                                                 ");
            pdfBody.Append(" <div class='hotel_search_details_cont bg_white'>                                                                                                                                        ");
            pdfBody.Append("  <p class='mb-1'>Check-in:</p>                                                                                                                                                          ");
            pdfBody.Append("  <h6><strong>11 Apr 2017 10:30:00</strong></h6>                                                                                                                    ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Check-out:</p>                                                                                                                                                         ");
            pdfBody.Append("  <h6><strong>11 Apr 2017 10:30:00</strong></h6>                                                                                                                      ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Room type:</p>                                                                                                                                                         ");
            pdfBody.Append("  <h6><strong>Sperior</strong></h6>                                                                                                                ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Room occupancy:</p>                                                                                                                                                    ");
            pdfBody.Append("  <h6><strong>2 Adults</strong></h6>                                                                                                                                                     ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Bedding preference:</p>                                                                                                                                                ");
            pdfBody.Append("  <h6><strong>No preference</strong></h6>                                                                                                                                                ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                               ");
            pdfBody.Append("  <p class='mb-1'>Rate basis:</p>                                                                                                                                                        ");
            pdfBody.Append("  <h6><strong>Breakfast</strong></h6>                                                                                                                                                    ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("                                                                                                                                                                                         ");
            pdfBody.Append("  <p class='mb-1'>Additional requests:</p>                                                                                                                                               ");
            pdfBody.Append("  <h6><ol><strong><li>Request for an early check in</li> <li>Request for an late check out</li> <li>Please note that guest is a VIP</li></strong></ol></h6>                              ");

            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append("</div>    ");
            pdfBody.Append("</div>    ");
            pdfBody.Append("</div>    ");
            string pdfContent = Convert.ToString(pdfBody);


            Document document = new Document();         
            document.Open();
            StyleSheet styles = new StyleSheet();
            HTMLWorker hw = new HTMLWorker(document);
            hw.Parse(new StringReader(pdfContent));
            document.Close();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=PrintVoucher.pdf");
            Response.Flush();
            Response.Clear();




            return View();
        }


    Pdf is downloaded but it shows failed to load pdf document.

I didn't find where I mistake in code.

Please give me correct code Pdf is downloaded but it shows failed to load pdf document.

I didn't find where I mistake in code.

Please give me correct code

Thanks.

lundi 10 avril 2017

Setting data filters in partial views

I need a little help. So I'm trying to call a lot of partial views from the same list model, each using a different filter. Is there anyway for me to pass the Datafilter value from the views into the model?

vendredi 7 avril 2017

how to get access to some files for some users in mvc asp application?

i'm trying code a website which is like youtube.com but some videos are premium and users must pay to get access to those videos , my problem is => my videos are available for all users and if someone would have the address of that video can download that without logging to my website . i want to let some parts of users to download that . I've tried changing video names after a short while but it has it's own problems :'( is there any way that i give some sessions access permission for downloading a file ? <3 thanks for your help

mercredi 5 avril 2017

StackOverflow exception at the end of a webservice (No recursion / infinite loop) [ASP.NET App]

First of all, I would like to apologize if my language is not the best, I'm acutally not english.

To begin with, I work in a company and I'm maintaining an ASP.NET MVC 3.0 application. Recently the client which I'm working for, submitted a report telling that when he validate a certain page (I will describe how it works later), the app was saving the values but returned an error page.

After a few research, I found out that the application was getting a StackOverflow Exception at the end of the webservice's call. This exception is occuring in mscorlib.dll.

The problem doesn't happen everytime, it only happens when there is a lot of products related to the one validated in the page.

I tried to use WinDbg to get more information about the StackOverflow Exception but it didn't really helped me... The first warning I caught was this picture.

If you have any questions or informations, feel free to tell me.

site developed using orchard cms shows blank pages frequently in live enviroment

i have developed the site in orchard cms by using asp .net mvc.It works fine for some time and then starts giving blank page.when i recycle the application pool then again site starts working fine and then after some time it shows blank page.this happens every day many times. can any body tell me the proper solution for this.

mardi 4 avril 2017

Display Values based on dropdown selection MVC

I have a requirement which I need to display details based on drop down selection. These details coming from database. when I click one user all then all the details belong to that user has to be displayed. This is my Model, public class TaskDetails { public string ProjectID { get; set; } public string ProjectName { get; set; } public DateTime StartDate { get; set; } public DateTime EstimatedDate { get; set; } public string TaskDescription { get; set; } }

This is My Controller,
            List<SelectListItem> query = DE.tblEmployees.Select(c => new SelectListItem { Text = c.Name, Value = c.Name }).ToList();
            ViewBag.Categories = query;
            return View();

This is My View,
<div class="dropdown">
        @Html.DropDownList("CategoryID", (List<SelectListItem>)ViewBag.Categories, "--User Name--")
    </div>

In the View I am loading all the user values inside the drop down. But when admin selects any of the user then all the details of user has to be displayed under a table. Upto here I am perfect but from here got strucked. How to move forward how to show the details of the user based on dropdown selection.

How to create an AngularCli application that contains another AngularCli inside?

I have an application in development that is in Angular2 using AngularCli, and I want to use it as a "Layout" (like a MasterPage) to another project. Like a big "SPA System".

For example, in the menu we will have the following:

  • Framework
    • Page A
  • Xpto
    • Page B

The Framework is running in http://localhost:90 and XPTO is running in http://localhost:91. Both of them is running on AngularCli.

I want to create a structure that when I click on Page A or Page B, the browser doesn't reload and it will give an "app" style to the user, loading the page as a SPA ACROSS the sites.

The main reason is to reuse the Javascripts, CSS and many other files from de "Framework" project to other 20 projects. I don't want to replicate all the components, files and etc across those projects.

Today we use MVC3 and the RazorGenerator to create .cshtml as a DLL to reuse the .cshtml from Framework to other modules.

But we want go AngularCli. Is there any way to do that ? If it isn't, is there some way to create a template in AngularCli that can be reused the components and the other files ?

Thank you !

How to refresh layout alone in MVC?

I want to refresh layout alone in MVC. I am binding layout menus from session. Whenever session is updated, I want to just refresh the layout for menu update.

Can't POST an array of string to ASP.NET MVC3

I have an MVC3 controller action:

public ActionResult DoStuff(DoStuffModel model)

The DoStuffModel looks like this:

public class DoStuffModel
{
    public long SomeId { get; set; }
    public List<string> Codes { get; set; }
}

In my jQuery I do this:

 var postData = {
     SomeId: 1,
     Codes: ["code1", "code2", "code3"]
 };

$.post(url, postData, function (data) {});

The URL is correct. The postData looks like this when I log it:

enter image description here

The SomeId gets bound correctly, but Codes remains null. What is going on?

How to display details from database to the single user in mvc

I am trying to get the details from database to display in the View. Here I need to display the records for particular user who logged currently. But unfortunately all the data which ever in DB table coming into the view. But I dont want to display all the data.

In DB I have two tables for tblEmployee and TaskDetails This is My Model, public class TaskDetails { public string ProjectID { get; set; } public string ProjectName { get; set; } public DateTime StartDate { get; set; } public DateTime EstimatedDate { get; set; } public string TaskDescription { get; set; } }

    This is My controller,
To fetch the data here I am using ADO.Net,
            public ActionResult TaskDetails(string td)
            {           
                string connectionstring = "data source = NLTI37; initial catalog = Data; integrated security = True; MultipleActiveResultSets = True; App = EntityFramework";
                string sql = "select * from TaskDetail";
                SqlConnection conn = new SqlConnection(connectionstring);
                SqlCommand cmd = new SqlCommand(sql, conn);
                var Details = new List<TaskDetails>();
                { 
                    conn.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        var ProjectDetail = new TaskDetails();
                        ProjectDetail.ProjectID = rdr["ProjectID"].ToString();
                        ProjectDetail.ProjectName = rdr["ProjectName"].ToString();
                        ProjectDetail.StartDate = DateTime.Parse(rdr["StartDate"].ToString());
                        ProjectDetail.EstimatedDate = DateTime.Parse(rdr["EstimatedDate"].ToString());
                        ProjectDetail.TaskDescription = rdr["TaskDescription"].ToString();
                        Details.Add(ProjectDetail);
                    }
              }
                return View(Details);
            }
    Here I am using ADO.Net to fetching the details. And these details I need to display on the View for user who currently logged in.

    This is my View,
    <tbody>
                    @foreach (var ProjectDetail in Model)
                {   
                        <tr>
                            <td>@ProjectDetail.ProjectID</td>
                            <td>@ProjectDetail.ProjectName</td>
                            <td>@ProjectDetail.StartDate</td>
                            <td>@ProjectDetail.EstimatedDate</td>
                            <td>@ProjectDetail.TaskDescription</td>
                        </tr>
                    }
                </tbody>

Here I need to display the records of the user who loggedin currently. But unfortunately all the user details I am getting here. As per my understanding SQL statement is wrong. Correct Me if wrong. How to get the details for that particular user details.  Can any one help on this.

Bind values from database to dropdown in MVC with Entity frame work

I am trying to bind a value from database to the dropdown in View.

I have a requirement that I need to display database values in dropdown list in a view. I am trying to bind the Email id to the dropdown from the database table.

Here I need to add the Email ID to the dropdown. This is my Model,

public class UserDetails
{
      public List<SelectListItem> Userdetails { get; set; }
      public string Email { get; set; }
}

This is My Controller,

public ActionResult Admin()
{
            var db = new DataEntities1();
            var query = db.tblEmployees.Select(c => new { c.Email });
            ViewBag.Categories = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName");
            return View();
}

This is my View,

   @model List<MVC_Sample.Models.UserDetails>

             <div class="dropdown">
               @Html.DropDownList("CategoryID", (SelectList)ViewBag.Categories, "--Select One--")

                </div>

View will be loaded with dropdown and the values from database. But unfortunately, I am not able to add the values to drop down. I dono where I did the wrong here. Can anyone help me on this..

lundi 3 avril 2017

Get database Value in textboxFor in bootstrap modal popup in MVC

I place a text box in the bootstrap modal popup and also I have a kink in the table data in the table come from database so I want when I click pop-up show database cell value in the textbox that exists in the modal-popup. Below is my code

Thats my action method that gets data and data is passing to the ViewBag.Type

public JsonResult LinkButton(int RoelID)
{
    Role model = new Role();
    Session["State"] = RoelID;
    int id = RoelID;
    RoleServices ser = new RoleServices();
    var data = ser.Get(id);          
    bool result=false;
    if(Session["State"]!=null)
    {
        ViewBag.Type = data.RoleType;
        result=true;
    }
    return Json(result, JsonRequestBehavior.AllowGet); 
}

Here is a code of JQuery and Ajax acall the action method on link click

<a href="#"  onclick="UpdateID(@item.RoelID)">Select</a>

<script>
    var UpdateID = function (RoelID) {
        $("#hiddenID").val(RoelID);
        var roleID=$("#hiddenID").val();
        $.ajax({
            type: "post",
            url: '@Url.Action("LinkButton", "Account")',
            data: { RoelID: roleID },
            success:function()
            {
                $("moReg").modal('hide');
            }
        })
        $("#moReg").modal('show');
    } 
</script>

Here is textBox in the Modal PopUp

@Html.TextBoxFor(model => model.RoleType, new { @value=ViewBag.Type })

vendredi 31 mars 2017

Check if another action filter attribute is being used in action in MVC 5

I have few custom action filters like

public class CustomFilter:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}


public class CustomFilterNew:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}


In my action method

[CustomFilter]
[CustomFilterNew]
public ActionResult Index()
{
   return View();
}

Lets say CustomFilterNew exactly does opposite of CustomFilter.

In such case how to prevent one filter action from executing another filter action lets say CustomFilterNew should prohibit executing CustomFilter

jeudi 30 mars 2017

Fetching Data from Database and display in View by using MVC entity frame work

I am creating one application by using MVC entity framework. In my application user will login with email ID and will enter the task details and later user can able to view the data which saved. Unfortunately not able to display the data for particular user as all the users data coming into the view. Below is the code for the Controller

   public ActionResult TaskDetails(string td)
        {
            using (Data DE = new Data())
            {
                var email = Session["Email"].ToString();
                var displaydata = DE.TaskDetails.Where(u => u.ProjectID.ToString() == email).ToList();
                ViewBag.details = displaydata;

                return View();
            }
        }

Here email id is from one table and projectID from one table and by using primary key I am trying to get the data. But unfortunately all the users data is coming. This is code for my View @model MVC_Sample.Models.TaskDetail @{ Layout = null; }

@using (Html.BeginForm("TaskDetails", "Home", FormMethod.Post))
{
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>TaskDetails</title>
</head>
<body>
    <div> 
        @foreach (var item in ViewBag.details)

        {
            <table id="t01">
                <tr>
                    <td>@item.ProjectID</td>
                    <td>@item.ProjectName</td>
                    <td>@item.StartDate</td>
                    <td>@item.EstimatedDate</td>
                    <td>@item.TaskDescription</td>
                </tr>

            </table>
        }
    </div>
</body>
</html>

Can any one help me to find where I did mistake.

mercredi 29 mars 2017

images not showing because relative path is not being converted to physical ASP MVC

I am storing image's relative path in my db and then when retrieved I passes it to my view via Model Binding method. When I am setting img's path to the path coming from db that relative path shows as it is in the html page instead of being converted into physical path. How can I force it to be converted to physical?

I tried Server.MapPath() in view but that doesn't help.

I wrote:

<img src=@Model.imgPath>

which is rendered as:

<img src="~/images/img.png">

in my browser.

Google Universal Analytics - Track download details

I am using the new Google Universal Analytics code and it tracks my page-views perfectly.

In addition to that I would like to track downloaded document details such as document name, UserID, etc.

When I googled, the suggestion was to include tracking code in OnClick method. But in my MVC application I am using ajax call and I am not using OnClick.

Is there any other option to track the same. Please let me know if there is a solution.

mardi 28 mars 2017

White space at top of page after converting .net project to use layouts

I recently changed my .net project to use master pages / layout pages. Now when my index page is rendered there is some space at the top of the page right before navbar.

I inspected that page in chrome, there is some empty quotes at the top of body, Removing those in the inspector solves the issue. but I am unable to understand where does that comes from? Here is my index.cshtml file.

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
  ViewBag.Title = "my title";
}
<!--HERO IMAGE-->
<div>
    //code
</div>

@section additionalStyles{
   //adding external stylesheets
}

I am using render section in my index page to load some style sheets not useful in the rest of the pages. These are loaded up just before the ending tag of layout page like this:

@RenderSection("additionalStyles", required: false);

What possibly be causing that quotes?

Passing data from one form to another in asp.net mvc

I want to pass data from one form to another. I have a form of products and after submitting this form i want to add buttom to add posts to for this product, so i want to pass the Product ID to the other form.

this is my product.cs:

public partial class Produits
{

    public Produits()
    {
        this.Postes = new HashSet<Postes>();
    }

    public int idProduit { get; set; }
    public int idPole { get; set; }
    public Nullable<int> Reference { get; set; }
    public string DesignationProduit { get; set; }

    public virtual Pole Pole { get; set; }

    public virtual ICollection<Postes> Postes { get; set; }
}

This is my Post.cs:

public partial class Postes
{
    public int idPoste { get; set; }
    public Nullable<int> Numero { get; set; }
    public int idProduit { get; set; }
    public int idAtelier { get; set; }
    public string DesignationPoste { get; set; }

    public virtual Atelier Atelier { get; set; }
    public virtual Produits Produits { get; set; }
}

this is my Create.cshtml for the product:

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

<div class="form-horizontal">
    <h4>Produits</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })


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

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

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

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

and this my Create.cshtml for the Post:

<form asp-controller="Postes" asp-action="Create" method="post" id="FormPs" role="form">
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Postes</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

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

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

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

My Product controller:

 public ActionResult Create([Bind(Include = "idProduit,idPole,Reference,DesignationProduit")] Produits produits)
    {
        if (ModelState.IsValid)
        {
            db.Produits.Add(produits);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.idPole = new SelectList(db.Pole, "id", "designation", produits.idPole);
        return View(produits);
    }

My Post Controller:

 public ActionResult Create(Postes postes)
    {
        if (ModelState.IsValid)
        {
            db.Postes.Add(postes);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.idAtelier = new SelectList(db.Atelier, "id", "DesignationAtelier", postes.idAtelier);
        ViewBag.idProduit = new SelectList(db.Produits, "idProduit", "DesignationProduit", postes.idProduit);
        return View();
    }

I want to pass idProduit to the other form, Idproduit is an not manually added.

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Survey_D8

I have an error. It is

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Survey_D8226C5F5E348399740EDE08FDF0A956BDAD893915272C075AF983B0C50DA25E', but this dictionary requires a model item of type 'SurveySpaceProject.Models.User'.

I am taking a Survey from database but it need User. I tried some solutions from Stackoverflow but there is no way. Can you help me please? It is not a homework. It is my project and I am started asp.net 1 week ago.

My View

       public ActionResult FillSurvey(int id)
        {
            var s = SSPEntity.getDB().Surveys.FirstOrDefault(x => x.ID == id);
            return View(s);
        }

My FillSurvey Page :

       @model SurveySpaceProject.Models.Survey

     @{
    ViewBag.Title = "FillSurvey";
    }

    <h2>FillSurvey</h2>

    <div>
    <h4>Survey</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.User.UserName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.User.UserName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Title)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Title)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CreatedDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CreatedDate)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.IsDeleted)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.IsDeleted)
        </dd>

       </dl>
      </div>
       <p>
        @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
        @Html.ActionLink("Back to List", "Index")
      </p>

And My Survey Model

            namespace SurveySpaceProject.Models
         {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Survey
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Survey()
        {
            SurveyAnswers = new HashSet<SurveyAnswer>();
            SurveyQuestions = new HashSet<SurveyQuestion>();
            //SurveyUsers = new HashSet<SurveyUser>();
        }

        public int ID { get; set; }

        public int UserID { get; set; }

        [Required]
        [StringLength(150)]
        public string Title { get; set; }

        [Column(TypeName = "date")]
        public DateTime? CreatedDate { get; set; }

        public bool IsDeleted { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyAnswer> SurveyAnswers { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyQuestion> SurveyQuestions { get; set; }

        public virtual User User { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyUser> SurveyUsers { get; set; }
    }
}

Resource not found error in MVC when posting using beginform

The below code is not working properly as expected.

The controller have an action method

[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];             
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }

and in view i have a form

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {  
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

and im submitting this using a function

<script>       
    $(function () {
        $('#ajax_method').click(function (e) {
            e.preventDefault();    
            $.ajax({
                type: "POST",
                url: "Dashboard/LoginResult",                             //Your Action name in the DropDownListConstroller.cs
                data: "{'AJAXParameter1':'" + $('#username').val() + "'}",  //Parameter in this function, Is case sensitive and also type must be string
                contentType: "application/json; charset=utf-8",
                dataType: "json"

            }).done(function (data) {
                //Successfully pass to server and get response
                if (data.result = "OK") {
                    alert("submit successfully.");
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(response.status + " " + response.statusText);
                }
            });
        });

    });
</script>

but im getting 404 error while clicking the button.

Even I tried adding that routerspecifications in route config.

   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );

and modified the cshtml again. But this is also not working.

 @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {  
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

samedi 25 mars 2017

WebGrid Search Exception - Error executing child request for handler

I want to make Search in WebGrid but it doesn't work.

I have 2 methods in Controller

 [HttpGet]
    public async Task<ActionResult> ICare()
    {.... return View(tuple);}
[HttpPost]
    public async Task<ActionResult> ICare(string Search)
    {.... return View(tuple);}

And in View I have

using (Html.BeginForm("ICare", "Communities"))
    {
        <div class="row">
            <div class="patientsearch">
                <div class="col-xs-6 col-md-3">
                    <div class="form-group">
                        <div class="input-group">
                            @Html.TextBox("Search", "", new {placeholder = "Search My Patients", @class = "form-control"})
                            <span class="input-group-btn">
                                <button type="submit" class="btn btn_green">Search</button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        var grid = new WebGrid(Model.Item1, canSort: false, canPage: true, rowsPerPage: 10);
        <div class="table-responsive">
            @grid.GetHtml(
                mode: WebGridPagerModes.All,
                tableStyle: "table table-hover table-condensed",
                rowStyle: "table-row-clickable",
                headerStyle: "webgrid-header",
                footerStyle: "table-pager",
                columns:
                    grid.Columns(....

But it always throw an exception in Layout in this

 @{
                          Html.RenderAction("GetUserInfoForMenu", "Menu", new { Area = ""});
                        }

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper

vendredi 24 mars 2017

primary of one table set as foreign key in other table. how to retrieve value?

I have a table containing a primary key and that same primary key is used as a foreign key. How do I retrieve the value from the second table where there are multiple foreign keys with the same primary key in first table?

jeudi 23 mars 2017

MVC Model Validation Mechanism

When we create a model (for example using EF Code First) using Data Annotations we can use Required, 'Range', ...:

public class Employee
{
   public int EmpId { get; set; }

   [DisplayName("Employee Name")]
   [Required(ErrorMessage = "Employee Name is required")]
   [StringLength(100,MinimumLength=3)]
   public String EmpName { get; set; } 

   [Required(ErrorMessage = "Employee Address is required")] 
   [StringLength(300)]
   public string Address { get; set; } 

   [Required(ErrorMessage = "Salary is required")] 
   [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
   public int Salary{ get; set; } 
}

and when using Html.ValidationSummary and Html.ValidationMessage we can show error messages.

My question is when a View would load, in specific page load state those validations will get and convert to JavaScript codes and inject to page. I want to know this mechanism and convert those Data Annotations to JavaScript. I want to create custom validations for models and I want to simulate that behavior.

Thanks

Google Timeline chart, haxis position and start/end times for bars

I have created google timeline chart and would like to add the start and end time's to the bars and change the bottom xaxis to the top of the chart. But cant find anything for this from the timeline options. Is this possible somehow??

function ChartView(chartWidth, chartHeight, renderedTo, dataset, minTime, maxTime) {
var colors = [];
for (var i = 0; i < dataset.getNumberOfRows(); i++) {
    if (dataset.getValue(i, 0) == 'DataNotFound') {
        colors.push("#ffffdd");
    }
    else {
        colors.push(colorArray[dataset.getValue(i, 1)]);
    }
}
var options = {
    backgroundColor: '#ffd',
    enableInteractivity: false, // select, on/off events wont cause normal action i.e. bar color change
    hAxis: {
        format: 'HH:mm',
        minValue: minTime,
        maxValue: maxTime
    },
    height: chartHeight,
    width: chartWidth,
    colors: colors
};
var chart = new google.visualization.Timeline(document.getElementById(renderedTo));
var view = new google.visualization.DataView(dataset);
view.setColumns([0, 1, 2, 3]);
var container = document.getElementById(renderedTo);

google.visualization.events.addListener(chart, 'ready', function () {
    // set original color
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" &&
            bar.getAttribute('fill') != "#ffffdd" &&
            index < (bars.length - 1)) {
                var textElem = bar.nextSibling;
                bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
        }
    });
});

google.visualization.events.addListener(chart, 'onmouseover', function (e) {
    // set original color
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" &&
            bar.getAttribute('fill') != "#ffffdd" &&
            index < (bars.length - 1)) {
                var textElem = bar.nextSibling;
                if (textElem == null) {
                    bars[index].setAttribute('fill', "#ffffff");
                }
                else {
                    bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
                }
        }
    });
});

google.visualization.events.addListener(chart, 'onmouseout', function (e) {
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" && // pohjaväri 1
            bar.getAttribute('fill') != "#ffffdd" && // pohjaväri 2
            index < (bars.length - 1)) {             // viimeinen aikajana bar
                var textElem = bar.nextSibling;
                if (textElem == null) {
                    bars[index].setAttribute('fill', "#ffffff");
                }
                else {
                    bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
                }
        }
    });
});
chart.draw(dataset, options);
}

mardi 21 mars 2017

Binding IEnumerable in ViewModel not working

I have a ViewModel - Customer. Within this there is an IEnumerable collection:

public class Tag
{
    public int TagNo{ get; set; }
    public DateTime CreatedDate { get; set; }
}

I output a list of tags to the page - along with the scalar customer information - using a foreach:

...output customer info....
<div class="col-md-9">
    @{
        foreach (var Tag in Model.Tags)
        {
            @Html.DisplayFor(x => Tag.TagNo);
            <br />
        }
    }
</div>

I am attempting to hide the tag list in the page for the model binder so on errors I don't need to hit the database again:

@{
    int[] tagArray = Model.Tags.Select(x => x.TagNo).ToArray();

    for (int i = 0; i < Model.Tags.Count(); i++)
    {
        @Html.Hidden("Tags[" + i + "]", tagArray[i])
    }
}

This outputs this:

<input id="Tags_0_" name="Tags[0]" type="hidden" value="21111111" />
etc

I have seen various questions on SO saying you can use an array (as above) in a certain format that the model binder will understand for binding lists - eg: Creating HiddenFor IEnumerable<String> in View

However, when the page has an error and I use the debugger to see what has been bound on the post, Although model.tags appears to have 3 elements - they are all empty.

I have also tried this:

@Html.Hidden("Tags[" + i + "].TagNo", tagArray[i])

But the Customer.Tags collection is empty after posting.

What am I doing wrong? How can I hide this list of tags in the page so that the model binder will see it?

How to make return to the current url to stay the same or should not postback after executing from an ActionResult method?

I have an actionresult which I used to call for saving something as shown below

  public async Task<ActionResult> GenerateData() 
    {
     //...my code to save something here

    return ???? // from here, after executing the statements above, 
// I want to return to the current url which should not post back and will just stay the same so that the user's inputs will remain. 

    }

In this case, my current url here that I want to stay the same is Home/Index. By looking at the code sample I shown above with its comment, how do I achieve this in order for me to return to the current url which will not postback or will stay the same after executing the statements before the return command? Thanks

lundi 20 mars 2017

Common function in razor view to generate drop down in multiple view pages

I have page which contains multiple dropdowns with option like

<option>1<option>
<option>2<option>
<option>3<option>

and

<option>-5<option>
<option>-6<option>
<option>-7<option>

so i have created in a function to generate dropdown options in razor view.

 @functions {
        public List<SelectListItem> GenerateDropDown(int startvalue, int endValue)
        {
            var dropDownList = new List<SelectListItem>();
            for (int i = startvalue; i <= endValue; i++)
            {
                string val = i.ToString();
                dropDownList.Add(new SelectListItem { Text = val, Value = val });
            }
            return dropDownList;
        }
}

and using like this

 @Html.DropDownListFor(m => m.xyz, GenerateDropDown(1, 10))
 @Html.DropDownListFor(m => m.Abc, GenerateDropDown(2, 20))

this work fine but i want use the same function in multiple pages with out code duplication i tried using helper method but no use can any one suggest me how to centralize GenerateDropDown function.

samedi 18 mars 2017

System.NullReferenceException: Object reference not set to an instance of an object.

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        try
        {
            int keyvalue = Convert.ToInt32(e.CommandArgument);
            //TextBox1.Text = keyvalue.ToString();
            con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand("spDelete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PatientId", keyvalue);

            cmd.ExecuteNonQuery();

            //da = new SqlDataAdapter(cmd);

            //GridView1.DataBind();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }


    }
}
trying to delete selected row but this error

System.NullReferenceException: Object reference not set to an instance of an object. at HospitalManagement.Edit.GridView1_RowCommand(Object sender, GridViewCommandEventArgs e) in C:\Users\sac\documents\visual studio 2015\Projects\HospitalManagement\HospitalManagement\Edit.aspx.cs:line 93

at cmd.commandType......... so help me

jeudi 16 mars 2017

Pass List as parameter to MVC controller

I try to do a thing I do everywhere in my code and for an unknown reason I can't do here.

I try to pass a list of object to my controller but I can't map my array into my list.

View :

var interventions = [
    {
        Id: 1,
        Title: 'Intervention 1',
        ToDoBefore: new Date(),
        PlannedDate: new Date()
    },
    {
        Id: 2,
        Title: 'Intervention 2',
        ToDoBefore: new Date(),
        PlannedDate: new Date()
    },
]

$.ajax({
    url: '/Home/AffectToSubcontractors',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(interventions),
    success: function (result) {
        debugger;
    }
});

Controller :

    public PartialViewResult AffectToSubcontractors(List<SelectedInterventionsViewModel> interventions)
    {
        // Do something
    }

Model :

public class SelectedInterventionsViewModel
{
    public int Id { get; set; }

    public string Title { get; set; }

    public DateTime ToDoBefore { get; set; }

    public DateTime PlannedDate { get; set; }
}

What I miss ?

Asp.MVC custom handle error attribute does not work with Castle Windsor DI

I am working on an ASP.NET MVC application. I have used Castle Windsor for DI and have created a custom handler error attribute to handle errors in controllers.

I have created a custom windsor controller factory to use the DI. Now the issue is, with castle windsor, the custom error handler attribute code is never called, and I directly get the yellow screen of error.

When an error occurs in the controller, the error bubbles up to GetControllerInstance() method of WindsorControllerFactory, and then it never reaches the custom error handler of MVC.

Can anyone help me, how can I get the custom handle error attribute to work?

Please Note: Without the DI setup, the custom error handler works like charm

public override void OnException(ExceptionContext exceptionContext)
{
    var controllerName = (string)exceptionContext.RouteData.Values["controller"];
    var actionName = (string)exceptionContext.RouteData.Values["action"];
    var model = new HandleErrorInfo(exceptionContext.Exception, controllerName, actionName);

    exceptionContext.Result = new ViewResult
    {
        ViewName = View,
        MasterName = Master,
        ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
        TempData = exceptionContext.Controller.TempData
    };

    exceptionContext.ExceptionHandled = true;
    exceptionContext.HttpContext.Response.Clear();
    exceptionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

    exceptionContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}


public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IKernel kernel;

    public WindsorControllerFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public override void ReleaseController(IController controller)
    {
        kernel.ReleaseComponent(controller);
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
        }
        return (IController)kernel.Resolve(controllerType);
    }
}

public class MvcApplication : System.Web.HttpApplication
{
    private static IWindsorContainer container;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        InitializeContainer();
    }

    private static void InitializeContainer()
    {
        container = new WindsorContainer()
            .Install(FromAssembly.This());
        var controllerFactory = new WindsorControllerFactory(container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    protected void Application_End()
    {
        container.Dispose();
    }
}

mercredi 15 mars 2017

How to Pass parameter to partiaView with return View(.....)

Iam totaly new mvc programmer and have some problem with my code. From my controller calling/returning to a partial view like that..and its working: Below is my code:

return View("~/Views/Partials/_CarModels.cshtml, new RenderModel(carsrent) );

I want now to pass a parameter color to partialview, i have tryed this and i get Error

return View("~/Views/Partials/_CarModels.cshtml?color=red", new RenderModel(carsrent) );

What is worong ?

mardi 14 mars 2017

How can I save a List in ASP.NET

I would like to know how can I save a List (many column) instead of one column in ASP.NET, THANKS!!

    public ActionResult Audit(int? id)
    {
        var tQ = from t in db.TR.Include("SInfo")
                        where t.SId == id 
                        orderby t.SId, t.Tid
                        select t;

        var list = tQ.ToList();
        return View(list);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Audit(TrainingRecord list)
    {
        if (ModelState.IsValid)
        {
            db.Entry(list).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Audit");
        }
        return View(list);
    }

I cannot save by this two contollers, is something missing or wrong in the controller or view?

Grid.Column if(else) two Grid.Column

I need to do something like this - if() - then grid.Column - else - then 1)grid.Column first and 2)grid.Column second

Now, I have this

grid.Column(header: "", format: @<text>@if (item.ListStatus != 1)
                                                   {
                                                       <button id='Resend' class='btn btn_green_resend'>Resend</button>
                                                   }
                                                   else
                                                   {
                                                   @*first column*@<a href=mailto: @item.Email class='btn btn-default' title='Send Email'><span class='glyphicon glyphicon-envelope text-primary' aria-hidden='true'></span></a>
                                                   @*second column*@<button type='button' title='Chat' class='btn btn-default' data-toggle='modal' data-target='#mdlConversation' data-interlocutorid=@item.UserId data-interlocutorname=@item.Name><span class='glyphicon glyphicon-comment text-primary' aria-hidden='true'></span></button>

            }
 </text>),

dimanche 12 mars 2017

what will happen if an asp.net project application is hosted in a hosting site got errors?

like in a localhost if errors occur a message will pop-up like data is null etc and you will just relaunch the application to be use again. what if it is already hosted in a hosting site what will happen to the application do a user will re upload again the application files in the hosting site? example of this error is like this http://ift.tt/2niTvt4 ( "can't upload picture in stack overflow just paste the URL link in the link bar to view" ) i'm just asking i'm very new in developing i'm just confused please dont be mad.

samedi 11 mars 2017

Url.Action to Html.Raw

I have this code om my View. And this is work good.

... onclick="location.href = '@Url.Action("Plan", "Care", new {Area = "HomeC"})'">

How Can I do the same code with Html.Raw? I tried this

...onclick= ' location.href = " + " ' " + Url.Action("Plan", "Care", new {Area = "HomeC"}) + " ' ' >" + "

With image all good, but link doesn't work. P.S. I added spaces that you can see where I put a single quotes

how to auto sum or automatically calculate when value is inputted in @html.editor

i have 5 property in the the table its score1 - score5 which are using @html.editor, how can i autosum all value inputted in the @html.editor which will be seen in my other property TotalScore? and it should automatically calculate without submiting or pressing the submit button.

vendredi 10 mars 2017

MVC: Trigger loading GIF when controller is processing

I got a loading gif feature in my ajax call. In all ajax call, I can trigger the loading gif.

But I want the loading gif to be triggered when I trigger a process in a controller too. The controller function is not being triggered by ajax call so my loading gif is not showing.

Is there any way I can trigger loading gif when controller is processing?

MVC 3 - Find script/method which fires PopUp

I know it is very basic question here but I am clueless. Since I am new to MVC I am unable to find out the script/method which fires PopUp menu.

In MVC3 application when I move my cursor over menu a PopUp list appears and I tried Google Chrome's Developers tool to find out how the PopUp appears but could not figure out.

Is there any tool or debugging mechanism available to find out which Script/Method fires Pop-Up screen.

DeserializeObject or Cast object from controller?

I have a Controller that deserialize the request in the following way;

public ActionResult ControlPartial() {
           Dictionary<string, object> modelState = (Dictionary<string, object>)new JavaScriptSerializer().DeserializeObject(Request.Params["ControlState"]); 
            SomeObject model = ControlModelFactory.CreateInstance(modelState );
            return PartialView("ControlPartial", model);
        }


 public static class ControlModelFactory{
         public static SomeObject CreateInstance(Dictionary<string, object> controlState){
           //Here is the Question! How I can deserialize or cast the controlState to SomeObject.
           return new SomeObject(){....};
             }
}

public class SomeObject{
 public int Width { get; set; }
 public Diccionari<string,Serie>{ get; set; }
}

public class Serie{
    public int ViewType { get; set; }
}

In my Request.Params["ControlState"] I have;

  • [0] {[Width, 0]} System.Collections.Generic.KeyValuePair
  • [1] {[Series,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair

     And Inside of the Series the following Value; 
     +        [0] {[serie1,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair<string,object>
                     +      [0] {[ViewType, 9]} System.Collections.Generic.KeyValuePair<string,object>
    
     +        [1] {[serie2,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair<string,object>
                     +      [1] {[ViewType, 11]}    System.Collections.Generic.KeyValuePair<string,object>
    
    

As you can see, from the client I get the JSON: {'Width':0, 'Series':{'serie1':{'ViewType':9},'serie2':{'ViewType':11}}}

What is the best method and how to convert from the controlstate to the object SomeObject? One problem is that I can not change the input parameter types.And I have to do the conversion inside CreateInstance.

mercredi 8 mars 2017

Date Time null in database

As my title above I got a table in my database that is DateTime datatype and it is null value. And I got this line of code that I am using but I don't know why that it is returning 12:00

string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");

So as you can see in my code If the value of datetime is null I want to display 00:00 and if it is not null it will display the current value.

NOTE

12 Hours Format

mardi 7 mars 2017

Mapped Folder Not Working On Publish

I am creating an web application. I have to show one attachment in a button click.The attachment file resides on another server which is in the same network. when i make the coding its works well in my development machine, but when i deploy it does not work.

i am deploying the application in 192.168.a.xyz server and the mapped folder is in 192.168.a.ijk.

i have used the below code which works well in the development machine which is also in the same network.

public ActionResult GetCorporateInvoiceCopy(string attachId)
        {
            if (attachId.Length > 0)
            {
                try
                {
                    string FileExtension = ".pdf";
                    string csvPath = "";
                    string inv = attachId;
                    csvPath = @"\\192.168.a.ijk\\Attached_Files\" + Path.GetFileName(inv.ToString() + FileExtension );
                    return File(csvPath, FileExtension);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return null;
            }
        }

Appreciate if anybody can help!

Capturing parts of MVC Views

I am capturing parts of MVC views like so:

<% using(Html.BeginScriptWrapper()) { %>
<script type="text/javascript">
    alert("Test : <%: DateTime.Now %>");
</script>
<% } %>

The code of HtmlHelper extension:

public static class HelperScriptWrapper
{
  public static IDisposable BeginScriptWrapper(this HtmlHelper anHtml)
  {
    return new ScriptWrapper(anHtml);
  }

  class ScriptWrapper : IDisposable
  {
    private HtmlHelper fHtml;
    private TextWriter fOldWriter;
    private StringWriter fNewWriter;

    private TextWriter ReplaceInnerWriter(TextWriter aReplacement)
    {
      TextWriter writer = fHtml.ViewContext.HttpContext.Response.Output;
      PropertyInfo propInfo = writer.GetType().GetProperty("InnerWriter",
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

      TextWriter oldWriter = propInfo.GetValue(writer, null) as TextWriter;
      propInfo.SetValue(writer, aReplacement, null);

      return oldWriter;
    }

    public ScriptWrapper(HtmlHelper anHtml)
    {
      fHtml = anHtml;
      fNewWriter = new StringWriter();
      fOldWriter = ReplaceInnerWriter(fNewWriter);
    }

    public void Dispose()
    {
      ReplaceInnerWriter(fOldWriter);
      string result = fNewWriter.GetStringBuilder().ToString();
      // store result to use later
    }
  }
}

Reflection is used to replace InnerWriter above with my StringWriter.

Is there a proper (ASP.NET MVC by-design) way to do this without reflection? That is to redirect content that goes to Response.Output in the middle of the view.

Not showing the id in the screen when hovering

I am using leaflet and mapbox and I use the function to print the id nuber on the screen when hovering over the line in the map.

geojson = L.geoJson(lines, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};


info.update = function (props) {
    this._div.innerHTML = '<h4><b>Links<b></h4>' +  (props ?
        '<b>Link' + props.id + '</b><br />'  
        : 'Hover over a link');


};

info.addTo(map);

The way I draw the line is by the following geoJSON file

var lines = {
    "type": "FeatureCollection",
    "features": [{
        "type": "LineString",
        "coordinates": [
            [103.85, 1.28992],
            [103.89, 1.294],
            [103.83, 1.216]
        ],
        "properties": { "id": "1" }
    }, {
        "type": "LineString",
        "properties": { "id": "2" },
        "coordinates": [
            [103.5, 1.292],
            [103.9, 1.4],
            [103.3, 1.21]
        ]
    }, {
        "type": "LineString",
        "properties": { "id": "3" },
        "coordinates": [
            [103.6, 1.291],
            [103.6, 1.39],
            [103.3, 1.29]
        ]
    }]
};

but when i hover over the line it shows "undefined" instead of showing the id.Any help is appreciated

Calculate center coordinates, zoom, and stops of the layer dynamically

Below is my code to display a base map, set center coordinates and zoom level to show Ghana in view-port and also style/ color the ghana map for NDVI property of my source layer (mapbox hosted tileset) ghanaNDVILayer.

 mapID='myMapID';
    mapboxgl.accessToken = 'accessToken';

    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        center: [-1.41, 6.32],
        zoom: 5
    });

    map.on('load', function () {
        map.addLayer({
            'id': 'main',
            'type': 'fill',
            'layout': {},
            'paint': {
                'fill-color': {
                  property: 'NDVI',
                    stops: [
                        [0, '#F2F12D'],
                        [1, '#EED322'],
                        [2, '#E6B71E'],
                        [3, '#DA9C20'],
                        [4, '#CA8323'],
                        [5, '#B86B25'],
                        [6, '#A25626'],
                        [7, '#8B4225'],
                        [8, '#723122']
                    ]
                },
                'fill-opacity': 0.8
            },
            'source': {
                'type': 'vector',
                'url': 'mapbox://' + mapID
            },
           "source-layer": "ghanaNDVILayer",
        });
    });

Now if you see in above code I've hard coded the center coordinates, zoom level and stops array which is typical for this Ghana NDVI trends example.

Now, this approach is fine when I am dealing with only one data source (in this case ghana data source) but I can't hard code these values as my data source could change and could be any region of the world and the property could also be anything other than NDVI.

I am using mapbox hosted tilesets as the data source, but I also have the original geoJson data source on my server.

Is there any way in Mapbox to calculate center, zoom and stops dynamically depending on the source we are loading?

The other approach I thought is to pass the tileset source Id to my server and locate the original geoJSON and using that calculate the center, zoom and stops on the server and then pass these values to my client and then render the map in the js.

Let me know what is the best way to calculate these values dynamically.

Mapbox data with google sheets

I am working to develop a crowdsourcing website that takes input from google forms and displays this information on a map. I am working with mapbox and am looking for a way to get the data points in my google spreadsheet (with lat/long info) to automatically show up on the map. Any tips would be appreciated, thanks!

Drawing annotations over mapbox map

I am using Mapbox as my mapping library. I am trying to add a functionality where after the map has been rendered completely, the user can draw an annotation and add a comment for it (see image). Now, these annotation details (drawn line coordinates and message) should be saved into my GeoJSON, so that next time when the user reloads the map, it should show the same annotation.

Now I didn't find native support in mapbox for annotation. So not sure how to implement this.

Is there any way to draw annotations over the map after the map is rendered?

enter image description here

lundi 6 mars 2017

jquery 1.4.2 and chrome.. detecting a check box is checked....How?

So for reasons beyond my control, I'm using jquery 1.4.2 and chrome..

I'm having a ludicrous amount of trouble trying to get detecting a check box is checked....working...

Here is what I have...

HTMl generated by asp.net Mvc3

<input type="checkbox" name="criteriaVm.WasApproved" id="criteriaVm.WasApproved">

Various versions I've tried

            var ob = $("#criteriaVm.WasApproved");// is valid
            var chk = ob.attr('checked'); // undefined
            //chk = ob.prop('checked');//crash
            //chk = ob.get(0).checked;//crash
            //chk = ob.get(0).is(":checked");//crash

I've tried others before I started keeping track to make sure I wasn't just going in circles...

Does anyone know what version works on the old school jquery i'm, stuck with?

samedi 4 mars 2017

ASP.NET MVC how can i display users information from active directory but not in the list of principal

ASP.NET MVC, how can i display users information from active directory but not in the list of principal ??

For example, I want to display users mobile number but mobile attribute is not in the list of user principal.

Also I would like to set a pin code for all users i asked someone in the team to create the field in the ACTIVE DIRECTORY as pin code. so basically it is a new field will be created. How can i add it also to the list of user principal and allow users to set it? please Note that i'm new to ASP.NET MVC

Thanks

jeudi 2 mars 2017

i'm having trouble putting set of value to the actionlink using mvc

    @Html.ActionLink("LecturePage", "Lecture", new { id=item.LectureId })

i want to set some values in the item.lectureId, like set the value of item.lectureId to 1 or 2 or 3 or etc. How can i do it? please do help me.

mercredi 1 mars 2017

How to change dropdown list to multiselect dropdown list

I have dynamically populated dropdown list, which I have tried to change to support multiselection. I have tried change the Html.DropDownList to ListBox, SelectList to MultiSelectList and html attribute: new { multiple = "multiple" }. But just cant get this to work. Can you help me?

Dynamically populate the dropdownlist:

$.post('<%= Url.Action("Groups", "Units") %>', { unitId: $('#UnitId').val() }, function (data) {
    $('#Groups').html('<option value="null">Select group</option>');
    $.each(data.list, function (index, element) {
        $('#Groups').append('<option value="' + element.Id + '">' + element.Name + '</option>');
        $('#li-group > .fade').hide();
    });
});

Show the dropdown list:

<!-- Group dropdown list -->
<li id="li-group">
    <div class="fade"></div>
    <%= @Html.DropDownList("Groups", new SelectList (new List<Object> { new { value = "null", text = "Select group" } }, "value", "text" )) %>
</li>

Send the selection to controller:

$('#page-content > .wrapper').load(url, { Group: $('#Groups').val() });

public ActionResult GroupSelection(string Group)

Tried to change this to:

$('#page-content > .wrapper').load(url, { Group: $('#Groups option:selected').val() });

public ActionResult GroupSelection(List<string> Group)

or

public ActionResult GroupSelection(string[] Group)

Capturing parts of MVC Views

I am capturing parts of MVC views like so:

<% using(Html.BeginScriptWrapper()) { %>
<script type="text/javascript">
    alert("Test : <%: DateTime.Now %>");
</script>
<% } %>

The code of HtmlHelper extension:

public static class HelperScriptWrapper
{
  public static IDisposable BeginScriptWrapper(this HtmlHelper anHtml)
  {
    return new ScriptWrapper(anHtml);
  }

  class ScriptWrapper : IDisposable
  {
    private HtmlHelper fHtml;
    private TextWriter fOldWriter;
    private StringWriter fNewWriter;

    private TextWriter ReplaceInnerWriter(TextWriter aReplacement)
    {
      TextWriter writer = fHtml.ViewContext.HttpContext.Response.Output;
      PropertyInfo propInfo = writer.GetType().GetProperty("InnerWriter",
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

      TextWriter oldWriter = propInfo.GetValue(writer, null) as TextWriter;
      propInfo.SetValue(writer, aReplacement, null);

      return oldWriter;
    }

    public ScriptWrapper(HtmlHelper anHtml)
    {
      fHtml = anHtml;
      fNewWriter = new StringWriter();
      fOldWriter = ReplaceInnerWriter(fNewWriter);
    }

    public void Dispose()
    {
      ReplaceInnerWriter(fOldWriter);
      string result = fNewWriter.GetStringBuilder().ToString();
      // store result to use later
    }
  }
}

Reflection is used to replace InnerWriter above with my StringWriter.

Is there a proper (ASP.NET MVC by-design) way to do this without reflection?

Do I have to learn asp.net before learning mvc

I am planning to learn mvc but i'm just wondering should i learn asp.net first ? Will it be easy to learn mvc after learning asp.net ?

mardi 28 février 2017

C# MVC upload CSV file & import it to SQL server by creating table dynamically

I have a requirement where we need to import data from a .csv file to SQL server by creating the table dynamically. The reason for dynamic table creation is because the .csv file will have columns changing. We have to drop the existing table & recreate a new table based on the header information in the .csv file. (user may be running some diagnostic queries on that table later on)

I'm using C#.net MVC-3 & SQL Server 2014 standard version.Please let me know the best possible ways of achieving this.

Thank you.

How to set Max on input text using angular JS

I want to set max value for an amount field using angular JS

If i enter value > 10 i want to display an error message next to the textbox. Since type="text" it is not working like number.

<input type="text" name="input" ng-model="example.value"   ngmin="0" ngmax="10" >

dimanche 26 février 2017

Google Analytics - Universal Analytics tracking two environments

I am using Google's Universal Analytics in MVC application for Page visits tracking purpose. I have three environments(i.e, Dev , Test & UAT) to test my code and as a primary user I have access to all three environments.

After initial test the code has been moved to Test environment from Dev environment. And again the code has been moved to UAT environment. Now the code resides in all three environments.

In my google analytics website, I have given UAT environment URL(domain name) alone for tracking purpose but now the problem is, when I login into Test and UAT environments it tracks both. When I navigate to different page in Test environment it tracks my navigation page.

As I mentioned above, I have given UAT domain name in GA website. And I want to track UAT alone and not other environments.

Do I need to configure any settings in Google Anlytics website?

Any suggestion please. Thanks in advance.

vendredi 24 février 2017

Trigger for multiplication of one table vale into another table value

This will be displayed in a monospaced font. The first four spaces will be stripped off, but all other whitespace will be preserved.

Markdown and HTML are turned off in code blocks:
<i>This is not italic</i>, and [this is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

The $ character is just a shortcut for window.jQuery. If you want to have a preformatted block within a list, indent by eight spaces:

  1. This is normal text.
  2. So is this, but now follows a code block:

    Skip a line and indent eight spaces.
    That's four spaces for the list
    and four to trigger the code block.  I have two tables 
    
    

    FirstTable is

    Id || EB || EBC || DG || DGCost

    1 || 10 || Null || 10 || Null 1 || 5 || Null || 20 || Null 2 || 20 || Null || 10 || Null

    and Second Table Is

    Id || EbCost || DGCost

    1 || 2 || 3

    2 || 3 || 6

    and when i insert values in firsttable these (EbCost,DGCost)values multiply with secondtable (EB,DG) and the reult will be update in (EBC,DGC) columns corresponding with ID final output look like

    Id || EB || EBC || DG || DGC

    1 || 10 || (10*2)=20 || 10 || 30

    1 || 5 || 10 || 20 || 60

    2 || 20 || 60 || 10 || 30


    I need Query Urgently.. can any one help me here

jeudi 23 février 2017

Prevent javascript execution during page refresh

In MVC application CSHTML page, I have some set of JavaScripts which performs some calculation based on page hits but I do not want to perform calculation during page refresh.

How to ignore script execution during page refresh?

mercredi 22 février 2017

How to get FileStreamResult Output

I have a program I'm modifying that is basically a delivery schedule website using ASP.NET MVC3. The addition I'm giving the site is the ability to print a manifest (it can already print a delivery schedule) but I've run into a snag which would be my lack of understanding. Basically I have it setup so when a user pushes the button it makes a call to populate the manifest. All I need to do now is print it to PDF using FileStreamResult (there's a method already in place for this) I'm just not sure how to get the output from my PrintShippingManifest method to return something a FileStreamResult method can use.

I've tried googling and searching this site, but I'm now into information overload and could use some direction.

Here's the PrintShippingManinfest in the controller:

  public JsonResult PrintShippingManifest(int id)
        {
            var _manifest = new List<ShippingManifestRootJSON>();
            FillShippingManifest(_manifest, id);
            return Json(new { result = "success", message = "OK" });
        }
        [HttpPost]

And this method as well:

 private void FillShippingManifest(List<ShippingManifestRootJSON> manifest, int id) //added by Chad
        {
            using (var tx = dbSession.BeginTransaction())
            {
                try
                {
                    var shipItems = dbSession.CreateCriteria<ShippingItem>()
                                .Add(Restrictions.Eq("DeliveryTicket.Id", id))
                                .AddOrder(Order.Asc("DeliveryOrder"))
                                .List<ShippingItem>();

                    foreach (var _item in shipItems)
                    {
                        var _root = manifest.Find(x => x.JobNumber == _item.JobNumber);
                        if (_root == null)
                        {
                            _root = new ShippingManifestRootJSON() { JobNumber = _item.JobNumber, Name = _item.JobName, ID = _item.Id };
                            manifest.Add(_root);
                        }
                        var _manifestItem = Mapper.Map<ShippingManifestSectionJSON>(_item);

                        _root.Add(_manifestItem);
                    }

                    foreach (var _job in manifest)
                    {
                        foreach (var _section in _job.Sections)
                        {
                            FillSectionWithData(_section);
                        }
                    }

                }
                catch (Exception ex)
                {
                    if (tx != null)
                        tx.Rollback();


                }
            }
        }